file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/rmpflow/robot_descriptor.yaml
api_version: 1.0 cspace: - joint1 - joint2 - joint3 - joint4 - joint5 - joint6 root_link: world default_q: [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ] cspace_to_urdf_rules: [] composite_task_spaces: []
224
YAML
15.071427
38
0.575893
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/rmpflow/mirrobot_rmpflow_common.yaml
joint_limit_buffers: [.01, .01, .01, .01, .01, .01] rmp_params: cspace_target_rmp: metric_scalar: 50. position_gain: 100. damping_gain: 50. robust_position_term_thresh: .5 inertia: 1. cspace_trajectory_rmp: p_gain: 100. d_gain: 10. ff_gain: .25 weight: 50. cspace_affine_rmp: final_handover_time_std_dev: .25 weight: 2000. joint_limit_rmp: metric_scalar: 1000. metric_length_scale: .01 metric_exploder_eps: 1e-3 metric_velocity_gate_length_scale: .01 accel_damper_gain: 200. accel_potential_gain: 1. accel_potential_exploder_length_scale: .1 accel_potential_exploder_eps: 1e-2 joint_velocity_cap_rmp: max_velocity: 1. velocity_damping_region: .3 damping_gain: 1000.0 metric_weight: 100. target_rmp: accel_p_gain: 30. accel_d_gain: 85. accel_norm_eps: .075 metric_alpha_length_scale: .05 min_metric_alpha: .01 max_metric_scalar: 10000 min_metric_scalar: 2500 proximity_metric_boost_scalar: 20. proximity_metric_boost_length_scale: .02 xi_estimator_gate_std_dev: 20000. accept_user_weights: false axis_target_rmp: accel_p_gain: 210. accel_d_gain: 60. metric_scalar: 10 proximity_metric_boost_scalar: 3000. proximity_metric_boost_length_scale: .08 xi_estimator_gate_std_dev: 20000. accept_user_weights: false collision_rmp: damping_gain: 50. damping_std_dev: .04 damping_robustness_eps: 1e-2 damping_velocity_gate_length_scale: .01 repulsion_gain: 800. repulsion_std_dev: .01 metric_modulation_radius: .5 metric_scalar: 10000. metric_exploder_std_dev: .02 metric_exploder_eps: .001 damping_rmp: accel_d_gain: 30. metric_scalar: 50. inertia: 100. canonical_resolve: max_acceleration_norm: 50. projection_tolerance: .01 verbose: false body_cylinders: - name: base pt1: [0,0,.333] pt2: [0,0,0.] radius: .05 body_collision_controllers: - name: Link6 radius: .05
2,266
YAML
28.441558
51
0.582083
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/rmpflow/denso_rmpflow_common.yaml
joint_limit_buffers: [.01, .01, .01, .01, .01, .01] rmp_params: cspace_target_rmp: metric_scalar: 50. position_gain: 100. damping_gain: 50. robust_position_term_thresh: .5 inertia: 1. cspace_trajectory_rmp: p_gain: 100. d_gain: 10. ff_gain: .25 weight: 50. cspace_affine_rmp: final_handover_time_std_dev: .25 weight: 2000. joint_limit_rmp: metric_scalar: 1000. metric_length_scale: .01 metric_exploder_eps: 1e-3 metric_velocity_gate_length_scale: .01 accel_damper_gain: 200. accel_potential_gain: 1. accel_potential_exploder_length_scale: .1 accel_potential_exploder_eps: 1e-2 joint_velocity_cap_rmp: max_velocity: 1. velocity_damping_region: .3 damping_gain: 1000.0 metric_weight: 100. target_rmp: accel_p_gain: 30. accel_d_gain: 85. accel_norm_eps: .075 metric_alpha_length_scale: .05 min_metric_alpha: .01 max_metric_scalar: 10000 min_metric_scalar: 2500 proximity_metric_boost_scalar: 20. proximity_metric_boost_length_scale: .02 xi_estimator_gate_std_dev: 20000. accept_user_weights: false axis_target_rmp: accel_p_gain: 210. accel_d_gain: 60. metric_scalar: 10 proximity_metric_boost_scalar: 3000. proximity_metric_boost_length_scale: .08 xi_estimator_gate_std_dev: 20000. accept_user_weights: false collision_rmp: damping_gain: 50. damping_std_dev: .04 damping_robustness_eps: 1e-2 damping_velocity_gate_length_scale: .01 repulsion_gain: 800. repulsion_std_dev: .01 metric_modulation_radius: .5 metric_scalar: 10000. metric_exploder_std_dev: .02 metric_exploder_eps: .001 damping_rmp: accel_d_gain: 30. metric_scalar: 50. inertia: 100. canonical_resolve: max_acceleration_norm: 50. projection_tolerance: .01 verbose: false body_cylinders: - name: base pt1: [0,0,.333] pt2: [0,0,0.] radius: .05 body_collision_controllers: - name: onrobot_rg6_base_link radius: .05
2,282
YAML
28.64935
51
0.583699
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/controllers/pick_place.py
from omni.isaac.manipulators.grippers.surface_gripper import SurfaceGripper import omni.isaac.manipulators.controllers as manipulators_controllers from .rmpflow import RMPFlowController from omni.isaac.core.articulations import Articulation # - Phase 0: Move end_effector above the cube center at the 'end_effector_initial_height'. # - Phase 1: Lower end_effector down to encircle the target cube # - Phase 2: Wait for Robot's inertia to settle. # - Phase 3: close grip. # - Phase 4: Move end_effector up again, keeping the grip tight (lifting the block). # - Phase 5: Smoothly move the end_effector toward the goal xy, keeping the height constant. # - Phase 6: Move end_effector vertically toward goal height at the 'end_effector_initial_height'. # - Phase 7: loosen the grip. # - Phase 8: Move end_effector vertically up again at the 'end_effector_initial_height' # - Phase 9: Move end_effector towards the old xy position. class PickPlaceController(manipulators_controllers.PickPlaceController): def __init__( self, name: str, gripper: SurfaceGripper, robot_articulation: Articulation, events_dt=None ) -> None: if events_dt is None: #These values needs to be tuned in general, you checkout each event in execution and slow it down or speed #it up depends on how smooth the movments are events_dt = [0.005, 0.002, 1, 0.05, 0.0008, 0.005, 0.0008, 0.1, 0.0008, 0.008] manipulators_controllers.PickPlaceController.__init__( self, name=name, cspace_controller=RMPFlowController( name=name + "_cspace_controller", robot_articulation=robot_articulation ), gripper=gripper, events_dt=events_dt, end_effector_initial_height=0.05, #This value can be changed # start_picking_height=0.6 ) return
1,930
Python
44.976189
118
0.674611
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/controllers/rmpflow.py
import omni.isaac.motion_generation as mg from omni.isaac.core.articulations import Articulation class RMPFlowController(mg.MotionPolicyController): def __init__(self, name: str, robot_articulation: Articulation, physics_dt: float = 1.0 / 60.0) -> None: # TODO: chamge the follow paths # # laptop # self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/MirobotFollowTarget/" # self._urdf_path = "/home/kimsooyoung/Downloads/Source/mirobot_ros2/mirobot_description/urdf/" # desktop self._desc_path = "/home/kimsooyoung/Downloads/source/RoadBalanceEdu/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/" self._urdf_path = "/home/kimsooyoung/Downloads/source/mirobot_ros2/mirobot_description/urdf/" self.rmpflow = mg.lula.motion_policies.RmpFlow( robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml", rmpflow_config_path=self._desc_path+"rmpflow/mirrobot_rmpflow_common.yaml", urdf_path=self._urdf_path+"mirobot_urdf_2.urdf", end_effector_frame_name="Link6", maximum_substep_size=0.00334 ) self.articulation_rmp = mg.ArticulationMotionPolicy(robot_articulation, self.rmpflow, physics_dt) mg.MotionPolicyController.__init__(self, name=name, articulation_motion_policy=self.articulation_rmp) self._default_position, self._default_orientation = ( self._articulation_motion_policy._robot_articulation.get_world_pose() ) self._motion_policy.set_robot_base_pose( robot_position=self._default_position, robot_orientation=self._default_orientation ) return def reset(self): mg.MotionPolicyController.reset(self) self._motion_policy.set_robot_base_pose( robot_position=self._default_position, robot_orientation=self._default_orientation )
1,955
Python
47.899999
131
0.691049
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/garage_conveyor.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.prims.geometry_prim import GeometryPrim from omni.isaac.examples.base_sample import BaseSample # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html from pxr import Sdf, UsdLux, Gf, UsdPhysics, PhysxSchema from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.utils.rotations import euler_angles_to_quat import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core import SimulationContext from omni.isaac.sensor import Camera from .geom_utils import createRigidBody, addObjectsGeom from .inference_utils import triton_inference import omni.replicator.core as rep import omni.graph.core as og import numpy as np import random import carb import omni import cv2 PROPS = { 'spam' : "/Isaac/Props/YCB/Axis_Aligned/010_potted_meat_can.usd", 'jelly' : "/Isaac/Props/YCB/Axis_Aligned/009_gelatin_box.usd", 'tuna' : "/Isaac/Props/YCB/Axis_Aligned/007_tuna_fish_can.usd", 'cleanser' : "/Isaac/Props/YCB/Axis_Aligned/021_bleach_cleanser.usd", 'tomato_soup' : "/Isaac/Props/YCB/Axis_Aligned/005_tomato_soup_can.usd" } class GarageConveyor(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self._nucleus_server = get_assets_root_path() self._bin_path = self._nucleus_server + "/Isaac/Props/KLT_Bin/small_KLT_visual.usd" self._bin_mass = 10.5 self._bin_scale = np.array([2.0, 2.0, 1.0]) self._bin_position = np.array([7.0, -0.2, 1.0]) self._plane_scale = np.array([0.4, 0.24, 1.0]) self._plane_position = np.array([-1.75, 1.2, 0.9]) self._plane_rotation = np.array([0.0, 0.0, 0.0]) self._gemini_usd_path = self._server_root + "/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Sensors/Orbbec/Gemini 2/orbbec_gemini2_V1.0.usd" self._gemini_position = np.array([-1.75, 1.2, 1.5]) self._gemini_rotation = np.array([0.0, 0.7071068, -0.7071068, 0]) self._sim_count = 0 self._is_captured = False return def add_background(self): self._world = self.get_world() bg_path = self._server_root + "/Projects/RBROS2/ConveyorGarage/Franka_Garage_Empty.usd" add_reference_to_stage(usd_path=bg_path, prim_path=f"/World/Garage") def add_camera(self): self._camera = Camera( prim_path="/World/normal_camera", position=np.array([-1.75, 1.2, 2.0]), frequency=30, resolution=(1280, 720), orientation=rot_utils.euler_angles_to_quats( np.array([ 0, 90, 180 ]), degrees=True), ) self._camera.set_focal_length(2.0) self._camera.initialize() self._camera.add_motion_vectors_to_frame() def add_bin(self, scene): add_reference_to_stage(usd_path=self._bin_path, prim_path="/World/inference_bin") createRigidBody(self._stage, "/World/inference_bin", False) self._bin_ref_geom = addObjectsGeom( scene, "inference_bin", self._bin_scale, self._bin_position, self._bin_mass, orientation=None ) def add_random_objects(self, scene, num_objects=3): choicelist = [random.choice( list(PROPS.keys()) ) for i in range(num_objects)] for _object in choicelist: prim_path = self._nucleus_server + PROPS[_object] prim_name = f"{_object}_{random.randint(0, 100)}" add_reference_to_stage(usd_path=prim_path, prim_path=f"/World/{prim_name}") createRigidBody(self._stage, f"/World/{prim_name}") position = ( random.uniform(6.8, 7.05), random.uniform(-0.3, -0.1), random.uniform(1.1, 1.3) ) prim_geom = addObjectsGeom( scene, prim_name, np.array([1.0, 1.0, 1.0]), position, 0.02 ) def add_light(self): distantLight = UsdLux.CylinderLight.Define(self._stage, Sdf.Path("/World/cylinderLight")) distantLight.CreateIntensityAttr(60000) distantLight.AddTranslateOp().Set(Gf.Vec3f(-1.2, 0.9, 3.0)) distantLight.AddScaleOp().Set((0.1, 4.0, 0.1)) distantLight.AddRotateXYZOp().Set((0, 0, 90)) def setup_scene(self): self._world = self.get_world() self._stage = omni.usd.get_context().get_stage() self.simulation_context = SimulationContext() self.add_background() self.add_light() self.add_camera() self.add_bin(self._world.scene) self.add_random_objects(self._world.scene, num_objects=3) self._scene = PhysicsContext() self._scene.set_physics_dt(1 / 30.0) return async def setup_post_load(self): self._world = self.get_world() self._world.scene.enable_bounding_boxes_computations() self._world.add_physics_callback("sim_step", callback_fn=self.physics_callback) #callback names have to be unique self._cur_bin_position, _ = self._bin_ref_geom.get_world_pose() self._prev_bin_position = self._cur_bin_position return def physics_callback(self, step_size): self._cur_bin_position, _ = self._bin_ref_geom.get_world_pose() bin_vel = np.linalg.norm(self._cur_bin_position - self._prev_bin_position) if self._cur_bin_position[1] > 1.1 and bin_vel < 1e-5 and not self._is_captured: print("capture image...") self._is_captured = True self._camera.get_current_frame() cur_img = self._camera.get_rgba()[:, :, :3] triton_inference(cur_img) else: # print(f"bin_vel: {bin_vel} / self._is_captured : {self._is_captured} / self._cur_bin_position[1]: {self._cur_bin_position[1]}") pass self._sim_count += 1 self._prev_bin_position = self._cur_bin_position async def setup_post_reset(self): await self._world.play_async() return def world_cleanup(self): self._world.pause() return
7,012
Python
37.745856
141
0.628066
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .garage_conveyor import GarageConveyor """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="Replicator", name="ReplicatorFactoryDemo", title="ReplicatorFactoryDemo", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=GarageConveyor(), ) return
2,076
Python
42.270832
135
0.743738
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/inference_utils.py
from tritonclient.utils import triton_to_np_dtype import tritonclient.grpc as grpcclient import cv2 import numpy as np from matplotlib import pyplot as plt inference_server_url = "localhost:8003" triton_client = grpcclient.InferenceServerClient(url=inference_server_url) model_name = "our_new_model" props_dict = { 0: 'klt_bin', 1: 'tomato_soup', 2: 'tuna', 3: 'spam', 4: 'jelly', 5: 'cleanser', } def triton_inference(image_bgr): target_width, target_height = 1280, 720 image_bgr = cv2.resize(image_bgr, (target_width, target_height)) image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) image = np.float32(image_rgb) # preprocessing image = image/255 image = np.moveaxis(image, -1, 0) # HWC to CHW image = image[np.newaxis, :] # add batch dimension image = np.float32(image) plt.imshow(image_rgb) # create input input_name = "input" inputs = [grpcclient.InferInput(input_name, image.shape, "FP32")] inputs[0].set_data_from_numpy(image) output_names = ["boxes", "labels", "scores"] outputs = [grpcclient.InferRequestedOutput(n) for n in output_names] results = triton_client.infer(model_name, inputs, outputs=outputs) boxes, labels, scores = [results.as_numpy(o) for o in output_names] # annotate annotated_image = image_bgr.copy() if boxes.size > 0: # ensure something is found for box, lab, scr in zip(boxes, labels, scores): if scr > 0.4: box_top_left = int(box[0]), int(box[1]) box_bottom_right = int(box[2]), int(box[3]) text_origin = int(box[0]), int(box[3]) border_color = list(np.random.random(size=3) * 256) text_color = (255, 255, 255) font_scale = 0.9 thickness = 1 # bounding box2 img = cv2.rectangle( annotated_image, box_top_left, box_bottom_right, border_color, thickness=5, lineType=cv2.LINE_8 ) print(f"index: {lab}, label: {props_dict[lab]}, score: {scr:.2f}") # For the text background # Finds space required by the text so that we can put a background with that amount of width. (w, h), _ = cv2.getTextSize( props_dict[lab], cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1 ) # Prints the text. img = cv2.rectangle( img, (box_top_left[0], box_top_left[1] - 20), (box_top_left[0] + w, box_top_left[1]), border_color, -1 ) img = cv2.putText( img, props_dict[lab], box_top_left, cv2.FONT_HERSHEY_SIMPLEX, 0.6, text_color, 1 ) final_img = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB) cv2.imwrite("/home/kimsooyoung/Documents/annotated_img.png", final_img)
3,145
Python
31.432989
109
0.539269
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/geom_utils.py
from omni.physx.scripts import utils from omni.isaac.core.prims.geometry_prim import GeometryPrim from pxr import Gf, PhysxSchema, Usd, UsdPhysics, UsdShade, UsdGeom, Sdf, Tf, UsdLux import numpy as np def createRigidBody(stage, primPath, kinematic=False): bodyPrim = stage.GetPrimAtPath(primPath) utils.setRigidBody(bodyPrim, "convexDecomposition", kinematic) def addObjectsGeom(scene, name, scale, ini_pos, mass, orientation=None): scene.add(GeometryPrim(prim_path=f"/World/{name}", name=f"{name}_ref_geom", collision=True)) geom = scene.get_object(f"{name}_ref_geom") if orientation is None: # Usually - (x, y, z, w) # But in Isaac Sim - (w, x, y, z) orientation = np.array([1.0, 0.0, 0.0, 0.0]) geom.set_local_scale(scale) geom.set_world_pose(position=ini_pos) geom.set_collision_approximation("convexDecomposition") geom.set_default_state(position=ini_pos, orientation=orientation) massAPI = UsdPhysics.MassAPI.Apply(geom.prim.GetPrim()) massAPI.CreateMassAttr().Set(mass) return geom
1,072
Python
37.321427
96
0.70709
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/inference/model_info.py
import tritonclient.grpc as grpcclient inference_server_url = "localhost:8003" triton_client = grpcclient.InferenceServerClient(url=inference_server_url) # find out info about model model_name = "our_new_model" config_info = triton_client.get_model_config(model_name) print(config_info)
290
Python
25.454543
74
0.793103
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/inference/inference.py
from tritonclient.utils import triton_to_np_dtype import tritonclient.grpc as grpcclient import cv2 import numpy as np from matplotlib import pyplot as plt inference_server_url = "localhost:8003" triton_client = grpcclient.InferenceServerClient(url=inference_server_url) model_name = "our_new_model" # load image data target_width, target_height = 1280, 720 image_bgr = cv2.imread("rgb_0055.png") # image_bgr = cv2.imread("rgb_0061.png") # image_bgr = cv2.imread("rgb_0083.png") image_bgr = cv2.resize(image_bgr, (target_width, target_height)) image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) image = np.float32(image_rgb) # preprocessing image = image/255 image = np.moveaxis(image, -1, 0) # HWC to CHW image = image[np.newaxis, :] # add batch dimension image = np.float32(image) plt.imshow(image_rgb) # create input input_name = "input" inputs = [grpcclient.InferInput(input_name, image.shape, "FP32")] inputs[0].set_data_from_numpy(image) output_names = ["boxes", "labels", "scores"] outputs = [grpcclient.InferRequestedOutput(n) for n in output_names] results = triton_client.infer(model_name, inputs, outputs=outputs) boxes, labels, scores = [results.as_numpy(o) for o in output_names] # annotate annotated_image = image_bgr.copy() props_dict = { 0: 'klt_bin', 1: 'tomato_soup', 2: 'tuna', 3: 'spam', 4: 'jelly', 5: 'cleanser', } if boxes.size > 0: # ensure something is found for box, lab, scr in zip(boxes, labels, scores): if scr > 0.4: box_top_left = int(box[0]), int(box[1]) box_bottom_right = int(box[2]), int(box[3]) text_origin = int(box[0]), int(box[3]) border_color = list(np.random.random(size=3) * 256) text_color = (255, 255, 255) font_scale = 0.9 thickness = 1 # bounding box2 img = cv2.rectangle( annotated_image, box_top_left, box_bottom_right, border_color, thickness=5, lineType=cv2.LINE_8 ) print(f"index: {lab}, label: {props_dict[lab]}, score: {scr:.2f}") # For the text background # Finds space required by the text so that we can put a background with that amount of width. (w, h), _ = cv2.getTextSize( props_dict[lab], cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1 ) # Prints the text. img = cv2.rectangle( img, (box_top_left[0], box_top_left[1] - 20), (box_top_left[0] + w, box_top_left[1]), border_color, -1 ) img = cv2.putText( img, props_dict[lab], box_top_left, cv2.FONT_HERSHEY_SIMPLEX, 0.6, text_color, 1 ) plt.imshow(cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)) plt.show()
2,945
Python
28.757575
105
0.582343
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/export/model_export.py
import os import torch import torchvision import warnings warnings.filterwarnings("ignore") device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') # load the PyTorch model. pytorch_dir = "/home/kimsooyoung/Documents/model.pth" model = torch.load(pytorch_dir).cuda() # Export Model dummy_input = torch.rand(1, 3, 1024, 1024).cuda() torch.onnx.export( model, dummy_input, "model.onnx", opset_version=11, input_names=["input"], output_names=["boxes", "labels", "scores"] )
527
Python
20.999999
83
0.698292
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/viz/data_visualize.py
import os import json import hashlib from PIL import Image import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches # # Desktop # data_dir = "/home/kimsooyoung/Documents/grocery_data_2024-05-21_18:52:00" # Laptop data_dir = "/home/kimsooyoung/Documents/grocery_data_2024-05-23_01:28:15" out_dir = "/home/kimsooyoung/Documents" number = "0025" # Write Visualization Functions # data_to_colour # takes in our data from a specific label ID and maps it to the proper color for the bounding box. def data_to_colour(data): if isinstance(data, str): data = bytes(data, "utf-8") else: data = bytes(data) m = hashlib.sha256() m.update(data) key = int(m.hexdigest()[:8], 16) r = ((((key >> 0) & 0xFF) + 1) * 33) % 255 g = ((((key >> 8) & 0xFF) + 1) * 33) % 255 b = ((((key >> 16) & 0xFF) + 1) * 33) % 255 inv_norm_i = 128 * (3.0 / (r + g + b)) return (int(r * inv_norm_i) / 255, int(g * inv_norm_i) / 255, int(b * inv_norm_i) / 255) # colorize_bbox_2d # takes in the path to the RGB image for the background, # the bounding box data, the labels, and the path to store the visualization. # It outputs a colorized bounding box. def colorize_bbox_2d(rgb_path, data, id_to_labels, file_path): rgb_img = Image.open(rgb_path) colors = [data_to_colour(bbox["semanticId"]) for bbox in data] fig, ax = plt.subplots(figsize=(10, 10)) ax.imshow(rgb_img) for bbox_2d, color, index in zip(data, colors, id_to_labels.keys()): labels = id_to_labels[str(index)] rect = patches.Rectangle( xy=(bbox_2d["x_min"], bbox_2d["y_min"]), width=bbox_2d["x_max"] - bbox_2d["x_min"], height=bbox_2d["y_max"] - bbox_2d["y_min"], edgecolor=color, linewidth=2, label=labels, fill=False, ) ax.add_patch(rect) plt.legend(loc="upper left") plt.savefig(file_path) # Load Synthetic Data and Visualize rgb_path = data_dir rgb = "rgb_"+number+".png" rgb_path = os.path.join(rgb_path, rgb) import os print(os.path.abspath(".")) # load the bounding box data. npy_path = data_dir bbox2d_tight_file_name = "bounding_box_2d_tight_"+number+".npy" data = np.load(os.path.join(npy_path, bbox2d_tight_file_name)) # load the labels corresponding to the image. json_path = data_dir bbox2d_tight_labels_file_name = "bounding_box_2d_tight_labels_"+number+".json" bbox2d_tight_id_to_labels = None with open(os.path.join(json_path, bbox2d_tight_labels_file_name), "r") as json_data: bbox2d_tight_id_to_labels = json.load(json_data) # Finally, we can call our function and see the labeled image! colorize_bbox_2d(rgb_path, data, bbox2d_tight_id_to_labels, os.path.join(out_dir, "bbox2d_tight.png"))
2,789
Python
31.823529
102
0.642524
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemo/train/fast_rcnn_train.py
from PIL import Image import os import numpy as np import torch import torch.utils.data import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torchvision import transforms as T import json import shutil epochs = 15 num_classes = 6 data_dir = "/home/kimsooyoung/Documents/grocery_data_2024-05-23_01:28:15" output_file = "/home/kimsooyoung/Documents/model.pth" device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') print(f"Using device: {device}") class GroceryDataset(torch.utils.data.Dataset): # This function is run once when instantiating the Dataset object def __init__(self, root, transforms): self.root = root self.transforms = transforms # In the first portion of this code we are taking our single dataset folder # and splitting it into three folders based on the file types. # This is just a preprocessing step. list_ = os.listdir(root) for file_ in list_: name, ext = os.path.splitext(file_) ext = ext[1:] if ext == '': continue if os.path.exists(root+ '/' + ext): shutil.move(root+'/'+file_, root+'/'+ext+'/'+file_) else: os.makedirs(root+'/'+ext) shutil.move(root+'/'+file_, root+'/'+ext+'/'+file_) self.imgs = list(sorted(os.listdir(os.path.join(root, "png")))) self.label = list(sorted(os.listdir(os.path.join(root, "json")))) self.box = list(sorted(os.listdir(os.path.join(root, "npy")))) # We have our three attributes with the img, label, and box data # Loads and returns a sample from the dataset at the given index idx def __getitem__(self, idx): img_path = os.path.join(self.root, "png", self.imgs[idx]) img = Image.open(img_path).convert("RGB") label_path = os.path.join(self.root, "json", self.label[idx]) with open(os.path.join('root', label_path), "r") as json_data: json_labels = json.load(json_data) box_path = os.path.join(self.root, "npy", self.box[idx]) dat = np.load(str(box_path)) boxes = [] labels = [] for i in dat: obj_val = i[0] xmin = torch.as_tensor(np.min(i[1]), dtype=torch.float32) xmax = torch.as_tensor(np.max(i[3]), dtype=torch.float32) ymin = torch.as_tensor(np.min(i[2]), dtype=torch.float32) ymax = torch.as_tensor(np.max(i[4]), dtype=torch.float32) if (ymax > ymin) & (xmax > xmin): boxes.append([xmin, ymin, xmax, ymax]) area = (xmax - xmin) * (ymax - ymin) labels += [json_labels.get(str(obj_val)).get('class')] label_dict = {} # Labels for the dataset static_labels = { 'klt_bin' : 0, 'tomato_soup' : 1, 'tuna' : 2, 'spam' : 3, 'jelly' : 4, 'cleanser' : 5 } labels_out = [] # Transforming the input labels into a static label dictionary to use for i in range(len(labels)): label_dict[i] = labels[i] for i in label_dict: fruit = label_dict[i] final_fruit_label = static_labels[fruit] labels_out += [final_fruit_label] target = {} target["boxes"] = torch.as_tensor(boxes, dtype=torch.float32) target["labels"] = torch.as_tensor(labels_out, dtype=torch.int64) target["image_id"] = torch.tensor([idx]) target["area"] = area if self.transforms is not None: img= self.transforms(img) return img, target # Finally we have a function for the number of samples in our dataset def __len__(self): return len(self.imgs) # Create Helper Functions # converting to `Tensor` objects and also converting the `dtypes`. def get_transform(train): transforms = [] transforms.append(T.PILToTensor()) transforms.append(T.ConvertImageDtype(torch.float)) return T.Compose(transforms) # Create a function to collate our samples. def collate_fn(batch): return tuple(zip(*batch)) # Create Model and Train # We are starting with the pretrained (default weights) object detection # fasterrcnn_resnet50 model from Torchvision. def create_model(num_classes): model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights='DEFAULT') in_features = model.roi_heads.box_predictor.cls_score.in_features model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) return model # create our dataset by using our custom GroceryDataset class # This is then passed into our DataLoader. dataset = GroceryDataset(data_dir, get_transform(train=True)) data_loader = torch.utils.data.DataLoader( dataset, # batch_size=16, batch_size=8, shuffle=True, collate_fn=collate_fn ) # create our model with the N classes # And then transfer it to the GPU for training. model = create_model(num_classes) model.to(device) params = [p for p in model.parameters() if p.requires_grad] optimizer = torch.optim.SGD(params, lr=0.001) len_dataloader = len(data_loader) # Now we can actually train our model. # Keep track of our loss and print it out as we train. model.train() ep = 0 for epoch in range(epochs): optimizer.zero_grad() ep += 1 i = 0 for imgs, annotations in data_loader: i += 1 imgs = list(img.to(device) for img in imgs) annotations = [{k: v.to(device) for k, v in t.items()} for t in annotations] loss_dict = model(imgs, annotations) losses = sum(loss for loss in loss_dict.values()) losses.backward() optimizer.step() print(f'Epoch: {ep} Iteration: {i}/{len_dataloader}, Loss: {losses}') torch.save(model, output_file)
5,909
Python
33.360465
84
0.616856
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNutsTable/nut_bolt_controller.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import typing import numpy as np from omni.isaac.core.controllers.base_controller import BaseController from omni.isaac.core.utils.rotations import euler_angles_to_quat, quat_to_euler_angles from omni.isaac.core.utils.stage import get_stage_units from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController from omni.isaac.franka.franka import Franka from omni.isaac.manipulators.controllers.pick_place_controller import PickPlaceController from .nut_vibra_table_controller import VibraFSM from .screw_controller import ScrewController class NutBoltController(BaseController): """ A state machine to tie nuts onto bolts with a vibrating table feeding the nuts - State 0: Pick and Place from pickup location on vibration table to different bolts - State 1: Screw nut onto bolt Args: name (str): Name id of the controller franka (Franka): Franka Robot """ def __init__(self, name: str, franka: Franka) -> None: BaseController.__init__(self, name=name) self._event = 0 self._franka = franka self._gripper = self._franka.gripper self._end_effector_initial_height = self._franka.get_world_pose()[0][2] + (0.4 / get_stage_units()) self._pause = False self._cspace_controller = RMPFlowController(name="pickplace_cspace_controller", robot_articulation=self._franka) pick_place_events_dt = [0.008, 0.005, 1, 0.1, 0.05, 0.01, 0.0025] self._pick_place_controller = PickPlaceController( name="pickplace_controller", cspace_controller=self._cspace_controller, gripper=self._gripper, end_effector_initial_height=self._end_effector_initial_height, events_dt=pick_place_events_dt, ) self._screw_controller = ScrewController( name=f"screw_controller", cspace_controller=self._cspace_controller, gripper=self._gripper ) self._vibraSM = VibraFSM() self._i = self._vibraSM._i self._vibraSM.stop_feed_after_delay(delay_sec=5.0) return def is_paused(self) -> bool: """ Returns: bool: True if the state machine is paused. Otherwise False. """ return self._pause def get_current_event(self) -> int: """ Returns: int: Current event/ phase of the state machine """ return self._event def forward( self, initial_picking_position: np.ndarray, bolt_top: np.ndarray, gripper_to_nut_offset: np.ndarray, x_offset: np.ndarray, ) -> np.ndarray: """Runs the controller one step. Args: initial_picking_position (np.ndarray): initial nut position at table feeder bolt_top (np.ndarray): bolt target position #""" _vibra_table_transforms = np.array([0.0, 0.0, 0.0]) if self.is_paused(): return _vibra_table_transforms offsetPos = self._vibraSM.update() _vibra_table_transforms = np.array(offsetPos, dtype=float) if self._vibraSM._state == "stop" and self._event == 0: initial_effector_orientation = quat_to_euler_angles(self._gripper.get_world_pose()[1]) initial_effector_orientation[2] = np.pi / 2 initial_end_effector_orientation = euler_angles_to_quat(initial_effector_orientation) actions = self._pick_place_controller.forward( picking_position=initial_picking_position + gripper_to_nut_offset, placing_position=bolt_top + np.array([x_offset, 0.0, 0.0]), current_joint_positions=self._franka.get_joint_positions(), end_effector_orientation=initial_end_effector_orientation, ) self._franka.apply_action(actions) if self._pick_place_controller.is_done(): self._vibraSM._set_delayed_state_change(delay_sec=1.0, nextState="backward") self._event = 1 if self._event == 1: actions2 = self._screw_controller.forward( franka_art_controller=self._franka.get_articulation_controller(), bolt_position=bolt_top, current_joint_positions=self._franka.get_joint_positions(), current_joint_velocities=self._franka.get_joint_velocities(), ) self._franka.apply_action(actions2) if self._screw_controller.is_paused(): self.pause() self._i += 1 return _vibra_table_transforms def reset(self, franka: Franka) -> None: """Resets the state machine to start from the first phase/ event Args: franka (Franka): Franka Robot """ BaseController.reset(self) self._event = 0 self._pause = False self._franka = franka self._gripper = self._franka.gripper self._end_effector_initial_height = self._franka.get_world_pose()[0][2] + (0.4 / get_stage_units()) self._pick_place_controller.reset(end_effector_initial_height=self._end_effector_initial_height) self._screw_controller.reset() return def pause(self) -> None: """Pauses the state machine's time and phase.""" self._pause = True return def resume(self) -> None: """Resumes the state machine's time and phase.""" self._pause = False return
5,896
Python
38.313333
120
0.633311
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNutsTable/screw_controller.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import typing import numpy as np from omni.isaac.core.articulations import Articulation from omni.isaac.core.controllers.articulation_controller import ArticulationController from omni.isaac.core.controllers.base_controller import BaseController from omni.isaac.core.utils.rotations import euler_angles_to_quat, quat_to_euler_angles from omni.isaac.core.utils.stage import get_stage_units from omni.isaac.core.utils.types import ArticulationAction from omni.isaac.manipulators.grippers.gripper import Gripper class ScrewController(BaseController): """ A state machine for screwing nuts on bolts Each phase runs for 1 second, which is the internal time of the state machine Dt of each phase/ event step is defined - State 0: Lower end_effector down to encircle the nut - State 1: Close grip - State 2: Re-Center end-effector grip with that of the nut and bolt - State 3: Screw Clockwise - State 4: Open grip (initiates at this state and cycles until limit) - State 5: Screw counter-clockwise Args: name (str): Name id of the controller cspace_controller (BaseController): a cartesian space controller that returns an ArticulationAction type gripper (Gripper): a gripper controller for open/ close actions. events_dt (typing.Optional[typing.List[float]], optional): Dt of each phase/ event step. 10 phases dt has to be defined. Defaults to None. Raises: Exception: events dt need to be list or numpy array Exception: events dt need have length of 5 or less """ def __init__( self, name: str, cspace_controller: BaseController, gripper: Gripper, events_dt: typing.Optional[typing.List[float]] = None, ) -> None: BaseController.__init__(self, name=name) self._event = 4 self._t = 0 self._events_dt = events_dt if self._events_dt is None: self._events_dt = [0.01, 0.1, 0.1, 0.025, 0.1, 0.05] else: if not isinstance(self._events_dt, np.ndarray) and not isinstance(self._events_dt, list): raise Exception("events dt need to be list or numpy array") elif isinstance(self._events_dt, np.ndarray): self._events_dt = self._events_dt.tolist() if len(self._events_dt) > 5: raise Exception("events dt need have length of 5 or less") self._cspace_controller = cspace_controller self._gripper = gripper self._pause = False self._start = True self._screw_position = np.array([0.0, 0.0, 0.0]) self._final_position = np.array([0.0, 0.0, 0.0]) self._screw_speed = 360.0 / 180.0 * np.pi self._screw_speed_back = 720.0 / 180.0 * np.pi return def is_paused(self) -> bool: """ Returns: bool: True if the state machine is paused. Otherwise False. """ return self._pause def get_current_event(self) -> int: """ Returns: int: Current event/ phase of the state machine """ return self._event def forward( self, franka_art_controller: ArticulationController, bolt_position: np.ndarray, current_joint_positions: np.ndarray, current_joint_velocities: np.ndarray, ) -> ArticulationAction: """Runs the controller one step. Args: franka_art_controller (ArticulationController): Robot's Articulation Controller. bolt_position (np.ndarray): bolt position to reference for screwing position. current_joint_positions (np.ndarray): Current joint positions of the robot. current_joint_velocities (np.ndarray): Current joint velocities of the robot. Returns: ArticulationAction: action to be executed by the ArticulationController """ if self._pause or self._event >= len(self._events_dt): target_joints = [None] * current_joint_positions.shape[0] return ArticulationAction(joint_positions=target_joints) if self._event == 0 and self._start: self._screw_position = np.copy(bolt_position) self._final_position = np.copy(bolt_position) self._start = False self._target_end_effector_orientation = self._gripper.get_world_pose()[1] if self._event == 0: franka_art_controller.switch_dof_control_mode(dof_index=6, mode="position") orientation_quat = self._gripper.get_world_pose()[1] self.orientation_euler = quat_to_euler_angles(orientation_quat) target_orientation_euler = np.array([self.orientation_euler[0], self.orientation_euler[1], -np.pi / 2]) target_orientation_quat = euler_angles_to_quat(target_orientation_euler) target_joints = self._cspace_controller.forward( target_end_effector_position=self._screw_position, target_end_effector_orientation=target_orientation_quat, ) if self._event == 1: self._lower = False franka_art_controller.switch_dof_control_mode(dof_index=6, mode="position") target_joints = self._gripper.forward(action="close") if self._event == 2: franka_art_controller.switch_dof_control_mode(dof_index=6, mode="position") orientation_quat = self._gripper.get_world_pose()[1] self.orientation_euler = quat_to_euler_angles(orientation_quat) target_orientation_euler = np.array([self.orientation_euler[0], self.orientation_euler[1], -np.pi / 2]) target_orientation_quat = euler_angles_to_quat(target_orientation_euler) finger_pos = current_joint_positions[-2:] positive_x_offset = finger_pos[1] - finger_pos[0] target_joints = self._cspace_controller.forward( target_end_effector_position=self._screw_position + np.array([positive_x_offset, 0.0, -0.001]), target_end_effector_orientation=target_orientation_quat, ) if self._event == 3: franka_art_controller.switch_dof_control_mode(dof_index=6, mode="velocity") target_joint_velocities = [None] * current_joint_velocities.shape[0] target_joint_velocities[6] = self._screw_speed if current_joint_positions[6] > 2.7: target_joint_velocities[6] = 0.0 target_joints = ArticulationAction(joint_velocities=target_joint_velocities) if self._event == 4: franka_art_controller.switch_dof_control_mode(dof_index=6, mode="position") target_joints = self._gripper.forward(action="open") if self._event == 5: franka_art_controller.switch_dof_control_mode(dof_index=6, mode="velocity") target_joint_velocities = [None] * current_joint_velocities.shape[0] target_joint_velocities[6] = -self._screw_speed_back if current_joint_positions[6] < -0.4: target_joint_velocities[6] = 0.0 target_joints = ArticulationAction(joint_velocities=target_joint_velocities) self._t += self._events_dt[self._event] if self._t >= 1.0: self._event = (self._event + 1) % 6 self._t = 0 if self._event == 5: if not self._start and (bolt_position[2] - self._final_position[2] > 0.0198): self.pause() return ArticulationAction(joint_positions=[None] * current_joint_positions.shape[0]) if self._start: self._screw_position[2] -= 0.001 self._final_position[2] -= 0.001 if bolt_position[2] - self._screw_position[2] < 0.013: self._screw_position[2] -= 0.0018 self._final_position[2] -= 0.0018 return target_joints def reset(self, events_dt: typing.Optional[typing.List[float]] = None) -> None: """Resets the state machine to start from the first phase/ event Args: events_dt (typing.Optional[typing.List[float]], optional): Dt of each phase/ event step. Defaults to None. Raises: Exception: events dt need to be list or numpy array Exception: events dt need have length of 5 or less """ BaseController.reset(self) self._cspace_controller.reset() self._event = 4 self._t = 0 self._pause = False self._start = True self._screw_position = np.array([0.0, 0.0, 0.0]) self._final_position = np.array([0.0, 0.0, 0.0]) self._screw_speed = 360.0 / 180.0 * np.pi self._screw_speed_back = 720.0 / 180.0 * np.pi # self._gripper = gripper if events_dt is not None: self._events_dt = events_dt if not isinstance(self._events_dt, np.ndarray) and not isinstance(self._events_dt, list): raise Exception("events dt need to be list or numpy array") elif isinstance(self._events_dt, np.ndarray): self._events_dt = self._events_dt.tolist() if len(self._events_dt) > 5: raise Exception("events dt need have length of 5 or less") return def is_done(self) -> bool: """ Returns: bool: True if the state machine reached the last phase. Otherwise False. """ if self._event >= len(self._events_dt): return True else: return False def pause(self) -> None: """Pauses the state machine's time and phase.""" self._pause = True return def resume(self) -> None: """Resumes the state machine's time and phase.""" self._pause = False return
10,293
Python
42.434599
146
0.61605
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNutsTable/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNutsTable/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .franka_nut_and_bolt import FrankaNutAndBolt """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ETRIDemo", name="FrankaNutsTable", title="FrankaNutsTable", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=FrankaNutAndBolt(), ) return
2,070
Python
42.145832
135
0.742029
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNutsTable/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNutsTable/franka_nut_and_bolt.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import numpy as np from omni.isaac.core.materials.physics_material import PhysicsMaterial from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.prims.geometry_prim import GeometryPrim from omni.isaac.core.prims.xform_prim import XFormPrim from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.prims import get_prim_at_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core import SimulationContext from omni.isaac.franka.franka import Franka from omni.isaac.sensor import Camera import omni.isaac.core.utils.numpy.rotations as rot_utils import omni.usd import h5py from pxr import Gf, PhysxSchema, Usd, UsdPhysics, UsdShade, UsdGeom, Sdf, Tf, UsdLux from .nut_bolt_controller import NutBoltController # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html class FrankaNutAndBolt(BaseSample): def __init__(self) -> None: super().__init__() # SCENE GEOMETRY # env (group) spacing: self._env_spacing = 2.0 # franka self._stool_height = 0.15 self._franka_position = np.array([0.269, 0.1778, 0.0]) # Gf.Vec3f(0.269, 0.1778, 0.0) # table and vibra table: self._table_position = np.array([0.5, 0.0, 0.0]) # Gf.Vec3f(0.5, 0.0, 0.0) self._table_scale = 0.01 self._tooling_plate_offset = np.array([0.0, 0.0, 0.0]) self._vibra_table_position_offset = np.array([0.157, -0.1524, 0.0]) self._vibra_top_offset = np.array([0.0, 0.0, 0.15]) self._vibra_table_top_to_collider_offset = np.array([0.05, 2.5, -0.59]) * 0.01 # xyz relative to the vibra table where the nut should be picked up self._vibra_table_nut_pickup_pos_offset = np.array([0.124, 0.24, 0.158]) # nut self._nut_height = 0.016 self._nut_spiral_center_vibra_offset = np.array([-0.04, -0.17, 0.01]) # randomize initial nut and bolt positions self._nut_radius = 0.055 self._nut_height_delta = 0.03 self._nut_dist_delta = 0.03 self._mass_nut = 0.065 # pipe and bolt parameters self._bolt_length = 0.1 self._bolt_radius = 0.11 self._pipe_pos_on_table = np.array([0.2032, 0.381, 0.0]) self._bolt_z_offset_to_pipe = 0.08 self._gripper_to_nut_offset = np.array([0.0, 0.0, 0.003]) self._top_of_bolt = ( np.array([0.0, 0.0, self._bolt_length + (self._nut_height / 2)]) + self._gripper_to_nut_offset ) # randomization self._randomize_nut_positions = True self._nut_position_noise_minmax = 0.005 self._rng_seed = 8 # states self._reset_hydra_instancing_on_shutdown = False self._time = 0.0 self._fsm_time = 0.0 # some global sim options: self._time_steps_per_second = 240 # 4.167ms aprx self._fsm_update_rate = 60 self._solverPositionIterations = 4 self._solverVelocityIterations = 1 self._solver_type = "TGS" self._ik_damping = 0.1 self._num_bolts = 6 self._num_nuts = 12 self._sim_dt = 1.0 / self._time_steps_per_second self._fsm_update_dt = 1.0 / self._fsm_update_rate self._sim_time_list = [] self._joint_positions = [] self._joint_velocities = [] self._camera1_img = [] self._camera2_img = [] self._camera3_img = [] return def setup_scene(self): # setup asset paths: self.nucleus_server = get_assets_root_path() self.asset_folder = self.nucleus_server + "/Isaac/Samples/Examples/FrankaNutBolt/" self.asset_paths = { "shop_table": self.asset_folder + "SubUSDs/Shop_Table/Shop_Table.usd", "tooling_plate": self.asset_folder + "SubUSDs/Tooling_Plate/Tooling_Plate.usd", "nut": self.asset_folder + "SubUSDs/Nut/M20_Nut_Tight_R256_Franka_SI.usd", "bolt": self.asset_folder + "SubUSDs/Bolt/M20_Bolt_Tight_R512_Franka_SI.usd", "vibra_table_top": self.asset_folder + "SubUSDs/VibrationTable_Top/VibrationTable_Top.usd", "vibra_table_bot": self.asset_folder + "SubUSDs/VibrationTable_Base/VibrationTable_Base.usd", "vibra_table_collision": self.asset_folder + "SubUSDs/VibrationTable_Top_collision.usd", "vibra_table_clamps": self.asset_folder + "SubUSDs/Clamps/Clamps.usd", "pipe": self.asset_folder + "SubUSDs/Pipe/Pipe.usd", } world = self.get_world() world.scene.add_default_ground_plane() stage = omni.usd.get_context().get_stage() self.simulation_context = SimulationContext() # Change Default SphereLight Intensity sphereLight = stage.GetPrimAtPath("/World/defaultGroundPlane/SphereLight") sphereLightIntensity = sphereLight.GetAttribute("intensity") sphereLightIntensity.Set(10000) # Add Distance Light distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/World/distantLight")) distantLight.CreateIntensityAttr(300) # Add New Sphere Light new_sphereLight = UsdLux.SphereLight.Define(stage, Sdf.Path("/World/sphereLight")) new_sphereLight.CreateIntensityAttr(20000) new_sphereLight.AddTranslateOp().Set(Gf.Vec3f(3.0, 0.0, 2.5)) world.scene.add(XFormPrim(prim_path="/World/collisionGroups", name="collision_groups_xform")) self._setup_simulation() # add_table_assets add_reference_to_stage(usd_path=self.asset_paths["shop_table"], prim_path="/World/env/table") world.scene.add(GeometryPrim(prim_path="/World/env/table", name=f"table_ref_geom", collision=True)) add_reference_to_stage(usd_path=self.asset_paths["tooling_plate"], prim_path="/World/env/tooling_plate") world.scene.add(GeometryPrim(prim_path="/World/env/tooling_plate", name=f"tooling_plate_geom", collision=True)) add_reference_to_stage(usd_path=self.asset_paths["pipe"], prim_path="/World/env/pipe") world.scene.add(GeometryPrim(prim_path="/World/env/pipe", name=f"pipe_geom", collision=True)) # add_vibra_table_assets add_reference_to_stage(usd_path=self.asset_paths["vibra_table_bot"], prim_path="/World/env/vibra_table_bottom") world.scene.add(GeometryPrim(prim_path="/World/env/vibra_table_bottom", name=f"vibra_table_bottom_geom")) add_reference_to_stage( usd_path=self.asset_paths["vibra_table_clamps"], prim_path="/World/env/vibra_table_clamps" ) world.scene.add( GeometryPrim(prim_path="/World/env/vibra_table_clamps", name=f"vibra_table_clamps_geom", collision=True) ) world.scene.add(XFormPrim(prim_path="/World/env/vibra_table", name=f"vibra_table_xform")) add_reference_to_stage(usd_path=self.asset_paths["vibra_table_top"], prim_path="/World/env/vibra_table/visual") add_reference_to_stage( usd_path=self.asset_paths["vibra_table_collision"], prim_path="/World/env/vibra_table/collision" ) world.scene.add(XFormPrim(prim_path="/World/env/vibra_table/visual", name=f"vibra_table_visual_xform")) world.scene.add( GeometryPrim( prim_path="/World/env/vibra_table/collision", name=f"vibra_table_collision_ref_geom", collision=True ) ) # add_nuts_bolts_assets for bolt in range(self._num_bolts): add_reference_to_stage(usd_path=self.asset_paths["bolt"], prim_path=f"/World/env/bolt{bolt}") world.scene.add(GeometryPrim(prim_path=f"/World/env/bolt{bolt}", name=f"bolt{bolt}_geom")) for nut in range(self._num_nuts): add_reference_to_stage(usd_path=self.asset_paths["nut"], prim_path=f"/World/env/nut{nut}") world.scene.add(GeometryPrim(prim_path=f"/World/env/nut{nut}", name=f"nut{nut}_geom")) # add_franka_assets self._franka = world.scene.add(Franka(prim_path="/World/env/franka", name=f"franka")) self._camera1 = Camera( prim_path="/World/env/franka/panda_hand/hand_camera", # position=np.array([0.088, 0.0, 0.926]), translation=np.array([0.1, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 180, -90 - 25, 0 ]), degrees=True), ) self._camera1.set_clipping_range(0.1, 1000000.0) self._camera1.initialize() self._camera1.add_motion_vectors_to_frame() self._camera1.set_visibility(False) self._camera2 = Camera( prim_path="/World/top_camera", position=np.array([0.5, 0.0, 5.0]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0, 90, 0 ]), degrees=True), ) self._camera2.initialize() self._camera2.set_visibility(True) # HDF Data Collection Setup self._save_count = 0 self._f = h5py.File('franka_bolts_nuts_table.hdf5','w') self._group_f = self._f.create_group("isaac_dataset") self._img_f = self._group_f.create_group("camera_images") return async def setup_post_load(self): self._world = self.get_world() self._rng = np.random.default_rng(self._rng_seed) self._world.scene.enable_bounding_boxes_computations() await self._setup_materials() # next four functions are for setting up the right positions and orientations for all assets await self._add_table() await self._add_vibra_table() await self._add_nuts_and_bolt(add_debug_nut=self._num_nuts == 2) await self._add_franka() self._controller = NutBoltController(name="nut_bolt_controller", franka=self._franka) self._franka.gripper.open() self._rbApi2 = UsdPhysics.RigidBodyAPI.Apply(self._vibra_table_xform.prim.GetPrim()) self._world.add_physics_callback(f"sim_step", callback_fn=self.physics_step) self._camera3 = Camera( prim_path="/World/front_camera", position=self._franka_position + np.array([1.0, 0.0, 0.3 + self._table_height]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0, 0, 180 ]), degrees=True), ) self._camera3.set_clipping_range(0.1, 1000000.0) self._camera3.set_focal_length(1.0) self._camera3.initialize() self._camera3.set_visibility(False) await self._world.play_async() return def physics_step(self, step_size): self._camera1.get_current_frame() self._camera2.get_current_frame() self._camera3.get_current_frame() current_time = self.simulation_context.current_time current_joint_pos = self._franka.get_joint_positions() current_joint_vel = self._franka.get_joint_velocities() if self._save_count % 100 == 0: self._sim_time_list.append(current_time) self._joint_positions.append(current_joint_pos) self._joint_velocities.append(current_joint_vel) self._camera1_img.append(self._camera1.get_rgba()[:, :, :3]) self._camera2_img.append(self._camera2.get_rgba()[:, :, :3]) self._camera3_img.append(self._camera3.get_rgba()[:, :, :3]) print("Collecting data...") elif self._save_count > 2000: self.world_cleanup() self._save_count += 1 if self._controller.is_paused(): if self._controller._i >= min(self._num_nuts, self._num_bolts): self._rbApi2.CreateVelocityAttr().Set(Gf.Vec3f(0.0, 0.0, 0.0)) return self._controller.reset(self._franka) if self._controller._i < min(self._num_nuts, self._num_bolts): initial_position = self._vibra_table_nut_pickup_pos_offset + self._vibra_table_position self._bolt_geom = self._world.scene.get_object(f"bolt{self._controller._i}_geom") finger_pos = self._franka.get_joint_positions()[-2:] positive_x_offset = finger_pos[1] - finger_pos[0] bolt_position, _ = self._bolt_geom.get_world_pose() placing_position = bolt_position + self._top_of_bolt _vibra_table_transforms = self._controller.forward( initial_picking_position=initial_position, bolt_top=placing_position, gripper_to_nut_offset=self._gripper_to_nut_offset, x_offset=positive_x_offset, ) self._rbApi2.CreateVelocityAttr().Set( Gf.Vec3f(_vibra_table_transforms[0], _vibra_table_transforms[1], _vibra_table_transforms[2]) ) return async def _setup_materials(self): self._bolt_physics_material = PhysicsMaterial( prim_path="/World/PhysicsMaterials/BoltMaterial", name="bolt_material_physics", static_friction=0.2, dynamic_friction=0.2, ) self._nut_physics_material = PhysicsMaterial( prim_path="/World/PhysicsMaterials/NutMaterial", name="nut_material_physics", static_friction=0.2, dynamic_friction=0.2, ) self._vibra_table_physics_material = PhysicsMaterial( prim_path="/World/PhysicsMaterials/VibraTableMaterial", name="vibra_table_material_physics", static_friction=0.2, dynamic_friction=0.2, ) self._franka_finger_physics_material = PhysicsMaterial( prim_path="/World/PhysicsMaterials/FrankaFingerMaterial", name="franka_finger_material_physics", static_friction=0.7, dynamic_friction=0.7, ) await self._world.reset_async() async def _add_table(self): ##shop_table self._table_ref_geom = self._world.scene.get_object(f"table_ref_geom") self._table_ref_geom.set_local_scale(np.array([self._table_scale])) self._table_ref_geom.set_world_pose(position=self._table_position) self._table_ref_geom.set_default_state(position=self._table_position) lb = self._world.scene.compute_object_AABB(name=f"table_ref_geom") zmin = lb[0][2] zmax = lb[1][2] self._table_position[2] = -zmin self._table_height = zmax self._table_ref_geom.set_collision_approximation("none") self._convexIncludeRel.AddTarget(self._table_ref_geom.prim_path) ##tooling_plate self._tooling_plate_geom = self._world.scene.get_object(f"tooling_plate_geom") self._tooling_plate_geom.set_local_scale(np.array([self._table_scale])) lb = self._world.scene.compute_object_AABB(name=f"tooling_plate_geom") zmin = lb[0][2] zmax = lb[1][2] tooling_transform = self._tooling_plate_offset tooling_tranfsorm[2] = -zmin + self._table_height tooling_transform = tooling_transform + self._table_position self._tooling_plate_geom.set_world_pose(position=tooling_transform) self._tooling_plate_geom.set_default_state(position=tooling_transform) self._tooling_plate_geom.set_collision_approximation("boundingCube") self._table_height += zmax - zmin self._convexIncludeRel.AddTarget(self._tooling_plate_geom.prim_path) ##pipe self._pipe_geom = self._world.scene.get_object(f"pipe_geom") self._pipe_geom.set_local_scale(np.array([self._table_scale])) lb = self._world.scene.compute_object_AABB(name=f"pipe_geom") zmin = lb[0][2] zmax = lb[1][2] self._pipe_height = zmax - zmin pipe_transform = self._pipe_pos_on_table pipe_transform[2] = -zmin + self._table_height pipe_transform = pipe_transform + self._table_position self._pipe_geom.set_world_pose(position=pipe_transform, orientation=np.array([0, 0, 0, 1])) self._pipe_geom.set_default_state(position=pipe_transform, orientation=np.array([0, 0, 0, 1])) self._pipe_geom.set_collision_approximation("none") self._convexIncludeRel.AddTarget(self._pipe_geom.prim_path) await self._world.reset_async() async def _add_vibra_table(self): self._vibra_table_bottom_geom = self._world.scene.get_object(f"vibra_table_bottom_geom") self._vibra_table_bottom_geom.set_local_scale(np.array([self._table_scale])) lb = self._world.scene.compute_object_AABB(name=f"vibra_table_bottom_geom") zmin = lb[0][2] bot_part_pos = self._vibra_table_position_offset bot_part_pos[2] = -zmin + self._table_height bot_part_pos = bot_part_pos + self._table_position self._vibra_table_bottom_geom.set_world_pose(position=bot_part_pos) self._vibra_table_bottom_geom.set_default_state(position=bot_part_pos) self._vibra_table_bottom_geom.set_collision_approximation("none") self._convexIncludeRel.AddTarget(self._vibra_table_bottom_geom.prim_path) # clamps self._vibra_table_clamps_geom = self._world.scene.get_object(f"vibra_table_clamps_geom") self._vibra_table_clamps_geom.set_collision_approximation("none") self._convexIncludeRel.AddTarget(self._vibra_table_clamps_geom.prim_path) # vibra_table self._vibra_table_xform = self._world.scene.get_object(f"vibra_table_xform") self._vibra_table_position = bot_part_pos vibra_kinematic_prim = self._vibra_table_xform.prim rbApi = UsdPhysics.RigidBodyAPI.Apply(vibra_kinematic_prim.GetPrim()) rbApi.CreateRigidBodyEnabledAttr(True) rbApi.CreateKinematicEnabledAttr(True) # visual self._vibra_table_visual_xform = self._world.scene.get_object(f"vibra_table_visual_xform") self._vibra_table_visual_xform.set_world_pose(position=self._vibra_top_offset) self._vibra_table_visual_xform.set_default_state(position=self._vibra_top_offset) self._vibra_table_visual_xform.set_local_scale(np.array([self._table_scale])) # not clear why this makes a difference for the position (new bug although no change to code) self._vibra_table_visual_xform.prim.SetInstanceable(True) # collision self._vibra_table_collision_ref_geom = self._world.scene.get_object(f"vibra_table_collision_ref_geom") offset = self._vibra_top_offset + self._vibra_table_top_to_collider_offset self._vibra_table_collision_ref_geom.set_local_scale(np.array([1.0])) self._vibra_table_collision_ref_geom.set_world_pose(position=offset) self._vibra_table_collision_ref_geom.set_default_state(position=offset) self._vibra_table_collision_ref_geom.apply_physics_material(self._vibra_table_physics_material) self._convexIncludeRel.AddTarget(self._vibra_table_collision_ref_geom.prim_path) self._vibra_table_collision_ref_geom.set_collision_approximation("convexHull") vibra_kinematic_prim.SetInstanceable(True) self._vibra_table_xform.set_world_pose(position=self._vibra_table_position, orientation=np.array([0, 0, 0, 1])) self._vibra_table_xform.set_default_state( position=self._vibra_table_position, orientation=np.array([0, 0, 0, 1]) ) self._vibra_table_visual_xform.set_default_state( position=self._vibra_table_visual_xform.get_world_pose()[0], orientation=self._vibra_table_visual_xform.get_world_pose()[1], ) self._vibra_table_collision_ref_geom.set_default_state( position=self._vibra_table_collision_ref_geom.get_world_pose()[0], orientation=self._vibra_table_collision_ref_geom.get_world_pose()[1], ) await self._world.reset_async() async def _add_nuts_and_bolt(self, add_debug_nut=False): angle_delta = np.pi * 2.0 / self._num_bolts for j in range(self._num_bolts): self._bolt_geom = self._world.scene.get_object(f"bolt{j}_geom") self._bolt_geom.prim.SetInstanceable(True) bolt_pos = np.array(self._pipe_pos_on_table) + self._table_position bolt_pos[0] += np.cos(j * angle_delta) * self._bolt_radius bolt_pos[1] += np.sin(j * angle_delta) * self._bolt_radius bolt_pos[2] = self._bolt_z_offset_to_pipe + self._table_height self._bolt_geom.set_world_pose(position=bolt_pos) self._bolt_geom.set_default_state(position=bolt_pos) self._boltMeshIncludeRel.AddTarget(self._bolt_geom.prim_path) self._bolt_geom.apply_physics_material(self._bolt_physics_material) await self._generate_nut_initial_poses() for nut_idx in range(self._num_nuts): nut_pos = self._nut_init_poses[nut_idx, :3].copy() if add_debug_nut and nut_idx == 0: nut_pos[0] = 0.78 nut_pos[1] = self._vibra_table_nut_pickup_pos_offset[1] + self._vibra_table_position[1] # 0.0264 if add_debug_nut and nut_idx == 1: nut_pos[0] = 0.78 nut_pos[1] = 0.0264 - 0.04 self._nut_geom = self._world.scene.get_object(f"nut{nut_idx}_geom") self._nut_geom.prim.SetInstanceable(True) self._nut_geom.set_world_pose(position=np.array(nut_pos.tolist())) self._nut_geom.set_default_state(position=np.array(nut_pos.tolist())) physxRBAPI = PhysxSchema.PhysxRigidBodyAPI.Apply(self._nut_geom.prim) physxRBAPI.CreateSolverPositionIterationCountAttr().Set(self._solverPositionIterations) physxRBAPI.CreateSolverVelocityIterationCountAttr().Set(self._solverVelocityIterations) self._nut_geom.apply_physics_material(self._nut_physics_material) self._convexIncludeRel.AddTarget(self._nut_geom.prim_path + "/M20_Nut_Tight_Convex") self._nutMeshIncludeRel.AddTarget(self._nut_geom.prim_path + "/M20_Nut_Tight_SDF") rbApi3 = UsdPhysics.RigidBodyAPI.Apply(self._nut_geom.prim.GetPrim()) rbApi3.CreateRigidBodyEnabledAttr(True) physxAPI = PhysxSchema.PhysxRigidBodyAPI.Apply(self._nut_geom.prim.GetPrim()) physxAPI.CreateSleepThresholdAttr().Set(0.0) massAPI = UsdPhysics.MassAPI.Apply(self._nut_geom.prim.GetPrim()) massAPI.CreateMassAttr().Set(self._mass_nut) await self._world.reset_async() async def _generate_nut_initial_poses(self): self._nut_init_poses = np.zeros((self._num_nuts, 7), dtype=np.float32) self._nut_init_poses[:, -1] = 1 # quat to identity nut_spiral_center = self._vibra_table_position + self._nut_spiral_center_vibra_offset nut_spiral_center += self._vibra_top_offset for nut_idx in range(self._num_nuts): self._nut_init_poses[nut_idx, :3] = np.array(nut_spiral_center) self._nut_init_poses[nut_idx, 0] += self._nut_radius * np.sin( np.pi / 3.0 * nut_idx ) + self._nut_dist_delta * (nut_idx // 6) self._nut_init_poses[nut_idx, 1] += self._nut_radius * np.cos( np.pi / 3.0 * nut_idx ) + self._nut_dist_delta * (nut_idx // 6) self._nut_init_poses[nut_idx, 2] += self._nut_height_delta * (nut_idx // 6) if self._randomize_nut_positions: self._nut_init_poses[nut_idx, 0] += self._rng.uniform( -self._nut_position_noise_minmax, self._nut_position_noise_minmax ) self._nut_init_poses[nut_idx, 1] += self._rng.uniform( -self._nut_position_noise_minmax, self._nut_position_noise_minmax ) await self._world.reset_async() async def _add_franka(self): self._franka = self._world.scene.get_object(f"franka") franka_pos = np.array(self._franka_position) franka_pos[2] = franka_pos[2] + self._table_height self._franka.set_world_pose(position=franka_pos) self._franka.set_default_state(position=franka_pos) self._franka.gripper.open() kps = np.array([6000000.0, 600000.0, 6000000.0, 600000.0, 25000.0, 15000.0, 25000.0, 15000.0, 15000.0]) kds = np.array([600000.0, 60000.0, 300000.0, 30000.0, 3000.0, 3000.0, 3000.0, 6000.0, 6000.0]) self._franka.get_articulation_controller().set_gains(kps=kps, kds=kds, save_to_usd=True) self._frankaHandIncludeRel.AddTarget(self._franka.prim_path + "/panda_leftfinger") self._frankaHandIncludeRel.AddTarget(self._franka.prim_path + "/panda_rightfinger") franka_left_finger = self._world.stage.GetPrimAtPath( "/World/env/franka/panda_leftfinger/geometry/panda_leftfinger" ) x = UsdShade.MaterialBindingAPI.Apply(franka_left_finger) x.Bind( self._franka_finger_physics_material.material, bindingStrength="weakerThanDescendants", materialPurpose="physics", ) franka_right_finger = self._world.stage.GetPrimAtPath( "/World/env/franka/panda_rightfinger/geometry/panda_rightfinger" ) x2 = UsdShade.MaterialBindingAPI.Apply(franka_right_finger) x2.Bind( self._franka_finger_physics_material.material, bindingStrength="weakerThanDescendants", materialPurpose="physics", ) await self._world.reset_async() def _setup_simulation(self): self._scene = PhysicsContext() self._scene.set_solver_type(self._solver_type) self._scene.set_broadphase_type("GPU") self._scene.enable_gpu_dynamics(flag=True) self._scene.set_friction_offset_threshold(0.01) self._scene.set_friction_correlation_distance(0.0005) self._scene.set_gpu_total_aggregate_pairs_capacity(10 * 1024) self._scene.set_gpu_found_lost_pairs_capacity(10 * 1024) self._scene.set_gpu_heap_capacity(64 * 1024 * 1024) self._scene.set_gpu_found_lost_aggregate_pairs_capacity(10 * 1024) # added because of new errors regarding collisionstacksize physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(get_prim_at_path("/physicsScene")) physxSceneAPI.CreateGpuCollisionStackSizeAttr().Set(76000000) # or whatever min is needed # group to include SDF mesh of nut only self._meshCollisionGroup = UsdPhysics.CollisionGroup.Define( self._world.scene.stage, "/World/collisionGroups/meshColliders" ) collectionAPI = Usd.CollectionAPI.Apply(self._meshCollisionGroup.GetPrim(), "colliders") self._nutMeshIncludeRel = collectionAPI.CreateIncludesRel() # group to include all convex collision (nut convex, pipe, table, vibrating table, other small assets on the table) self._convexCollisionGroup = UsdPhysics.CollisionGroup.Define( self._world.scene.stage, "/World/collisionGroups/convexColliders" ) collectionAPI = Usd.CollectionAPI.Apply(self._convexCollisionGroup.GetPrim(), "colliders") self._convexIncludeRel = collectionAPI.CreateIncludesRel() # group to include bolt prim only (only has SDF mesh) self._boltCollisionGroup = UsdPhysics.CollisionGroup.Define( self._world.scene.stage, "/World/collisionGroups/boltColliders" ) collectionAPI = Usd.CollectionAPI.Apply(self._boltCollisionGroup.GetPrim(), "colliders") self._boltMeshIncludeRel = collectionAPI.CreateIncludesRel() # group to include the franka hands prims only self._frankaHandCollisionGroup = UsdPhysics.CollisionGroup.Define( self._world.scene.stage, "/World/collisionGroups/frankaHandColliders" ) collectionAPI = Usd.CollectionAPI.Apply(self._frankaHandCollisionGroup.GetPrim(), "colliders") self._frankaHandIncludeRel = collectionAPI.CreateIncludesRel() # invert group logic so only groups that filter each-other will collide: self._scene.set_invert_collision_group_filter(True) # # the SDF mesh collider nuts should only collide with the bolts filteredRel = self._meshCollisionGroup.CreateFilteredGroupsRel() filteredRel.AddTarget("/World/collisionGroups/boltColliders") # # the convex hull nuts should collide with other nuts, the vibra table, table, pipe and small assets on the table. # It should also collide with the franka grippers filteredRel = self._convexCollisionGroup.CreateFilteredGroupsRel() filteredRel.AddTarget("/World/collisionGroups/convexColliders") filteredRel.AddTarget("/World/collisionGroups/frankaHandColliders") # # the SDF mesh bolt only collides with the SDF mesh nut colliders # and with the franka grippers filteredRel = self._boltCollisionGroup.CreateFilteredGroupsRel() filteredRel.AddTarget("/World/collisionGroups/meshColliders") filteredRel.AddTarget("/World/collisionGroups/frankaHandColliders") async def setup_pre_reset(self): return async def setup_post_reset(self): self._controller._vibraSM.reset() self._controller._vibraSM._i = 2 self._controller.reset(franka=self._franka) self._controller._i = self._controller._vibraSM._i self._franka.gripper.open() self._controller._vibraSM.start_feed() await self._world.play_async() return def world_cleanup(self): self._controller = None self._group_f.create_dataset(f"sim_time", data=self._sim_time_list, compression='gzip', compression_opts=9) self._group_f.create_dataset(f"joint_positions", data=self._joint_positions, compression='gzip', compression_opts=9) self._group_f.create_dataset(f"joint_velocities", data=self._joint_velocities, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"hand_camera", data=self._camera1_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"top_camera", data=self._camera2_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"front_camera", data=self._camera3_img, compression='gzip', compression_opts=9) self._f.close() print("Data saved") self._save_count = 0 self._world.pause() return
31,138
Python
48.115142
126
0.638898
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNutsTable/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNutsTable/nut_vibra_table_controller.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import numpy as np class VibraFSM: _amplitudes = { "stop": np.array((0.0, 0.0, 0.0), dtype=np.float32), # [m] "run_feed": np.array((0.000, 0.03, 0.02), dtype=np.float32), # [m] "backward": np.array((0.000, -0.03, 0.02), dtype=np.float32), # [m] "realign": np.array((-0.03, 0.0, 0.02), dtype=np.float32), # [m] } _motion_frequency = 60.0 # [Hz] # configure unblock-cycle: _feed_time = 3.5 _stop_time = 5.0 _backward_time = 0.75 _realign_time = 0.75 def __init__(self, dt=None): self.reset() self._i = 2 if dt is not None: self._dt = dt def reset(self): self._dt = 1.0 / 240.0 self._time = 0.0 self.state = "stop" self._after_delay_state = None def start_feed(self): self.state = "run_feed" # kick off unblock cycle self._set_delayed_state_change(delay_sec=self._feed_time, nextState="backward") def stop_feed_after_delay(self, delay_sec: float): self.state = "run_feed" self._set_delayed_state_change(delay_sec=delay_sec, nextState="stop") def _set_delayed_state_change(self, delay_sec: float, nextState: str): self._after_delay_state = nextState self._wait_end_time = self._time + delay_sec def update(self): self._time += self._dt # process wait if necessary if self._after_delay_state is not None and self._time > self._wait_end_time: self.state = self._after_delay_state # auto-unblock cycle if self._state == "run_feed": self.stop_feed_after_delay(self._stop_time) elif self._state == "backward": self._set_delayed_state_change(delay_sec=self._backward_time, nextState="realign") elif self._state == "realign": self._set_delayed_state_change(delay_sec=self._realign_time, nextState="run_feed") else: self._after_delay_state = None return self._motion_amplitude def is_stopped(self): return self._state == "stop" def is_stopping(self): return self.is_stopped() or self._after_delay_state == "stop" @property def state(self): return self._state @state.setter def state(self, newState): self._state = newState if self._state in self._amplitudes: self._motion_amplitude = self._amplitudes[self._state] else: self._motion_amplitude = self._amplitudes["stop"]
2,983
Python
34.105882
98
0.601408
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNutsTable/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoAckermannROS2/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoAckermannROS2/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .limo_ackermann import LimoAckermann """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="WegoRobotics", name="LimoAckermannROS2", title="LimoAckermannROS2", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=LimoAckermann(), ) return
2,067
Python
42.083332
135
0.742622
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoAckermannROS2/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoAckermannROS2/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoAckermannROS2/limo_ackermann.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from pxr import UsdGeom, Gf, UsdPhysics, Sdf, Gf, Tf, UsdLux from omni.physx.scripts import deformableUtils, physicsUtils import omni.graph.core as og import numpy as np import usdrt.Sdf import omni import carb class LimoAckermann(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self.TRACK_PATH = self._server_root + "/Projects/WegoLimo/LimoTrack/LIMO_simulation_table.usd" # self.ROBOT_PATH = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_diff_thin.usd" self.ROBOT_PATH = self._server_root + "/Projects/WegoLimo/Limo/limo_ackermann.usd" # omniverse://localhost/Projects/WegoLimo/Limo/limo_ackermann.usd self._domain_id = 30 self._maxWheelRotation = 1e6 self._maxWheelVelocity = 1e6 self._trackWidth = 0.13 self._turningWheelRadius = 0.045 self._wheelBase = 0.2 self._targetPrim = "/World/Limo/base_link" self._robotPath = "/World/Limo/base_link" self._cameraPath = "/World/Limo/depth_link/rgb_camera" return def og_setup(self): try: og.Controller.edit( {"graph_path": "/ROS2Ackermann", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("subscribeTwist", "omni.isaac.ros2_bridge.ROS2SubscribeTwist"), ("scaleToFromStage", "omni.isaac.core_nodes.OgnIsaacScaleToFromStageUnit"), ("angVelBreak", "omni.graph.nodes.BreakVector3"), ("linVelBreak", "omni.graph.nodes.BreakVector3"), ("wheelbase", "omni.graph.nodes.ConstantDouble"), ("multiply", "omni.graph.nodes.Multiply"), ("atan2", "omni.graph.nodes.ATan2"), ("toRad", "omni.graph.nodes.ToRad"), ("ackermannCtrl", "omni.isaac.wheeled_robots.AckermannSteering"), ("wheelJointNames", "omni.graph.nodes.ConstructArray"), ("wheelRotationVel", "omni.graph.nodes.ConstructArray"), ("hingeJointNames", "omni.graph.nodes.ConstructArray"), ("hingePosVel", "omni.graph.nodes.ConstructArray"), ("articulationRotation", "omni.isaac.core_nodes.IsaacArticulationController"), ("articulationPosition", "omni.isaac.core_nodes.IsaacArticulationController"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", self._domain_id), ("subscribeTwist.inputs:topicName", "cmd_vel"), ("wheelbase.inputs:value", self._wheelBase), ("ackermannCtrl.inputs:maxWheelRotation", self._maxWheelRotation), ("ackermannCtrl.inputs:maxWheelVelocity", self._maxWheelVelocity), ("ackermannCtrl.inputs:trackWidth", self._trackWidth), ("ackermannCtrl.inputs:turningWheelRadius", self._turningWheelRadius), ("ackermannCtrl.inputs:useAcceleration", False), ("wheelJointNames.inputs:arraySize", 4), ("wheelJointNames.inputs:arrayType", "token[]"), ("wheelJointNames.inputs:input0", "rear_left_wheel"), ("wheelJointNames.inputs:input1", "rear_right_wheel"), ("wheelJointNames.inputs:input2", "front_left_wheel"), ("wheelJointNames.inputs:input3", "front_right_wheel"), ("hingeJointNames.inputs:arraySize", 2), ("hingeJointNames.inputs:arrayType", "token[]"), ("hingeJointNames.inputs:input0", "left_steering_hinge_wheel"), ("hingeJointNames.inputs:input1", "right_steering_hinge_wheel"), ("wheelRotationVel.inputs:arraySize", 4), ("wheelRotationVel.inputs:arrayType", "double[]"), ("hingePosVel.inputs:arraySize", 2), ("hingePosVel.inputs:arrayType", "double[]"), ("articulationRotation.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]), ("articulationRotation.inputs:robotPath", self._targetPrim), ("articulationRotation.inputs:usePath", False), ("articulationPosition.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]), ("articulationPosition.inputs:robotPath", self._targetPrim), ("articulationPosition.inputs:usePath", False), ], og.Controller.Keys.CREATE_ATTRIBUTES: [ ("wheelJointNames.inputs:input1", "token"), ("wheelJointNames.inputs:input2", "token"), ("wheelJointNames.inputs:input3", "token"), ("hingeJointNames.inputs:input1", "token"), ("wheelRotationVel.inputs:input1", "double"), ("wheelRotationVel.inputs:input2", "double"), ("wheelRotationVel.inputs:input3", "double"), ("hingePosVel.inputs:input1", "double"), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "subscribeTwist.inputs:execIn"), ("context.outputs:context", "subscribeTwist.inputs:context"), ("subscribeTwist.outputs:linearVelocity", "scaleToFromStage.inputs:value"), ("scaleToFromStage.outputs:result", "linVelBreak.inputs:tuple"), ("subscribeTwist.outputs:angularVelocity", "angVelBreak.inputs:tuple"), ("subscribeTwist.outputs:execOut", "ackermannCtrl.inputs:execIn"), ("angVelBreak.outputs:z", "multiply.inputs:a"), ("linVelBreak.outputs:x", "ackermannCtrl.inputs:speed"), ("wheelbase.inputs:value", "multiply.inputs:b"), ("wheelbase.inputs:value", "ackermannCtrl.inputs:wheelBase"), ("multiply.outputs:product", "atan2.inputs:a"), ("linVelBreak.outputs:x", "atan2.inputs:b"), ("atan2.outputs:result", "toRad.inputs:degrees"), ("toRad.outputs:radians", "ackermannCtrl.inputs:steeringAngle"), ("ackermannCtrl.outputs:leftWheelAngle", "hingePosVel.inputs:input0"), ("ackermannCtrl.outputs:rightWheelAngle", "hingePosVel.inputs:input1"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input0"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input1"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input2"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input3"), ("ackermannCtrl.outputs:execOut", "articulationRotation.inputs:execIn"), ("wheelJointNames.outputs:array", "articulationRotation.inputs:jointNames"), ("wheelRotationVel.outputs:array", "articulationRotation.inputs:velocityCommand"), ("ackermannCtrl.outputs:execOut", "articulationPosition.inputs:execIn"), ("hingeJointNames.outputs:array", "articulationPosition.inputs:jointNames"), ("hingePosVel.outputs:array", "articulationPosition.inputs:positionCommand"), ], }, ) og.Controller.edit( {"graph_path": "/ROS2Odom", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("computeOdom", "omni.isaac.core_nodes.IsaacComputeOdometry"), ("publishOdom", "omni.isaac.ros2_bridge.ROS2PublishOdometry"), ("publishRawTF", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", self._domain_id), ("computeOdom.inputs:chassisPrim", [usdrt.Sdf.Path(self._targetPrim)]), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "computeOdom.inputs:execIn"), ("onPlaybackTick.outputs:tick", "publishOdom.inputs:execIn"), ("onPlaybackTick.outputs:tick", "publishRawTF.inputs:execIn"), ("readSimTime.outputs:simulationTime", "publishOdom.inputs:timeStamp"), ("readSimTime.outputs:simulationTime", "publishRawTF.inputs:timeStamp"), ("context.outputs:context", "publishOdom.inputs:context"), ("context.outputs:context", "publishRawTF.inputs:context"), ("computeOdom.outputs:angularVelocity", "publishOdom.inputs:angularVelocity"), ("computeOdom.outputs:linearVelocity", "publishOdom.inputs:linearVelocity"), ("computeOdom.outputs:orientation", "publishOdom.inputs:orientation"), ("computeOdom.outputs:position", "publishOdom.inputs:position"), ("computeOdom.outputs:orientation", "publishRawTF.inputs:rotation"), ("computeOdom.outputs:position", "publishRawTF.inputs:translation"), ], }, ) # Camera OG og.Controller.edit( {"graph_path": "/ROS2Camera", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("renderer", "omni.isaac.core_nodes.IsaacCreateRenderProduct"), ("RGBPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("DepthPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("CameraInfoPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", self._domain_id), ("renderer.inputs:cameraPrim", [usdrt.Sdf.Path(self._cameraPath)]), ("RGBPublish.inputs:topicName", "/limo/rgb"), ("RGBPublish.inputs:type", "rgb"), ("RGBPublish.inputs:resetSimulationTimeOnStop", True), ("RGBPublish.inputs:frameId", "limo_rgbd_frame"), ("DepthPublish.inputs:topicName", "/limo/depth"), ("DepthPublish.inputs:type", "depth"), ("DepthPublish.inputs:resetSimulationTimeOnStop", True), ("DepthPublish.inputs:frameId", "limo_rgbd_frame"), ("CameraInfoPublish.inputs:topicName", "/limo/camera_info"), ("CameraInfoPublish.inputs:type", "camera_info"), ("CameraInfoPublish.inputs:resetSimulationTimeOnStop", True), ("CameraInfoPublish.inputs:frameId", "limo_rgbd_frame"), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "renderer.inputs:execIn"), ("context.outputs:context", "RGBPublish.inputs:context"), ("context.outputs:context", "DepthPublish.inputs:context"), ("context.outputs:context", "CameraInfoPublish.inputs:context"), ("renderer.outputs:execOut", "RGBPublish.inputs:execIn"), ("renderer.outputs:execOut", "DepthPublish.inputs:execIn"), ("renderer.outputs:execOut", "CameraInfoPublish.inputs:execIn"), ("renderer.outputs:renderProductPath", "RGBPublish.inputs:renderProductPath"), ("renderer.outputs:renderProductPath", "DepthPublish.inputs:renderProductPath"), ("renderer.outputs:renderProductPath", "CameraInfoPublish.inputs:renderProductPath"), ], }, ) except Exception as e: print(e) def add_background(self): add_reference_to_stage(usd_path=self.TRACK_PATH, prim_path="/World/LimoTrack") bg_mesh = UsdGeom.Mesh.Get(omni.usd.get_context().get_stage(), "/World/LimoTrack") physicsUtils.set_or_add_scale_op(bg_mesh, scale=Gf.Vec3f(0.01, 0.01, 0.01)) def add_robot(self): add_reference_to_stage(usd_path=self.ROBOT_PATH, prim_path="/World/Limo") limo_mesh = UsdGeom.Mesh.Get(omni.usd.get_context().get_stage(), "/World/Limo") physicsUtils.set_or_add_translate_op(limo_mesh, translate=Gf.Vec3f(0.0, -0.18, 0.0)) def add_light(self): distantLight1 = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/distantLight1")) distantLight1.CreateIntensityAttr(3000) distantLight1.AddTranslateOp().Set(Gf.Vec3f(0.0, 0.0, 0.0)) def setup_scene(self): self._world = self.get_world() self._stage = omni.usd.get_context().get_stage() self.add_background() self.add_light() self.add_robot() self.og_setup() self._save_count = 0 return async def setup_post_load(self): self._world = self.get_world() # self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) return async def setup_pre_reset(self): if self._world.physics_callback_exists("sim_step"): self._world.remove_physics_callback("sim_step") self._world.pause() return async def setup_post_reset(self): await self._world.play_async() self._world.pause() return def world_cleanup(self): self._world.pause() return
15,868
Python
57.992565
109
0.560814
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoAckermannROS2/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloDeformable/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloDeformable/hello_deformable.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import numpy as np from omni.isaac.core.materials.deformable_material import DeformableMaterial from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.physx.scripts import deformableUtils, physicsUtils from omni.isaac.examples.base_sample import BaseSample from pxr import UsdGeom, Gf, UsdPhysics import omni.physx import omni.usd import omni class HelloDeformable(BaseSample): def __init__(self) -> None: super().__init__() return def _setup_simulation(self): self._scene = PhysicsContext() self._scene.set_solver_type("TGS") self._scene.set_broadphase_type("GPU") self._scene.enable_gpu_dynamics(flag=True) def setup_scene(self): world = self.get_world() self._setup_simulation() stage = omni.usd.get_context().get_stage() world.scene.add_default_ground_plane() # Create cube result, path = omni.kit.commands.execute("CreateMeshPrimCommand", prim_type="Cube") omni.kit.commands.execute("MovePrim", path_from=path, path_to="/World/cube") omni.usd.get_context().get_selection().set_selected_prim_paths([], False) cube_mesh = UsdGeom.Mesh.Get(stage, "/World/cube") physicsUtils.set_or_add_translate_op(cube_mesh, translate=Gf.Vec3f(0.0, 0.0, 0.5)) # physicsUtils.set_or_add_orient_op(cube_mesh, orient=Gf.Quatf(0.707, 0.707, 0, 0)) physicsUtils.set_or_add_scale_op(cube_mesh, scale=Gf.Vec3f(0.1, 0.1, 0.1)) cube_mesh.CreateDisplayColorAttr([(1.0, 0.0, 0.0)]) # Apply PhysxDeformableBodyAPI and PhysxCollisionAPI to skin mesh and set parameter to default values deformableUtils.add_physx_deformable_body( stage, "/World/cube", collision_simplification=True, simulation_hexahedral_resolution=10, self_collision=False, ) # Create a deformable body material and set it on the deformable body deformable_material_path = omni.usd.get_stage_next_free_path(stage, "/World/deformableBodyMaterial", True) deformableUtils.add_deformable_body_material( stage, deformable_material_path, youngs_modulus=10000.0, poissons_ratio=0.49, damping_scale=0.0, dynamic_friction=0.5, ) physicsUtils.add_physics_material_to_prim(stage, stage.GetPrimAtPath("/World/cube"), "/World/cube") async def setup_post_load(self): self._world = self.get_world() return
3,016
Python
37.679487
114
0.671088
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloDeformable/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .hello_deformable import HelloDeformable """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="", name="HelloDeformable", title="HelloDeformable", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=HelloDeformable(), ) return
2,057
Python
41.874999
135
0.741371
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloDeformable/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloDeformable/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloDeformable/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFactory/franka_factory.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.franka.controllers import PickPlaceController from omni.isaac.examples.base_sample import BaseSample import numpy as np from omni.isaac.core.prims.geometry_prim import GeometryPrim # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html from pxr import Sdf, UsdLux, Gf from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.utils.rotations import euler_angles_to_quat from omni.isaac.core import SimulationContext import carb import omni from .franka_playing import FrankaPlaying class FrankaGarage(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self._franka_position = np.array([-0.8064, 1.3602, 0.0]) # (w, x, y, z) self._franka_rotation = np.array([0.0, 0.0, 0.0, 1.0]) self._table_scale = 0.01 self._table_height = 0.0 self._table_position = np.array([-0.7, 1.8, 0.007]) # Gf.Vec3f(0.5, 0.0, 0.0) self._bin_scale = np.array([1.5, 1.5, 0.5]) self._bin1_position = np.array([-0.5, 2.1, 0.90797]) self._bin2_position = np.array([-0.5, 1.6, 0.90797]) return def add_background(self): self._world = self.get_world() self._nucleus_server = get_assets_root_path() bg_path = self._server_root + "/Projects/RBROS2/ConveyorGarage/Franka_Garage_Empty.usd" add_reference_to_stage(usd_path=bg_path, prim_path=f"/World/Franka_Garage") def add_bin(self): bin_path = self._nucleus_server + "/Isaac/Props/KLT_Bin/small_KLT_visual.usd" # bin 1 add_reference_to_stage(usd_path=bin_path, prim_path="/World/bin1") self._world.scene.add(GeometryPrim(prim_path="/World/bin1", name=f"bin1_ref_geom", collision=True)) self._bin1_ref_geom = self._world.scene.get_object(f"bin1_ref_geom") self._bin1_ref_geom.set_local_scale(np.array([self._bin_scale])) self._bin1_ref_geom.set_world_pose(position=self._bin1_position) self._bin1_ref_geom.set_default_state(position=self._bin1_position) # bin 2 add_reference_to_stage(usd_path=bin_path, prim_path="/World/bin2") self._world.scene.add(GeometryPrim(prim_path="/World/bin2", name=f"bin2_ref_geom", collision=True)) self._bin2_ref_geom = self._world.scene.get_object(f"bin2_ref_geom") self._bin2_ref_geom.set_local_scale(np.array([self._bin_scale])) self._bin2_ref_geom.set_world_pose(position=self._bin2_position) self._bin2_ref_geom.set_default_state(position=self._bin2_position) def add_light(self): stage = omni.usd.get_context().get_stage() distantLight = UsdLux.CylinderLight.Define(stage, Sdf.Path("/World/cylinderLight")) distantLight.CreateIntensityAttr(60000) distantLight.AddTranslateOp().Set(Gf.Vec3f(-1.2, 0.9, 3.0)) distantLight.AddScaleOp().Set((0.1, 4.0, 0.1)) distantLight.AddRotateXYZOp().Set((0, 0, 90)) async def add_table(self): table_path = self._nucleus_server + "/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Shop_Table/Shop_Table.usd" add_reference_to_stage(usd_path=table_path, prim_path="/World/table") self._world.scene.add(GeometryPrim(prim_path="/World/table", name=f"table_ref_geom", collision=True)) self._table_ref_geom = self._world.scene.get_object(f"table_ref_geom") self._table_ref_geom.set_local_scale(np.array([self._table_scale])) self._table_ref_geom.set_world_pose(position=self._table_position) self._table_ref_geom.set_default_state(position=self._table_position) lb = self._world.scene.compute_object_AABB(name=f"table_ref_geom") zmin = lb[0][2] zmax = lb[1][2] self._table_height = zmax async def add_controller(self): self._franka = self._world.scene.get_object("franka") self._controller = PickPlaceController( name="pick_place_controller", gripper=self._franka.gripper, robot_articulation=self._franka, end_effector_initial_height=1.1, ) def setup_scene(self): self._world = self.get_world() self._stage = omni.usd.get_context().get_stage() self.simulation_context = SimulationContext() self.add_background() self.add_light() self.add_bin() self._world.add_task( FrankaPlaying( name="franka_task", object="tuna_fish_can" )) return async def setup_post_load(self): self._world = self.get_world() self._world.scene.enable_bounding_boxes_computations() # for compute_object_AABB from add_table, # bounding box computations should be enabled before, # which means we need to wait for the scene to be loaded # That's for franka too. await self.add_table() await self.add_controller() self._world.add_physics_callback("sim_step", callback_fn=self.physics_callback) #callback names have to be unique return def physics_callback(self, step_size): current_observations = self._world.get_observations() object_position = current_observations["object"]["position"] # print(object_position) if object_position[1] > 1.25: print("picking and placing") actions = self._controller.forward( picking_position=object_position, placing_position=current_observations["object"]["goal_position"], current_joint_positions=current_observations["franka"]["joint_positions"], end_effector_orientation=euler_angles_to_quat( # np.array([0, np.pi, -np.pi/2]) np.array([0, np.pi, 0]) ), ) if self._controller.is_done(): print("done picking and placing") self._franka.apply_action(actions) return # async def setup_pre_reset(self): # return async def setup_post_reset(self): self._controller.reset() await self._world.play_async() return def world_cleanup(self): self._world.pause() return
7,073
Python
37.032258
121
0.639333
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFactory/franka_playing.py
from omni.isaac.core.tasks import BaseTask from omni.isaac.franka.franka import Franka from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.prims.geometry_prim import GeometryPrim from pxr import Gf, PhysxSchema, Usd, UsdPhysics, UsdShade, UsdGeom, Sdf, Tf, UsdLux from omni.physx.scripts import utils import numpy as np import omni def createRigidBody(stage, primPath): bodyPrim = stage.GetPrimAtPath(primPath) # UsdPhysics.RigidBodyAPI.Apply(bodyPrim) utils.setRigidBody(bodyPrim, "convexDecomposition", False) def addObjectsGeom(scene, name, scale, ini_pos, mass, orientation=None): scene.add(GeometryPrim(prim_path=f"/World/{name}", name=f"{name}_ref_geom", collision=True)) geom = scene.get_object(f"{name}_ref_geom") if orientation is None: # Usually - (x, y, z, w) # But in Isaac Sim - (w, x, y, z) orientation = np.array([1.0, 0.0, 0.0, 0.0]) object_scale = np.array([1.0, 1.0, 1.0]) if isinstance(scale, float): object_scale = np.array([scale, scale, scale]) elif isinstance(scale, list): object_scale = np.array(scale) geom.set_local_scale(object_scale) geom.set_world_pose(position=ini_pos) geom.set_default_state(position=ini_pos, orientation=orientation) massAPI = UsdPhysics.MassAPI.Apply(geom.prim.GetPrim()) massAPI.CreateMassAttr().Set(mass) return geom class FrankaPlaying(BaseTask): def __init__(self, name, object="sugar_box"): super().__init__(name=name, offset=None) self._object = object self._franka_position = np.array([-1.0, 1.8602, 0.8976]) self._franka_rotation = np.array([0.0, 0.0, 0.0, 1.0]) # (w, x, y, z) self._sugar_box_scale = 0.7 self._tomato_soup_scale = 1.0 self._tuna_fish_can_scale = 0.9 # self._obj_ini_pos = np.array([-1.0, 1.4, 1.0]) # self._obj_ini_pos = np.array([-1.5, 1.29418, 0.79]) self._obj_ini_pos = np.array([8.0, -0.05, 0.8]) self._obj_target = np.array([-0.5, 2.17, 1.1]) return def add_franka(self, scene): self._franka = scene.add( Franka( prim_path="/World/franka", name="franka", gripper_open_position=np.array([0.2, 0.2]) / get_stage_units() ) ) # adjust franka position self._franka = scene.get_object(f"franka") franka_pos = np.array(self._franka_position) self._franka.set_world_pose( position=franka_pos, orientation=self._franka_rotation ) def add_sugar_box(self, scene): sugar_box_path = get_assets_root_path() + "/Isaac/Props/YCB/Axis_Aligned_Physics/004_sugar_box.usd" add_reference_to_stage(usd_path=sugar_box_path, prim_path="/World/sugar_box") self._sugar_box_ref_geom = addObjectsGeom(scene, "sugar_box", self._sugar_box_scale, self._obj_ini_pos, 0.02) def add_tomato_soup_can(self, scene): tomato_soup_can_path = get_assets_root_path() + "/Isaac/Props/YCB/Axis_Aligned_Physics/005_tomato_soup_can.usd" add_reference_to_stage(usd_path=tomato_soup_can_path, prim_path="/World/tomato_soup_can") self._tomato_soup_can_ref_geom = addObjectsGeom(scene, "tomato_soup_can", self._tomato_soup_scale, self._obj_ini_pos, 0.02) def add_tuna_fish_can(self, scene): tuna_fish_can_path = get_assets_root_path() + "/Isaac/Props/YCB/Axis_Aligned/007_tuna_fish_can.usd" add_reference_to_stage(usd_path=tuna_fish_can_path, prim_path="/World/tuna_fish_can") # give rigid body property for visual only objects stage = omni.usd.get_context().get_stage() createRigidBody(stage, "/World/tuna_fish_can") orientation = np.array([ 0.7071068, 0.7071068, 0.0, 0.0 ]) self._tuna_fish_can_ref_geom = addObjectsGeom(scene, "tuna_fish_can", self._tuna_fish_can_scale, self._obj_ini_pos, 0.02, orientation) def set_up_scene(self, scene): super().set_up_scene(scene) self.add_franka(scene) if self._object == "sugar_box": self.add_sugar_box(scene) elif self._object == "tomato_soup_can": self.add_tomato_soup_can(scene) elif self._object == "tuna_fish_can": self.add_tuna_fish_can(scene) return def get_observations(self): current_joint_positions = self._franka.get_joint_positions() currnet_joint_velocities = self._franka.get_joint_velocities() observations = { self._franka.name: { "joint_positions": current_joint_positions, "joint_velocities": currnet_joint_velocities, }, } if self._object == "sugar_box": sugar_box_position, _ = self._sugar_box_ref_geom.get_world_pose() observations["object"] = { "position": sugar_box_position, "goal_position": self._obj_target } elif self._object == "tomato_soup_can": tomato_soup_can_position, _ = self._tomato_soup_can_ref_geom.get_world_pose() observations["object"] = { "position": tomato_soup_can_position, "goal_position": self._obj_target } elif self._object == "tuna_fish_can": tuna_fish_can_position, _ = self._tuna_fish_can_ref_geom.get_world_pose() observations["object"] = { "position": tuna_fish_can_position, "goal_position": self._obj_target } return observations def post_reset(self): self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions) self._task_achieved = False return
5,904
Python
36.373417
142
0.609417
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFactory/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFactory/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .franka_factory import FrankaGarage """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ROS2 Examples", name="FrankaGarage", title="FrankaGarage", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=FrankaGarage(), ) return
2,056
Python
41.854166
135
0.740759
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFactory/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFactory/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFactory/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNuts/pick_and_place_twice.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.franka import Franka from omni.isaac.core.objects import DynamicCuboid from omni.isaac.franka.controllers import PickPlaceController import numpy as np class HelloManip(BaseSample): def __init__(self) -> None: super().__init__() return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() franka = world.scene.add(Franka(prim_path="/World/Fancy_Franka", name="fancy_franka")) world.scene.add( DynamicCuboid( prim_path="/World/random_cube1", name="fancy_cube1", position=np.array([0.3, 0.3, 0.3]), scale=np.array([0.0515, 0.0515, 0.0515]), color=np.array([0, 0, 1.0]), ) ) world.scene.add( DynamicCuboid( prim_path="/World/random_cube2", name="fancy_cube2", position=np.array([0.5, 0.0, 0.3]), scale=np.array([0.0515, 0.0515, 0.0515]), color=np.array([0, 0, 1.0]), ) ) self._event = 0 return async def setup_post_load(self): self._world = self.get_world() self._franka = self._world.scene.get_object("fancy_franka") self._fancy_cube1 = self._world.scene.get_object("fancy_cube1") self._fancy_cube2 = self._world.scene.get_object("fancy_cube2") # Initialize a pick and place controller self._controller = PickPlaceController( name="pick_place_controller", gripper=self._franka.gripper, robot_articulation=self._franka, ) self._world.add_physics_callback("sim_step", callback_fn=self.physics_step) # World has pause, stop, play..etc # Note: if async version exists, use it in any async function is this workflow self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions) await self._world.play_async() return # This function is called after Reset button is pressed # Resetting anything in the world should happen here async def setup_post_reset(self): self._controller.reset() self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions) await self._world.play_async() return def physics_step(self, step_size): cube_position1, _ = self._fancy_cube1.get_world_pose() cube_position2, _ = self._fancy_cube2.get_world_pose() goal_position1 = np.array([-0.3, -0.3, 0.0515 / 2.0]) goal_position2 = np.array([-0.2, -0.3, 0.0515 / 2.0]) current_joint_positions = self._franka.get_joint_positions() if self._event == 0: actions = self._controller.forward( picking_position=cube_position1, placing_position=goal_position1, current_joint_positions=current_joint_positions, ) self._franka.apply_action(actions) elif self._event == 1: actions = self._controller.forward( picking_position=cube_position2, placing_position=goal_position2, current_joint_positions=current_joint_positions, ) self._franka.apply_action(actions) # Only for the pick and place controller, indicating if the state # machine reached the final state. if self._controller.is_done(): self._event += 1 self._controller.reset() return
4,083
Python
37.168224
94
0.607886
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNuts/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNuts/hello_manip_basic.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.franka import Franka from omni.isaac.core.objects import DynamicCuboid from omni.isaac.franka.controllers import PickPlaceController import numpy as np from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.utils.prims import define_prim, get_prim_at_path from omni.isaac.core.utils.rotations import euler_angles_to_quat from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.prims.geometry_prim import GeometryPrim from omni.isaac.core.prims.xform_prim import XFormPrim from omni.isaac.core.prims.rigid_prim import RigidPrim from omni.isaac.universal_robots import UR10 from omni.isaac.core.materials.physics_material import PhysicsMaterial from omni.isaac.core.physics_context.physics_context import PhysicsContext from pxr import Gf, PhysxSchema, Usd, UsdPhysics, UsdShade import carb class HelloManip(BaseSample): def __init__(self) -> None: super().__init__() # some global sim options: self._time_steps_per_second = 240 # 4.167ms aprx self._fsm_update_rate = 60 self._solverPositionIterations = 4 self._solverVelocityIterations = 1 self._solver_type = "TGS" self._ik_damping = 0.1 self._num_nuts = 2 self._num_bins = 2 # Asset Path from Nucleus # self._cube_asset_path = get_assets_root_path() + "/Isaac/Props/Blocks/nvidia_cube.usd" self._bin_asset_path = get_assets_root_path() + "/Isaac/Props/KLT_Bin/small_KLT.usd" self._nut_asset_path = get_assets_root_path() + "/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Nut/M20_Nut_Tight_R256_Franka_SI.usd" self._bin_position = np.array([ [ 0.35, -0.25, 0.1], [ 0.35, 0.25, 0.1], ]) self._bins = [] self._bins_offset = 0.1 self._nuts_position = np.array([ [0.35, -0.22, 0.2], [0.30, -0.28, 0.2], ]) # self._nut_position_x = np.array([0.28, 0.4]) # self._nut_position_y = np.array([-0.35, -0.15]) # self._nut_position_z = 0.2 self._nuts = [] self._nuts_offset = 0.005 return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() prim = get_prim_at_path("/World/defaultGroundPlane") self._setup_simulation() franka = world.scene.add(Franka(prim_path="/World/Fancy_Franka", name="fancy_franka")) # ur10 = world.scene.add(UR10(prim_path="/World/UR10", name="UR10")) # RigidPrim Ref. # https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.core/docs/index.html#omni.isaac.core.prims.RigidPrim # GeometryPrim Ref. # https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.core/docs/index.html?highlight=geometryprim#omni.isaac.core.prims.GeometryPrim for bins in range(self._num_bins): add_reference_to_stage( usd_path=self._bin_asset_path, prim_path=f"/World/bin{bins}", ) _bin = world.scene.add( RigidPrim( prim_path=f"/World/bin{bins}", name=f"bin{bins}", position=self._bin_position[bins] / get_stage_units(), orientation=euler_angles_to_quat(np.array([np.pi, 0., 0.])), mass=0.1, # kg ) ) self._bins.append(_bin) for nut in range(self._num_nuts): # nut_position = np.array([ # np.random.randint(*(self._nut_position_x*100)) / 100, # np.random.randint(*(self._nut_position_y*100)) / 100, # self._nut_position_z, # ]) add_reference_to_stage( usd_path=self._nut_asset_path, prim_path=f"/World/nut{nut}", ) nut = world.scene.add( GeometryPrim( prim_path=f"/World/nut{nut}", name=f"nut{nut}_geom", position=self._nuts_position[nut] / get_stage_units(), collision=True, # mass=0.1, # kg ) ) self._nuts.append(nut) return def _setup_simulation(self): self._scene = PhysicsContext() self._scene.set_solver_type(self._solver_type) self._scene.set_broadphase_type("GPU") self._scene.enable_gpu_dynamics(flag=True) self._scene.set_friction_offset_threshold(0.01) self._scene.set_friction_correlation_distance(0.0005) self._scene.set_gpu_total_aggregate_pairs_capacity(10 * 1024) self._scene.set_gpu_found_lost_pairs_capacity(10 * 1024) self._scene.set_gpu_heap_capacity(64 * 1024 * 1024) self._scene.set_gpu_found_lost_aggregate_pairs_capacity(10 * 1024) # added because of new errors regarding collisionstacksize physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(get_prim_at_path("/physicsScene")) physxSceneAPI.CreateGpuCollisionStackSizeAttr().Set(76000000) # or whatever min is needed async def setup_post_load(self): self._world = self.get_world() self._franka = self._world.scene.get_object("fancy_franka") # Initialize a pick and place controller self._controller = PickPlaceController( name="pick_place_controller", gripper=self._franka.gripper, robot_articulation=self._franka, ) self._world.add_physics_callback("sim_step", callback_fn=self.physics_step) # World has pause, stop, play..etc # Note: if async version exists, use it in any async function is this workflow self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions) await self._world.play_async() return # This function is called after Reset button is pressed # Resetting anything in the world should happen here async def setup_post_reset(self): self._controller.reset() self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions) await self._world.play_async() return def physics_step(self, step_size): target_position, _ = self._nuts[0].get_world_pose() target_position[2] += self._nuts_offset goal_position, _ = self._bins[1].get_world_pose() goal_position[2] += self._bins_offset # print(goal_position) current_joint_positions = self._franka.get_joint_positions() actions = self._controller.forward( picking_position=target_position, placing_position=goal_position, current_joint_positions=current_joint_positions, ) self._franka.apply_action(actions) # Only for the pick and place controller, indicating if the state # machine reached the final state. if self._controller.is_done(): self._world.pause() return
7,645
Python
39.670213
163
0.616089
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNuts/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .franka_nuts_pick_and_place import FrankaNutsBasic """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ETRIDemo", name="FrankaNutsBasic", title="FrankaNutsBasic", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=FrankaNutsBasic(), ) return
2,075
Python
42.249999
135
0.742169
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNuts/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNuts/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNuts/franka_nuts_pick_and_place.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.franka.controllers import PickPlaceController from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.tasks import BaseTask from omni.isaac.franka import Franka from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.utils.rotations import euler_angles_to_quat from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.prims.geometry_prim import GeometryPrim from omni.isaac.core.utils.prims import get_prim_at_path from omni.isaac.core.prims.rigid_prim import RigidPrim from omni.isaac.sensor import Camera import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core import SimulationContext from pxr import PhysxSchema from datetime import datetime import numpy as np import h5py class FrankaPlaying(BaseTask): #NOTE: we only cover here a subset of the task functions that are available, # checkout the base class for all the available functions to override. # ex: calculate_metrics, is_done..etc. def __init__(self, name): super().__init__(name=name, offset=None) self._num_nuts = 2 self._num_bins = 2 # Asset Path from Nucleus self._bin_asset_path = get_assets_root_path() + "/Isaac/Props/KLT_Bin/small_KLT.usd" self._nut_asset_path = get_assets_root_path() + "/Isaac/Samples/Examples/FrankaNutBolt/SubUSDs/Nut/M20_Nut_Tight_R256_Franka_SI.usd" self._bin_position = np.array([ [ 0.35, -0.25, 0.1], [ 0.35, 0.25, 0.1], ]) self._bins = [] self._bins_offset = 0.1 self._nuts_position = np.array([ [0.35, -0.22, 0.2], [0.30, -0.28, 0.2], ]) self._nuts = [] self._nuts_offset = 0.005 self._goal_position = np.array([ [0.35, 0.18, 0.2], [0.30, 0.25, 0.2], ]) self._pick_position = np.array([0, 0, 0]) self._task_achieved = False self._task_event = 0 return def setup_cameras(self): # Exception: You can not define translation and position at the same time self._camera1 = Camera( prim_path="/World/Fancy_Franka/panda_hand/hand_camera", # position=np.array([0.088, 0.0, 0.926]), translation=np.array([0.1, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 180, -90 - 25, 0 ]), degrees=True), ) self._camera1.set_clipping_range(0.1, 1000000.0) self._camera1.initialize() self._camera1.add_motion_vectors_to_frame() self._camera1.set_visibility(False) self._camera2 = Camera( prim_path="/World/top_camera", position=np.array([0.0, 0.0, 5.0]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0, 90, 0 ]), degrees=True), ) self._camera2.initialize() self._camera2.set_visibility(False) self._camera3 = Camera( prim_path="/World/front_camera", position=np.array([1.0, 0.0, 0.3]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0, 0, 180 ]), degrees=True), ) self._camera3.set_clipping_range(0.1, 1000000.0) self._camera3.set_focal_length(1.0) self._camera3.initialize() self._camera3.set_visibility(False) return def setup_bins(self, scene): for bins in range(self._num_bins): add_reference_to_stage( usd_path=self._bin_asset_path, prim_path=f"/World/bin{bins}", ) _bin = scene.add( RigidPrim( prim_path=f"/World/bin{bins}", name=f"bin{bins}", position=self._bin_position[bins] / get_stage_units(), orientation=euler_angles_to_quat(np.array([np.pi, 0., 0.])), mass=0.1, # kg ) ) self._bins.append(_bin) return def setup_nuts(self, scene): for nut in range(self._num_nuts): add_reference_to_stage( usd_path=self._nut_asset_path, prim_path=f"/World/nut{nut}", ) nut = scene.add( GeometryPrim( prim_path=f"/World/nut{nut}", name=f"nut{nut}_geom", position=self._nuts_position[nut] / get_stage_units(), collision=True, # mass=0.1, # kg ) ) self._nuts.append(nut) return # Here we setup all the assets that we care about in this task. def set_up_scene(self, scene): super().set_up_scene(scene) scene.add_default_ground_plane() self._franka = scene.add( Franka( prim_path="/World/Fancy_Franka", name="fancy_franka" ) ) self.setup_cameras() self.setup_bins(scene) self.setup_nuts(scene) return # Information exposed to solve the task is returned from the task through get_observations def get_observations(self): current_joint_positions = self._franka.get_joint_positions() currnet_joint_velocities = self._franka.get_joint_velocities() self._pick_position1, _ = self._nuts[0].get_world_pose() self._pick_position1[2] += self._nuts_offset self._pick_position2, _ = self._nuts[1].get_world_pose() self._pick_position2[2] += self._nuts_offset observations = { self._franka.name: { "joint_positions": current_joint_positions, "joint_velocities": currnet_joint_velocities, }, "nut0_geom": { "position": self._pick_position1, "goal_position": self._goal_position[0], }, "nut1_geom": { "position": self._pick_position2, "goal_position": self._goal_position[1], }, } return observations # Called before each physics step, # for instance we can check here if the task was accomplished by # changing the color of the cube once its accomplished def pre_step(self, control_index, simulation_time): return # Called after each reset, # for instance we can always set the gripper to be opened at the beginning after each reset # also we can set the cube's color to be blue def post_reset(self): self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions) # self._nuts[0].get_applied_visual_material().set_color(color=np.array([0, 0, 1.0])) self._task_achieved = False return @property def camera1(self): return self._camera1 @property def camera2(self): return self._camera2 @property def camera3(self): return self._camera3 class FrankaNutsBasic(BaseSample): def __init__(self) -> None: super().__init__() # some global sim options: self._time_steps_per_second = 240 # 4.167ms aprx self._fsm_update_rate = 60 self._solverPositionIterations = 4 self._solverVelocityIterations = 1 self._solver_type = "TGS" self._ik_damping = 0.1 self._event = 0 self._step_size = 0.01 return def _setup_simulation(self): self._scene = PhysicsContext() self._scene.set_solver_type(self._solver_type) self._scene.set_broadphase_type("GPU") self._scene.enable_gpu_dynamics(flag=True) self._scene.set_friction_offset_threshold(0.01) self._scene.set_friction_correlation_distance(0.0005) self._scene.set_gpu_total_aggregate_pairs_capacity(10 * 1024) self._scene.set_gpu_found_lost_pairs_capacity(10 * 1024) self._scene.set_gpu_heap_capacity(64 * 1024 * 1024) self._scene.set_gpu_found_lost_aggregate_pairs_capacity(10 * 1024) # added because of new errors regarding collisionstacksize physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(get_prim_at_path("/physicsScene")) physxSceneAPI.CreateGpuCollisionStackSizeAttr().Set(76000000) # or whatever min is needed def setup_dataset(self): self._f = None self._sim_time_list = [] self._joint_positions = [] self._joint_velocities = [] self._camera1_img = [] self._camera2_img = [] self._camera3_img = [] now = datetime.now() # current date and time date_time_str = now.strftime("%m_%d_%Y_%H_%M_%S") file_name = f'franka_nuts_basis_{date_time_str}.hdf5' print(file_name) self._f = h5py.File(file_name,'w') self._group_f = self._f.create_group("isaac_dataset") self._save_count = 0 self._img_f = self._group_f.create_group("camera_images") return def setup_scene(self): print("setup_scene") world = self.get_world() self.simulation_context = SimulationContext() self._setup_simulation() self.setup_dataset() # We add the task to the world here self._franka_playing = FrankaPlaying(name="my_first_task") world.add_task(self._franka_playing) return async def setup_post_load(self): print("setup_post_load") self._world = self.get_world() # The world already called the setup_scene from the task (with first reset of the world) # so we can retrieve the task objects self._franka = self._world.scene.get_object("fancy_franka") self._controller = PickPlaceController( name="pick_place_controller", gripper=self._franka.gripper, robot_articulation=self._franka, ) self._camera1 = self._franka_playing.camera1 self._camera2 = self._franka_playing.camera2 self._camera3 = self._franka_playing.camera3 self._world.add_physics_callback("sim_step", callback_fn=self.physics_step) await self._world.play_async() return async def setup_pre_reset(self): if self._f is not None: self._f.close() self._f = None elif self._f is None: print("Create new file for new data collection...") self.setup_dataset() self._save_count = 0 self._event = 0 return async def setup_post_reset(self): self._controller.reset() await self._world.play_async() return def physics_step(self, step_size): # Gets all the tasks observations self._camera1.get_current_frame() self._camera2.get_current_frame() self._camera3.get_current_frame() current_observations = self._world.get_observations() current_time = self.simulation_context.current_time current_joint_pos = current_observations["fancy_franka"]["joint_positions"] current_joint_vel = current_observations["fancy_franka"]["joint_velocities"] # print(step_size) if self._save_count % 100 == 0: if current_joint_pos is not None and current_joint_vel is not None: self._sim_time_list.append(current_time) self._joint_positions.append(current_joint_pos) self._joint_velocities.append(current_joint_vel) self._camera1_img.append(self._camera1.get_rgba()[:, :, :3]) self._camera2_img.append(self._camera2.get_rgba()[:, :, :3]) self._camera3_img.append(self._camera3.get_rgba()[:, :, :3]) print("Collecting data...") if self._event == 0: actions = self._controller.forward( picking_position=current_observations["nut0_geom"]["position"], placing_position=current_observations["nut0_geom"]["goal_position"], current_joint_positions=current_joint_pos, ) self._franka.apply_action(actions) elif self._event == 1: actions = self._controller.forward( picking_position=current_observations["nut1_geom"]["position"], placing_position=current_observations["nut1_geom"]["goal_position"], current_joint_positions=current_joint_pos, ) self._franka.apply_action(actions) self._save_count += 1 if self._controller.is_done(): self._controller.reset() self._event += 1 if self._event == 2: self.world_cleanup() return def world_cleanup(self): try: if self._f is not None: self._group_f.create_dataset(f"sim_time", data=self._sim_time_list, compression='gzip', compression_opts=9) self._group_f.create_dataset(f"joint_positions", data=self._joint_positions, compression='gzip', compression_opts=9) self._group_f.create_dataset(f"joint_velocities", data=self._joint_velocities, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"hand_camera", data=self._camera1_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"top_camera", data=self._camera2_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"front_camera", data=self._camera3_img, compression='gzip', compression_opts=9) self._f.close() print("Data saved") elif self._f is None: print("Invalid Operation Data not saved") except Exception as e: print(e) finally: self._f = None self._save_count = 0 self._world.pause() return
14,771
Python
33.921986
140
0.580259
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaNuts/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/URPalletizing/__init__.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .ur10_palletizing_extension import BinStackingExtension
493
Python
43.909087
76
0.819473
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/URPalletizing/ur10_palletizing.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import random import numpy as np import omni import h5py import omni.isaac.cortex.math_util as math_util import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core import SimulationContext from omni.isaac.core.objects.capsule import VisualCapsule from omni.isaac.core.objects.sphere import VisualSphere from omni.isaac.core.prims.xform_prim import XFormPrim from omni.isaac.core.tasks.base_task import BaseTask from omni.isaac.core.utils.rotations import euler_angles_to_quat from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.cortex.cortex_rigid_prim import CortexRigidPrim from omni.isaac.cortex.cortex_utils import get_assets_root_path from omni.isaac.cortex.robot import CortexUr10 from omni.isaac.cortex.sample_behaviors.ur10 import bin_stacking_behavior as behavior from omni.isaac.examples.cortex.cortex_base import CortexBase from omni.isaac.sensor import Camera class Ur10Assets: def __init__(self): self.assets_root_path = get_assets_root_path() self.ur10_table_usd = ( self.assets_root_path + "/Isaac/Samples/Leonardo/Stage/ur10_bin_stacking_short_suction.usd" ) self.small_klt_usd = self.assets_root_path + "/Isaac/Props/KLT_Bin/small_KLT.usd" self.background_usd = self.assets_root_path + "/Isaac/Environments/Simple_Warehouse/warehouse.usd" self.rubiks_cube_usd = self.assets_root_path + "/Isaac/Props/Rubiks_Cube/rubiks_cube.usd" def random_bin_spawn_transform(): x = random.uniform(-0.15, 0.15) y = 1.5 z = -0.15 position = np.array([x, y, z]) z = random.random() * 0.02 - 0.01 w = random.random() * 0.02 - 0.01 norm = np.sqrt(z**2 + w**2) quat = math_util.Quaternion([w / norm, 0, 0, z / norm]) if random.random() > 0.5: print("<flip>") # flip the bin so it's upside down quat = quat * math_util.Quaternion([0, 0, 1, 0]) else: print("<no flip>") return position, quat.vals class BinStackingTask(BaseTask): def __init__(self, env_path, assets) -> None: super().__init__("bin_stacking") self.assets = assets self.env_path = env_path self.bins = [] self.stashed_bins = [] self.on_conveyor = None def _spawn_bin(self, rigid_bin): x, q = random_bin_spawn_transform() rigid_bin.set_world_pose(position=x, orientation=q) rigid_bin.set_linear_velocity(np.array([0, -0.30, 0])) rigid_bin.set_visibility(True) def post_reset(self) -> None: if len(self.bins) > 0: for rigid_bin in self.bins: self.scene.remove_object(rigid_bin.name) self.bins.clear() self.on_conveyor = None def pre_step(self, time_step_index, simulation_time) -> None: """Spawn a new randomly oriented bin if the previous bin has been placed.""" spawn_new = False if self.on_conveyor is None: spawn_new = True else: (x, y, z), _ = self.on_conveyor.get_world_pose() is_on_conveyor = y > 0.0 and -0.4 < x and x < 0.4 if not is_on_conveyor: spawn_new = True if spawn_new: name = "bin_{}".format(len(self.bins)) prim_path = self.env_path + "/bins/{}".format(name) # "/Isaac/Props/KLT_Bin/small_KLT.usd" # prim_path add_reference_to_stage(usd_path=self.assets.small_klt_usd, prim_path=prim_path) self.on_conveyor = self.scene.add(CortexRigidPrim(name=name, prim_path=prim_path)) self._spawn_bin(self.on_conveyor) self.bins.append(self.on_conveyor) def world_cleanup(self): self.bins = [] self.stashed_bins = [] self.on_conveyor = None return class BinStacking(CortexBase): def __init__(self, monitor_fn=None): super().__init__() self._monitor_fn = monitor_fn self.robot = None self._sim_time_list = [] self._joint_positions = [] self._joint_velocities = [] self._camera1_img = [] self._camera2_img = [] self._camera3_img = [] self._camera4_img = [] self._camera5_img = [] self._save_count = 0 def _setup_camera(self): self._camera1 = Camera( prim_path="/World/Ur10Table/ur10/ee_link/ee_camera", # position=np.array([0.088, 0.0, 0.926]), translation=np.array([-0.15, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 180.0, -15.0, 0.0 ]), degrees=True), ) self._camera1.set_clipping_range(0.1, 1000000.0) self._camera1.set_focal_length(1.5) self._camera1.initialize() self._camera1.add_motion_vectors_to_frame() self._camera1.set_visibility(False) self._camera2 = Camera( prim_path="/World/left_camera", position=np.array([2.5, 0.0, 0.0]), # translation=np.array([0.0, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0.0, 0.0, 180.0 ]), degrees=True), ) self._camera2.set_focal_length(1.5) self._camera2.set_visibility(False) self._camera2.initialize() self._camera3 = Camera( prim_path="/World/right_camera", position=np.array([-2.5, 0.0, 0.0]), # translation=np.array([0.0, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0.0, 0.0, 0.0 ]), degrees=True), ) self._camera3.set_focal_length(1.5) self._camera3.set_visibility(False) self._camera3.initialize() self._camera4 = Camera( prim_path="/World/front_camera", position=np.array([0.0, 2.0, 0.0]), # translation=np.array([0.0, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0.0, 0.0, -90.0 ]), degrees=True), ) self._camera4.set_focal_length(1.5) self._camera4.set_visibility(False) self._camera4.initialize() self._camera5 = Camera( prim_path="/World/back_camera", position=np.array([0.5, -2.0, -0.2]), # translation=np.array([0.0, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0.0, 0.0, 90.0 ]), degrees=True), ) self._camera5.set_focal_length(1.5) self._camera5.set_visibility(False) self._camera5.initialize() def _setup_data_collection(self): self._f = h5py.File('ur_bin_palleting.hdf5','w') self._group_f = self._f.create_group("isaac_dataset") self._save_count = 0 self._img_f = self._group_f.create_group("camera_images") def setup_scene(self): world = self.get_world() self.simulation_context = SimulationContext() env_path = "/World/Ur10Table" ur10_assets = Ur10Assets() add_reference_to_stage(usd_path=ur10_assets.ur10_table_usd, prim_path=env_path) add_reference_to_stage(usd_path=ur10_assets.background_usd, prim_path="/World/Background") background_prim = XFormPrim( "/World/Background", position=[10.00, 2.00, -1.18180], orientation=[0.7071, 0, 0, 0.7071] ) self.robot = world.add_robot(CortexUr10(name="robot", prim_path="{}/ur10".format(env_path))) obs = world.scene.add( VisualSphere( "/World/Ur10Table/Obstacles/FlipStationSphere", name="flip_station_sphere", position=np.array([0.73, 0.76, -0.13]), radius=0.2, visible=False, ) ) self.robot.register_obstacle(obs) obs = world.scene.add( VisualSphere( "/World/Ur10Table/Obstacles/NavigationDome", name="navigation_dome_obs", position=[-0.031, -0.018, -1.086], radius=1.1, visible=False, ) ) self.robot.register_obstacle(obs) az = np.array([1.0, 0.0, -0.3]) ax = np.array([0.0, 1.0, 0.0]) ay = np.cross(az, ax) R = math_util.pack_R(ax, ay, az) quat = math_util.matrix_to_quat(R) obs = world.scene.add( VisualCapsule( "/World/Ur10Table/Obstacles/NavigationBarrier", name="navigation_barrier_obs", position=[0.471, 0.276, -0.463 - 0.1], orientation=quat, radius=0.5, height=0.9, visible=False, ) ) self.robot.register_obstacle(obs) obs = world.scene.add( VisualCapsule( "/World/Ur10Table/Obstacles/NavigationFlipStation", name="navigation_flip_station_obs", position=np.array([0.766, 0.755, -0.5]), radius=0.5, height=0.5, visible=False, ) ) self.robot.register_obstacle(obs) self._setup_camera() self._setup_data_collection() async def setup_post_load(self): world = self.get_world() env_path = "/World/Ur10Table" ur10_assets = Ur10Assets() if not self.robot: self.robot = world._robots["robot"] world._current_tasks.clear() world._behaviors.clear() world._logical_state_monitors.clear() self.task = BinStackingTask(env_path, ur10_assets) print(world.scene) self.task.set_up_scene(world.scene) world.add_task(self.task) self.decider_network = behavior.make_decider_network(self.robot, self._on_monitor_update) world.add_decider_network(self.decider_network) return def _on_monitor_update(self, diagnostics): decision_stack = "" if self.decider_network._decider_state.stack: decision_stack = "\n".join( [ "{0}{1}".format(" " * i, element) for i, element in enumerate(str(i) for i in self.decider_network._decider_state.stack) ] ) if self._monitor_fn: self._monitor_fn(diagnostics, decision_stack) def _on_physics_step(self, step_size): world = self.get_world() self._camera1.get_current_frame() self._camera2.get_current_frame() self._camera3.get_current_frame() self._camera4.get_current_frame() self._camera5.get_current_frame() current_time = self.simulation_context.current_time current_joint_state = self.robot.get_joints_state() current_joint_positions = current_joint_state.positions current_joint_velocities = current_joint_state.velocities print(self._save_count) if self._save_count % 50 == 0: self._sim_time_list.append(current_time) self._joint_positions.append(current_joint_positions) self._joint_velocities.append(current_joint_velocities) self._camera1_img.append(self._camera1.get_rgba()[:, :, :3]) self._camera2_img.append(self._camera2.get_rgba()[:, :, :3]) self._camera3_img.append(self._camera3.get_rgba()[:, :, :3]) self._camera4_img.append(self._camera4.get_rgba()[:, :, :3]) self._camera5_img.append(self._camera5.get_rgba()[:, :, :3]) print("Collecting data...") if self._save_count > 3000: self.save_data() self._save_count += 1 world.step(False, False) return async def on_event_async(self): world = self.get_world() await omni.kit.app.get_app().next_update_async() world.reset_cortex() world.add_physics_callback("sim_step", self._on_physics_step) await world.play_async() return async def setup_pre_reset(self): world = self.get_world() if world.physics_callback_exists("sim_step"): world.remove_physics_callback("sim_step") return def world_cleanup(self): return def save_data(self): self._group_f.create_dataset(f"sim_time", data=self._sim_time_list, compression='gzip', compression_opts=9) self._group_f.create_dataset(f"joint_positions", data=self._joint_positions, compression='gzip', compression_opts=9) self._group_f.create_dataset(f"joint_velocities", data=self._joint_velocities, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"ee_camera", data=self._camera1_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"left_camera", data=self._camera2_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"right_camera", data=self._camera3_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"front_camera", data=self._camera4_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"back_camera", data=self._camera5_img, compression='gzip', compression_opts=9) self._f.close() print("Data saved") self._save_count = 0 self._world.pause() return
14,252
Python
35.359694
126
0.57648
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/URPalletizing/ur10_palletizing_extension.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import os import omni.ui as ui from omni.isaac.cortex.cortex_world import CortexWorld from omni.isaac.examples.base_sample import BaseSampleExtension from omni.isaac.ui.ui_utils import btn_builder, cb_builder, get_style, str_builder from .ur10_palletizing import BinStacking class BinStackingExtension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ETRIDemo", name="UR10 Palletizing", title="UR10 Palletizing", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/replicator_tutorials/tutorial_replicator_ur10_palletizing.html#isaac-sim-app-tutorial-replicator-ur10-palletizing", overview="This Example shows how to do Palletizing using UR10 robot and Cortex behaviors in Isaac Sim.\n\nPress the 'Open in IDE' button to view the source code.", sample=BinStacking(self.on_diagnostics), file_path=os.path.abspath(__file__), number_of_extra_frames=2, ) self.decision_stack = "" self.task_ui_elements = {} frame = self.get_frame(index=0) self.build_task_controls_ui(frame) return def on_diagnostics(self, diagnostic, decision_stack): if self.decision_stack != decision_stack: self.decision_stack = decision_stack if decision_stack: decision_stack = "\n".join( [ "{0}{1}".format(" " * (i + 1) if i > 0 else "", element) for i, element in enumerate(decision_stack.replace("]", "").split("[")) ] ) self.state_model.set_value(decision_stack) if diagnostic.bin_name: self.selected_bin.set_value(str(diagnostic.bin_name)) self.bin_base.set_value(str(diagnostic.bin_base.prim_path)) self.grasp_reached.set_value((diagnostic.grasp_reached)) self.is_attached.set_value((diagnostic.attached)) self.needs_flip.set_value((diagnostic.needs_flip)) else: self.selected_bin.set_value(str("No Bin Selected")) self.bin_base.set_value("") self.grasp_reached.set_value(False) self.is_attached.set_value(False) self.needs_flip.set_value(False) def get_world(self): return CortexWorld.instance() def _on_start_button_event(self): asyncio.ensure_future(self.sample.on_event_async()) self.task_ui_elements["Start Palletizing"].enabled = False return def post_reset_button_event(self): self.task_ui_elements["Start Palletizing"].enabled = True return def post_load_button_event(self): self.task_ui_elements["Start Palletizing"].enabled = True return def post_clear_button_event(self): self.task_ui_elements["Start Palletizing"].enabled = False return def build_task_controls_ui(self, frame): with frame: with ui.VStack(spacing=5): # Update the Frame Title frame.title = "Task Controls" frame.visible = True dict = { "label": "Start Palletizing", "type": "button", "text": "Start Palletizing", "tooltip": "Start Palletizing", "on_clicked_fn": self._on_start_button_event, } self.task_ui_elements["Start Palletizing"] = btn_builder(**dict) self.task_ui_elements["Start Palletizing"].enabled = False # with self._main_stack: with self.get_frame(index=1): self.get_frame(index=1).title = "Diagnostics" self.get_frame(index=1).visible = True self._diagnostics = ui.VStack(spacing=5) # self._diagnostics.enabled = False with self._diagnostics: ui.Label("Decision Stack", height=20) self.state_model = ui.SimpleStringModel() ui.StringField(self.state_model, multiline=True, height=120) self.selected_bin = str_builder("Selected Bin", "<No Bin Selected>", read_only=True) self.bin_base = str_builder("Bin Base", "", read_only=True) self.grasp_reached = cb_builder("Grasp Reached", False) self.is_attached = cb_builder("Is Attached", False) self.needs_flip = cb_builder("Needs Flip", False)
5,043
Python
42.860869
187
0.608368
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloManipulator/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloManipulator/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .hello_manip import HelloManip """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="", name="HelloManipulator", title="HelloManipulator", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=HelloManip(), ) return
2,044
Python
41.604166
135
0.739726
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloManipulator/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloManipulator/hello_manip.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample # This extension has franka related tasks and controllers as well from omni.isaac.franka import Franka from omni.isaac.core.objects import DynamicCuboid from omni.isaac.franka.controllers import PickPlaceController from omni.isaac.franka.tasks import PickPlace from omni.isaac.core.tasks import BaseTask import numpy as np class FrankaPlaying(BaseTask): #NOTE: we only cover here a subset of the task functions that are available, # checkout the base class for all the available functions to override. # ex: calculate_metrics, is_done..etc. def __init__(self, name): super().__init__(name=name, offset=None) self._goal_position = np.array([-0.3, -0.3, 0.0515 / 2.0]) self._task_achieved = False return # Here we setup all the assets that we care about in this task. def set_up_scene(self, scene): super().set_up_scene(scene) scene.add_default_ground_plane() self._cube = scene.add(DynamicCuboid(prim_path="/World/random_cube", name="fancy_cube", position=np.array([0.3, 0.3, 0.3]), scale=np.array([0.0515, 0.0515, 0.0515]), color=np.array([0, 0, 1.0]))) self._franka = scene.add(Franka(prim_path="/World/Fancy_Franka", name="fancy_franka")) return # Information exposed to solve the task is returned from the task through get_observations def get_observations(self): cube_position, _ = self._cube.get_world_pose() current_joint_positions = self._franka.get_joint_positions() observations = { self._franka.name: { "joint_positions": current_joint_positions, }, self._cube.name: { "position": cube_position, "goal_position": self._goal_position } } return observations # Called before each physics step, # for instance we can check here if the task was accomplished by # changing the color of the cube once its accomplished def pre_step(self, control_index, simulation_time): cube_position, _ = self._cube.get_world_pose() if not self._task_achieved and np.mean(np.abs(self._goal_position - cube_position)) < 0.02: # Visual Materials are applied by default to the cube # in this case the cube has a visual material of type # PreviewSurface, we can set its color once the target is reached. self._cube.get_applied_visual_material().set_color(color=np.array([0, 1.0, 0])) self._task_achieved = True return # Called after each reset, # for instance we can always set the gripper to be opened at the beginning after each reset # also we can set the cube's color to be blue def post_reset(self): self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions) self._cube.get_applied_visual_material().set_color(color=np.array([0, 0, 1.0])) self._task_achieved = False return class HelloManip(BaseSample): def __init__(self) -> None: super().__init__() return def setup_scene(self): world = self.get_world() # We add the task to the world here world.add_task(FrankaPlaying(name="my_first_task")) return async def setup_post_load(self): self._world = self.get_world() # The world already called the setup_scene from the task (with first reset of the world) # so we can retrieve the task objects self._franka = self._world.scene.get_object("fancy_franka") self._controller = PickPlaceController( name="pick_place_controller", gripper=self._franka.gripper, robot_articulation=self._franka, ) self._world.add_physics_callback("sim_step", callback_fn=self.physics_step) await self._world.play_async() return async def setup_post_reset(self): self._controller.reset() await self._world.play_async() return def physics_step(self, step_size): # Gets all the tasks observations current_observations = self._world.get_observations() actions = self._controller.forward( picking_position=current_observations["fancy_cube"]["position"], placing_position=current_observations["fancy_cube"]["goal_position"], current_joint_positions=current_observations["fancy_franka"]["joint_positions"], ) self._franka.apply_action(actions) if self._controller.is_done(): self._world.pause() return
5,289
Python
42.719008
99
0.629609
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloManipulator/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloManipulator/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/DingoLibrary/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/DingoLibrary/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .dingo_library import DingoLibrary """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ROS2 Examples", name="DingoLibrary", title="DingoLibrary", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=DingoLibrary(), ) return
2,055
Python
41.833332
135
0.740633
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/DingoLibrary/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/DingoLibrary/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/DingoLibrary/dingo_library.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample import numpy as np # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.objects import DynamicCuboid from omni.isaac.sensor import Camera, RotatingLidarPhysX from omni.isaac.core import World import omni.graph.core as og import usdrt.Sdf import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core import SimulationContext from omni.physx.scripts import deformableUtils, physicsUtils from pxr import UsdGeom, Gf, UsdPhysics, Sdf, Gf, Tf, UsdLux from PIL import Image import carb import h5py import omni import cv2 class DingoLibrary(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) return def og_setup(self): domain_id = 0 try: # Twist OG maxLinearSpeed = 3.0 wheelDistance = 0.23632 wheelRadius = 0.049 jointNames = ["left_wheel_joint", "right_wheel_joint"] base_link_prim = "/World/dingo/base_link" og.Controller.edit( {"graph_path": "/ROS2DiffDrive", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("subscribeTwist", "omni.isaac.ros2_bridge.ROS2SubscribeTwist"), ("scaleToFromStage", "omni.isaac.core_nodes.OgnIsaacScaleToFromStageUnit"), ("breakLinVel", "omni.graph.nodes.BreakVector3"), ("breakAngVel", "omni.graph.nodes.BreakVector3"), ("diffController", "omni.isaac.wheeled_robots.DifferentialController"), ("artController", "omni.isaac.core_nodes.IsaacArticulationController"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", domain_id), ("diffController.inputs:maxLinearSpeed", maxLinearSpeed), ("diffController.inputs:wheelDistance", wheelDistance), ("diffController.inputs:wheelRadius", wheelRadius), ("artController.inputs:jointNames", jointNames), ("artController.inputs:usePath", False), ("artController.inputs:targetPrim", [usdrt.Sdf.Path(base_link_prim)]), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "subscribeTwist.inputs:execIn"), ("onPlaybackTick.outputs:tick", "artController.inputs:execIn"), ("context.outputs:context", "subscribeTwist.inputs:context"), ("subscribeTwist.outputs:execOut", "diffController.inputs:execIn"), ("subscribeTwist.outputs:angularVelocity", "breakAngVel.inputs:tuple"), ("subscribeTwist.outputs:linearVelocity", "scaleToFromStage.inputs:value"), ("scaleToFromStage.outputs:result", "breakLinVel.inputs:tuple"), ("breakAngVel.outputs:z", "diffController.inputs:angularVelocity"), ("breakLinVel.outputs:x", "diffController.inputs:linearVelocity"), # ("diffController.outputs:effortCommand", "artController.inputs:effortCommand"), # ("diffController.outputs:positionCommand", "artController.inputs:positionCommand"), ("diffController.outputs:velocityCommand", "artController.inputs:velocityCommand"), ], }, ) # Static TF OG og.Controller.edit( {"graph_path": "/ROS2TF", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("publishTF", "omni.isaac.ros2_bridge.ROS2PublishTransformTree"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", domain_id), ("publishTF.inputs:parentPrim", [usdrt.Sdf.Path("/World/dingo/base_link")]), ("publishTF.inputs:targetPrims", [ usdrt.Sdf.Path("/World/dingo/left_wheel_link"), usdrt.Sdf.Path("/World/dingo/right_wheel_link"), usdrt.Sdf.Path("/World/dingo/base_link/velodyne_frame"), usdrt.Sdf.Path("/World/dingo/base_link/realsense_frame"), usdrt.Sdf.Path("/World/dingo/base_link/realsense_frame/realsense_left_stereo_frame"), usdrt.Sdf.Path("/World/dingo/base_link/realsense_frame/realsense_right_stereo_frame"), ]), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "publishTF.inputs:execIn"), ("context.outputs:context", "publishTF.inputs:context"), ("readSimTime.outputs:simulationTime", "publishTF.inputs:timeStamp"), ], }, ) # Odom TF OG og.Controller.edit( {"graph_path": "/ROS2Odom", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("computeOdom", "omni.isaac.core_nodes.IsaacComputeOdometry"), ("publishOdom", "omni.isaac.ros2_bridge.ROS2PublishOdometry"), ("publishRawTF", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", domain_id), ("computeOdom.inputs:chassisPrim", [usdrt.Sdf.Path("/World/dingo")]), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "computeOdom.inputs:execIn"), ("onPlaybackTick.outputs:tick", "publishOdom.inputs:execIn"), ("onPlaybackTick.outputs:tick", "publishRawTF.inputs:execIn"), ("readSimTime.outputs:simulationTime", "publishOdom.inputs:timeStamp"), ("readSimTime.outputs:simulationTime", "publishRawTF.inputs:timeStamp"), ("context.outputs:context", "publishOdom.inputs:context"), ("context.outputs:context", "publishRawTF.inputs:context"), ("computeOdom.outputs:angularVelocity", "publishOdom.inputs:angularVelocity"), ("computeOdom.outputs:linearVelocity", "publishOdom.inputs:linearVelocity"), ("computeOdom.outputs:orientation", "publishOdom.inputs:orientation"), ("computeOdom.outputs:position", "publishOdom.inputs:position"), ("computeOdom.outputs:orientation", "publishRawTF.inputs:rotation"), ("computeOdom.outputs:position", "publishRawTF.inputs:translation"), ], }, ) # Clock OG og.Controller.edit( {"graph_path": "/ROS2Clock", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("publishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", domain_id), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "publishClock.inputs:execIn"), ("readSimTime.outputs:simulationTime", "publishClock.inputs:timeStamp"), ("context.outputs:context", "publishClock.inputs:context"), ], }, ) # 2D Lidar OG og.Controller.edit( {"graph_path": "/ROS2LaserScan", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("readLidar", "omni.isaac.range_sensor.IsaacReadLidarBeams"), ("publishLidar", "omni.isaac.ros2_bridge.ROS2PublishLaserScan"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", domain_id), ("publishLidar.inputs:frameId", "velodyne_frame"), ("readLidar.inputs:lidarPrim", [usdrt.Sdf.Path("/World/dingo/base_link/velodyne_frame/Lidar/laserscan_lidar")]), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "readLidar.inputs:execIn"), ("context.outputs:context", "publishLidar.inputs:context"), ("readSimTime.outputs:simulationTime", "publishLidar.inputs:timeStamp"), ("readLidar.outputs:execOut", "publishLidar.inputs:execIn"), ("readLidar.outputs:azimuthRange", "publishLidar.inputs:azimuthRange"), ("readLidar.outputs:depthRange", "publishLidar.inputs:depthRange"), ("readLidar.outputs:horizontalFov", "publishLidar.inputs:horizontalFov"), ("readLidar.outputs:horizontalResolution", "publishLidar.inputs:horizontalResolution"), ("readLidar.outputs:intensitiesData", "publishLidar.inputs:intensitiesData"), ("readLidar.outputs:linearDepthData", "publishLidar.inputs:linearDepthData"), ("readLidar.outputs:numCols", "publishLidar.inputs:numCols"), ("readLidar.outputs:numRows", "publishLidar.inputs:numRows"), ("readLidar.outputs:rotationRate", "publishLidar.inputs:rotationRate"), ], }, ) # 3D Lidar OG og.Controller.edit( {"graph_path": "/ROS2PointCloud", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("readLidar", "omni.isaac.range_sensor.IsaacReadLidarPointCloud"), ("publishLidar", "omni.isaac.ros2_bridge.ROS2PublishPointCloud"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", domain_id), ("publishLidar.inputs:frameId", "velodyne_frame"), ("readLidar.inputs:lidarPrim", [usdrt.Sdf.Path("/World/dingo/base_link/velodyne_frame/Lidar/pointcloud_lidar")]), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "readLidar.inputs:execIn"), ("context.outputs:context", "publishLidar.inputs:context"), ("readSimTime.outputs:simulationTime", "publishLidar.inputs:timeStamp"), ("readLidar.outputs:execOut", "publishLidar.inputs:execIn"), ("readLidar.outputs:data", "publishLidar.inputs:data"), ], }, ) # Left Camera OG og.Controller.edit( {"graph_path": "/ROS2CameraLeft", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("renderer", "omni.isaac.core_nodes.IsaacCreateRenderProduct"), ("RGBPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("DepthPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("CameraInfoPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", domain_id), ("renderer.inputs:cameraPrim", [usdrt.Sdf.Path("/World/dingo/base_link/realsense_frame/realsense_left_stereo_frame/realsense_left_stereo_camera")]), ("RGBPublish.inputs:topicName", "/left/rgb"), ("RGBPublish.inputs:type", "rgb"), ("RGBPublish.inputs:resetSimulationTimeOnStop", True), ("RGBPublish.inputs:frameId", "realsense_left_stereo_frame"), ("DepthPublish.inputs:topicName", "/left/depth"), ("DepthPublish.inputs:type", "depth"), ("DepthPublish.inputs:resetSimulationTimeOnStop", True), ("DepthPublish.inputs:frameId", "realsense_left_stereo_frame"), ("CameraInfoPublish.inputs:topicName", "/left/camera_info"), ("CameraInfoPublish.inputs:type", "camera_info"), ("CameraInfoPublish.inputs:resetSimulationTimeOnStop", True), ("CameraInfoPublish.inputs:frameId", "realsense_left_stereo_frame"), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "renderer.inputs:execIn"), ("context.outputs:context", "RGBPublish.inputs:context"), ("context.outputs:context", "DepthPublish.inputs:context"), ("context.outputs:context", "CameraInfoPublish.inputs:context"), ("renderer.outputs:execOut", "RGBPublish.inputs:execIn"), ("renderer.outputs:execOut", "DepthPublish.inputs:execIn"), ("renderer.outputs:execOut", "CameraInfoPublish.inputs:execIn"), ("renderer.outputs:renderProductPath", "RGBPublish.inputs:renderProductPath"), ("renderer.outputs:renderProductPath", "DepthPublish.inputs:renderProductPath"), ("renderer.outputs:renderProductPath", "CameraInfoPublish.inputs:renderProductPath"), ], }, ) # Right Camera OG og.Controller.edit( {"graph_path": "/ROS2CameraRight", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("renderer", "omni.isaac.core_nodes.IsaacCreateRenderProduct"), ("RGBPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("DepthPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("CameraInfoPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", domain_id), ("renderer.inputs:cameraPrim", [usdrt.Sdf.Path("/World/dingo/base_link/realsense_frame/realsense_right_stereo_frame/realsense_right_stereo_camera")]), ("RGBPublish.inputs:topicName", "/right/rgb"), ("RGBPublish.inputs:type", "rgb"), ("RGBPublish.inputs:resetSimulationTimeOnStop", True), ("RGBPublish.inputs:frameId", "realsense_right_stereo_frame"), ("DepthPublish.inputs:topicName", "/right/depth"), ("DepthPublish.inputs:type", "depth"), ("DepthPublish.inputs:resetSimulationTimeOnStop", True), ("DepthPublish.inputs:frameId", "realsense_right_stereo_frame"), ("CameraInfoPublish.inputs:topicName", "/right/camera_info"), ("CameraInfoPublish.inputs:type", "camera_info"), ("CameraInfoPublish.inputs:resetSimulationTimeOnStop", True), ("CameraInfoPublish.inputs:frameId", "realsense_right_stereo_frame"), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "renderer.inputs:execIn"), ("context.outputs:context", "RGBPublish.inputs:context"), ("context.outputs:context", "DepthPublish.inputs:context"), ("context.outputs:context", "CameraInfoPublish.inputs:context"), ("renderer.outputs:execOut", "RGBPublish.inputs:execIn"), ("renderer.outputs:execOut", "DepthPublish.inputs:execIn"), ("renderer.outputs:execOut", "CameraInfoPublish.inputs:execIn"), ("renderer.outputs:renderProductPath", "RGBPublish.inputs:renderProductPath"), ("renderer.outputs:renderProductPath", "DepthPublish.inputs:renderProductPath"), ("renderer.outputs:renderProductPath", "CameraInfoPublish.inputs:renderProductPath"), ], }, ) except Exception as e: print(e) def add_background(self): bg_path = self._server_root + "/Projects/RBROS2/LibraryNoRoof/Library_No_Roof_Collide_Light.usd" add_reference_to_stage( usd_path=bg_path, prim_path=f"/World/Library_No_Roof", ) bg_mesh = UsdGeom.Mesh.Get(self._stage, "/World/Library_No_Roof") # physicsUtils.set_or_add_translate_op(bg_mesh, translate=Gf.Vec3f(0.0, 0.0, 0.0)) # physicsUtils.set_or_add_orient_op(bg_mesh, orient=Gf.Quatf(-0.5, -0.5, -0.5, -0.5)) physicsUtils.set_or_add_scale_op(bg_mesh, scale=Gf.Vec3f(0.01, 0.01, 0.01)) def add_dingo(self): dingo_usd_path = self._server_root + "/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Robots/Clearpath/Dingo/dingo.usd" add_reference_to_stage( usd_path=dingo_usd_path, prim_path=f"/World/dingo", ) dingo_mesh = UsdGeom.Mesh.Get(self._stage, "/World/dingo") physicsUtils.set_or_add_translate_op(dingo_mesh, translate=Gf.Vec3f(0.0, 0.0, 0.02)) # physicsUtils.set_or_add_orient_op(dingo_mesh, orient=Gf.Quatf(-0.5, -0.5, -0.5, -0.5)) # physicsUtils.set_or_add_scale_op(dingo_mesh, scale=Gf.Vec3f(0.001, 0.001, 0.001)) # Dingo Left Cam has a translation Error left_cam = UsdGeom.Mesh.Get(self._stage, "/World/dingo/base_link/realsense_frame/realsense_left_stereo_frame/realsense_left_stereo_camera") physicsUtils.set_or_add_translate_op(left_cam, translate=Gf.Vec3f(0.0, 0.0, 0.0)) def lidar_setup(self): self._2d_lidar = RotatingLidarPhysX( prim_path="/World/dingo/base_link/velodyne_frame/Lidar/laserscan_lidar", name="laserscan_lidar", translation=np.array([0.0, 0.0, 0.0]), ) self._2d_lidar.set_valid_range([0.4, 10.0]) self._2d_lidar.add_depth_data_to_frame() self._2d_lidar.add_point_cloud_data_to_frame() self._2d_lidar.enable_visualization(high_lod=False, draw_points=False, draw_lines=False) self._3d_lidar = RotatingLidarPhysX( prim_path="/World/dingo/base_link/velodyne_frame/Lidar/pointcloud_lidar", name="pointcloud_lidar", translation=np.array([0.0, 0.0, 0.0]), valid_range=(0.4, 10.0), ) self._3d_lidar.set_resolution([0.4, 2.0]) self._3d_lidar.add_depth_data_to_frame() self._3d_lidar.add_point_cloud_data_to_frame() self._3d_lidar.enable_visualization(high_lod=True, draw_points=False, draw_lines=False) def add_light(self): sphereLight1 = UsdLux.SphereLight.Define(self._stage, Sdf.Path("/World/SphereLight1")) sphereLight1.CreateIntensityAttr(100000) sphereLight1.CreateRadiusAttr(100.0) sphereLight1.AddTranslateOp().Set(Gf.Vec3f(885.0, 657.0, 226.0)) def setup_scene(self): self._world = self.get_world() self._stage = omni.usd.get_context().get_stage() self.simulation_context = SimulationContext() self.add_background() self.add_dingo() self.lidar_setup() self.og_setup() return async def setup_post_load(self): self._world.add_physics_callback("sim_step", callback_fn=self.physics_callback) #callback names have to be unique return def physics_callback(self, step_size): return # async def setup_pre_reset(self): # return # async def setup_post_reset(self): # return def world_cleanup(self): self._world.pause() return
23,420
Python
54.368794
174
0.55205
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/DingoLibrary/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorScatter2D/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorScatter2D/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .replicator_basic import Scatter2D """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="Replicator", name="Scatter2D", title="Scatter2D", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=Scatter2D(), ) return
2,043
Python
41.583332
135
0.739599
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorScatter2D/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorScatter2D/replicator_basic.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.stage import open_stage import omni.replicator.core as rep import carb.settings import numpy as np from os.path import expanduser import datetime now = datetime.datetime.now() class Scatter2D(BaseSample): def __init__(self) -> None: super().__init__() self.assets_root_path = get_assets_root_path() self._nucleus_server_path = "omniverse://localhost/NVIDIA/" # Enable scripts carb.settings.get_settings().set_bool("/app/omni.graph.scriptnode/opt_in", True) # Disable capture on play and async rendering carb.settings.get_settings().set("/omni/replicator/captureOnPlay", False) carb.settings.get_settings().set("/omni/replicator/asyncRendering", False) carb.settings.get_settings().set("/app/asyncRendering", False) self.spheres = None self._sim_step = 0 self.collision_objects = [] # Replicator Writerdir now_str = now.strftime("%Y-%m-%d_%H:%M:%S") self._out_dir = str(expanduser("~") + "/Documents/scatter2D_sample_" + now_str) return def randomize_spheres(self): self.spheres = rep.create.sphere(scale=0.5, count=5) with self.spheres: rep.randomizer.scatter_2d(self.collision_objects, check_for_collisions=True) def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() self.cam = rep.create.camera(position=(0, 0, 8), look_at=(0, 0, 0)) self.rp = rep.create.render_product(self.cam, resolution=(1024, 1024)) self.plane = rep.create.plane(scale=4, position = (0, 0, 0.1), rotation=(0, 0, 0), visible=True) self.collision_objects.append(self.plane) rep.randomizer.register(self.randomize_spheres) return async def setup_post_load(self): with rep.trigger.on_frame(num_frames=20): rep.randomizer.randomize_spheres() # Create a writer and apply the augmentations to its corresponding annotators self._writer = rep.WriterRegistry.get("BasicWriter") print(f"Writing data to: {self._out_dir}") self._writer.initialize( output_dir=self._out_dir, rgb=True, bounding_box_2d_tight=True, ) # Attach render product to writer self._writer.attach([self.rp]) return
2,958
Python
33.811764
104
0.664976
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorScatter2D/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorScatter2D/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaCabinet/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaCabinet/ros2_twist_sub.py
import numpy as np # ROS2 imports import rclpy from rclpy.node import Node from std_msgs.msg import Float32 from geometry_msgs.msg import Twist, PoseStamped def quaternion_multiply(q1, q2): w1, x1, y1, z1 = q1 w2, x2, y2, z2 = q2 w = w1*w2 - x1*x2 - y1*y2 - z1*z2 x = w1*x2 + x1*w2 + y1*z2 - z1*y2 y = w1*y2 - x1*z2 + y1*w2 + z1*x2 z = w1*z2 + x1*y2 - y1*x2 + z1*w2 return np.array([w, x, y, z]) class QuestROS2Sub(Node): def __init__(self): super().__init__('questros2_subscriber') queue_size = 10 # Queue Size self._rh_twist_sub = self.create_subscription( Twist, 'q2r_right_hand_twist', self.twist_sub_callback, queue_size ) self._rh_pose_sub = self.create_subscription( PoseStamped, 'q2r_right_hand_pose', self.pose_sub_callback, queue_size ) self._rh_index_btn_sub = self.create_subscription( Float32, 'right_press_index', self.btn_sub_callback, queue_size ) self._cur_twist = Twist() self._cur_pose = PoseStamped() self._btn_press = False def twist_sub_callback(self, msg): # self.get_logger().info(f""" # x : {msg.linear.x:.3f} / y : {msg.linear.y:.3f} / z : {msg.linear.z:.3f} # r : {msg.angular.x:.3f} / p : {msg.angular.y:.3f} / y : {msg.angular.z:.3f} # """) self._cur_twist = msg def pose_sub_callback(self, msg): # self.get_logger().info(f""" # x : {msg.pose.position.x:.3f} / y : {msg.pose.position.y:.3f} / z : {msg.pose.position.z:.3f} # x : {msg.pose.orientation.x:.3f} / y : {msg.pose.orientation.y:.3f} / z : {msg.pose.orientation.z:.3f} / w : {msg.pose.orientation.w:.3f} # """) self._cur_pose = msg def btn_sub_callback(self, msg): if msg.data == 1.0: self._btn_press = True else: self._btn_press = False # print(f"msg.data: {msg.data} / self._btn_press: {self._btn_press}") def get_twist(self): # return self._cur_twist lin_x, lin_y, lin_z = self._cur_twist.linear.x, self._cur_twist.linear.y, self._cur_twist.linear.z ang_x, ang_y, ang_z = self._cur_twist.angular.x, self._cur_twist.angular.y, self._cur_twist.angular.z lin_x *= 5 lin_y *= 2 lin_z *= 2 return [ lin_x, lin_y, lin_z, 0.0, 0.0, 0.0] def get_pose(self, z_offset, q_offset): position = np.array([ self._cur_pose.pose.position.x * 2, self._cur_pose.pose.position.y * 2, self._cur_pose.pose.position.z * 2 + z_offset ]) orientation = np.array([ self._cur_pose.pose.orientation.x, self._cur_pose.pose.orientation.y, self._cur_pose.pose.orientation.z, self._cur_pose.pose.orientation.w ]) orientation = quaternion_multiply(q_offset, orientation) isaac_orientation = np.array([ orientation[3], orientation[0], orientation[1], orientation[2], ]) return position, isaac_orientation def get_right_btn(self): return self._btn_press def main(args=None): """Do enter into this main function first.""" rclpy.init(args=args) quest_ros2_sub = QuestROS2Sub() rclpy.spin(quest_ros2_sub) quest_ros2_sub.destroy_node() rclpy.shutdown() if __name__ == '__main__': """main function""" main()
3,514
Python
28.291666
151
0.550939
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaCabinet/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .franka_cabinet import FrankaCabinet """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ROS2 Examples", name="FrankaCabinet", title="FrankaCabinet", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=FrankaCabinet(), ) return
2,060
Python
41.937499
135
0.741262
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaCabinet/franka_cabinet.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample import numpy as np from omni.isaac.core.materials.physics_material import PhysicsMaterial from omni.isaac.core.prims.geometry_prim import GeometryPrim # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html from pxr import UsdGeom, Gf, UsdPhysics, Sdf, Gf, Tf, UsdLux, UsdShade from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController from omni.isaac.franka import Franka from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root import carb import omni import rclpy import asyncio from .ros2_twist_sub import QuestROS2Sub def addObjectsGeom(scene, name, scale, ini_pos, collision=None, mass=None, orientation=None): scene.add(GeometryPrim(prim_path=f"/World/{name}", name=f"{name}_ref_geom", collision=True)) geom = scene.get_object(f"{name}_ref_geom") if orientation is None: # Usually - (x, y, z, w) # But in Isaac Sim - (w, x, y, z) orientation = np.array([1.0, 0.0, 0.0, 0.0]) geom.set_local_scale(scale) geom.set_world_pose(position=ini_pos) geom.set_default_state(position=ini_pos, orientation=orientation) geom.set_collision_enabled(False) if collision is not None: geom.set_collision_enabled(True) geom.set_collision_approximation(collision) if mass is not None: massAPI = UsdPhysics.MassAPI.Apply(geom.prim.GetPrim()) massAPI.CreateMassAttr().Set(mass) return geom class FrankaCabinet(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self._isaac_assets_path = get_assets_root_path() self.CUBE_URL = self._isaac_assets_path + "/Isaac/Props/Blocks/nvidia_cube.usd" self.CABINET_URL = self._server_root + "/Projects/RBROS2/Quest2ROS/sektin_cabinet_light.usd" self._quest_ros2_sub_node = None self._controller = None self._articulation_controller = None return def __del__(self): if self._quest_ros2_sub_node is not None: self._quest_ros2_sub_node.destroy_node() return async def ros_loop(self): while rclpy.ok(): rclpy.spin_once(self._quest_ros2_sub_node, timeout_sec=0) await asyncio.sleep(1e-4) def add_light(self): sphereLight1 = UsdLux.SphereLight.Define(self._stage, Sdf.Path("/World/SphereLight")) sphereLight1.CreateIntensityAttr(10000) sphereLight1.CreateRadiusAttr(0.1) sphereLight1.AddTranslateOp().Set(Gf.Vec3f(1.0, 0.0, 1.0)) def add_cabinet(self): add_reference_to_stage(usd_path=self.CABINET_URL, prim_path=f"/World/Cabinet") self._cabinet_geom = addObjectsGeom( self._world.scene, "Cabinet", scale=np.array([1.0, 1.0, 1.0]), ini_pos=np.array([0.9, 0.4, 0.4]), collision=None, mass=None, orientation=np.array([0.0, 0.0, 0.0, 1.0]) ) def add_franka(self): self._franka = self._world.scene.add( Franka( prim_path="/World/Fancy_Franka", name="fancy_franka" ) ) def setup_scene(self): self._world = self.get_world() self._stage = omni.usd.get_context().get_stage() self._world.scene.add_default_ground_plane() self.add_franka() self.add_light() self.add_cabinet() return def add_franka_material(self): self._franka_finger_physics_material = PhysicsMaterial( prim_path="/World/PhysicsMaterials/FrankaFingerMaterial", name="franka_finger_material_physics", static_friction=0.9, dynamic_friction=0.9, ) franka_left_finger = self._world.stage.GetPrimAtPath( "/World/Fancy_Franka/panda_leftfinger/geometry/panda_leftfinger" ) x = UsdShade.MaterialBindingAPI.Apply(franka_left_finger) x.Bind( self._franka_finger_physics_material.material, bindingStrength="weakerThanDescendants", materialPurpose="physics", ) franka_right_finger = self._world.stage.GetPrimAtPath( "/World/Fancy_Franka/panda_rightfinger/geometry/panda_rightfinger" ) x2 = UsdShade.MaterialBindingAPI.Apply(franka_right_finger) x2.Bind( self._franka_finger_physics_material.material, bindingStrength="weakerThanDescendants", materialPurpose="physics", ) async def setup_post_load(self): self._world = self.get_world() self._my_franka = self._world.scene.get_object("fancy_franka") self._my_gripper = self._my_franka.gripper self.add_franka_material() # RMPFlow controller self._controller = RMPFlowController( name="target_follower_controller", robot_articulation=self._my_franka ) # ROS 2 init rclpy.init(args=None) self._quest_ros2_sub_node = QuestROS2Sub() self._articulation_controller = self._my_franka.get_articulation_controller() self._world.add_physics_callback("sim_step", callback_fn=self.physics_callback) await self.ros_loop() return def physics_callback(self, step_size): ee_position, ee_orientation = self._quest_ros2_sub_node.get_pose( z_offset=0.8, # z -180 > 0, 0, -1, 0 # q_offset=np.array([0.0, 0.0, 0.0, 1.0]) # x 90 / z -180 # q_offset=np.array([0, 0.7071068, -0.7071068, 0 ]) # y 90 / z -180 q_offset=np.array([-0.7071068, 0, -0.7071068, 0 ]) ) gripper_command = self._quest_ros2_sub_node.get_right_btn() if np.array_equal( ee_position, np.array([0.0, 0.0, 0.0]) ): ee_position = np.array([0.4, 0, 0.5]) if gripper_command: self._my_gripper.close() else: self._my_gripper.open() # RMPFlow controller actions = self._controller.forward( target_end_effector_position=ee_position, # target_end_effector_orientation=ee_orientation, # w x y z => x y z w # 0 0 1 0 => 0 1 0 0 # 0 0 1 0 => 0 1 0 0 target_end_effector_orientation=np.array([ 0.5, -0.5, 0.5, -0.5 ]), ) self._articulation_controller.apply_action(actions) return async def setup_pre_reset(self): world = self.get_world() if world.physics_callback_exists("sim_step"): world.remove_physics_callback("sim_step") self._controller.reset() return async def setup_post_reset(self): self._controller.reset() await self._world.play_async() return def world_cleanup(self): self._world.pause() self._controller = None return
7,808
Python
34.175676
116
0.616931
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaCabinet/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaCabinet/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaCabinet/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotsKaya/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotsKaya/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .kaya_robot import KayaRobot """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="WheeledRobots", name="KayaRobot", title="KayaRobot", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=KayaRobot(), ) return
2,040
Python
41.520832
135
0.739216
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotsKaya/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotsKaya/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotsKaya/kaya_robot.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController from omni.isaac.wheeled_robots.robots.holonomic_robot_usd_setup import HolonomicRobotUsdSetup import numpy as np class KayaRobot(BaseSample): def __init__(self) -> None: super().__init__() return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() assets_root_path = get_assets_root_path() kaya_asset_path = assets_root_path + "/Isaac/Robots/Kaya/kaya.usd" self._wheeled_robot = world.scene.add( WheeledRobot( prim_path="/World/Kaya", name="my_kaya", wheel_dof_names=["axle_0_joint", "axle_1_joint", "axle_2_joint"], create_robot=True, usd_path=kaya_asset_path, position=np.array([0, 0.0, 0.02]), orientation=np.array([1.0, 0.0, 0.0, 0.0]), ) ) self._save_count = 0 return async def setup_post_load(self): self._world = self.get_world() kaya_setup = HolonomicRobotUsdSetup( robot_prim_path=self._wheeled_robot.prim_path, com_prim_path="/World/Kaya/base_link/control_offset" ) ( wheel_radius, wheel_positions, wheel_orientations, mecanum_angles, wheel_axis, up_axis, ) = kaya_setup.get_holonomic_controller_params() self._holonomic_controller = HolonomicController( name="holonomic_controller", wheel_radius=wheel_radius, wheel_positions=wheel_positions, wheel_orientations=wheel_orientations, mecanum_angles=mecanum_angles, wheel_axis=wheel_axis, up_axis=up_axis, ) print("wheel_radius : ", wheel_radius) print("wheel_positions : ", wheel_positions) print("wheel_orientations : ", wheel_orientations) print("mecanum_angles : ", mecanum_angles) print("wheel_axis : ", wheel_axis) print("up_axis : ", up_axis) self._holonomic_controller.reset() self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) return def send_robot_actions(self, step_size): self._save_count += 1 wheel_action = None if self._save_count >= 0 and self._save_count < 300: wheel_action = self._holonomic_controller.forward(command=[0.5, 0.0, 0.0]) elif self._save_count >= 300 and self._save_count < 600: wheel_action = self._holonomic_controller.forward(command=[-0.5, 0.0, 0.0]) elif self._save_count >= 600 and self._save_count < 900: wheel_action = self._holonomic_controller.forward(command=[0.0, 0.5, 0.0]) elif self._save_count >= 900 and self._save_count < 1200: wheel_action = self._holonomic_controller.forward(command=[0.0, -0.5, 0.0]) elif self._save_count >= 1200 and self._save_count < 1500: wheel_action = self._holonomic_controller.forward(command=[0.0, 0.0, 0.2]) elif self._save_count >= 1500 and self._save_count < 1800: wheel_action = self._holonomic_controller.forward(command=[0.0, 0.0, -0.2]) else: self._save_count = 0 self._wheeled_robot.apply_wheel_actions(wheel_action) return
4,150
Python
37.435185
111
0.62241
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotsKaya/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoDiffROS2/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoDiffROS2/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .limo_diff_drive import LimoDiffDrive """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="WegoRobotics", name="LimoDiffDriveROS2", title="LimoDiffDriveROS2", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=LimoDiffDrive(), ) return
2,068
Python
42.104166
135
0.742263
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoDiffROS2/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoDiffROS2/limo_diff_drive.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from pxr import UsdGeom, Gf, UsdPhysics, Sdf, Gf, Tf, UsdLux from omni.physx.scripts import deformableUtils, physicsUtils import omni.graph.core as og import numpy as np import usdrt.Sdf import omni import carb class LimoDiffDrive(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self.TRACK_PATH = self._server_root + "/Projects/WegoLimo/LimoTrack/LIMO_simulation_table.usd" self.ROBOT_PATH = self._server_root + "/Projects/WegoLimo/Limo/limo_diff_thin.usd" self.LIGHT_PATH = self._server_root + "/Projects/WegoLimo/LimoTrack/Traffic_Light.usdz" self.STOP_PATH = self._server_root + "/Projects/WegoLimo/LimoTrack/Stop_Sign.usdz" self.HYDRANT_PATH = self._server_root + "/Projects/WegoLimo/LimoTrack/Hydrant.usdz" self.PARK_BENCH_PATH = self._server_root + "/Projects/WegoLimo/LimoTrack/Park_Bench.usdz" # omniverse://localhost/Projects/WegoLimo/LimoTrack/Traffic_Light.usdz self._domain_id = 30 self._maxLinearSpeed = 1e6 self._wheelDistance = 0.43 self._wheelRadius = 0.045 self._front_jointNames = ["rear_left_wheel", "rear_right_wheel"] self._rear_jointNames = ["front_left_wheel", "front_right_wheel"] self._contorl_targetPrim = "/World/Limo/base_link" self._odom_targetPrim = "/World/Limo/base_footprint" self._cameraPath = "/World/Limo/depth_link/rgb_camera" return def og_setup(self): try: # OG reference : https://docs.omniverse.nvidia.com/isaacsim/latest/ros2_tutorials/tutorial_ros2_drive_turtlebot.html og.Controller.edit( {"graph_path": "/ROS2DiffDrive", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("subscribeTwist", "omni.isaac.ros2_bridge.ROS2SubscribeTwist"), ("scaleToFromStage", "omni.isaac.core_nodes.OgnIsaacScaleToFromStageUnit"), ("breakLinVel", "omni.graph.nodes.BreakVector3"), ("breakAngVel", "omni.graph.nodes.BreakVector3"), ("diffController", "omni.isaac.wheeled_robots.DifferentialController"), ("artControllerRear", "omni.isaac.core_nodes.IsaacArticulationController"), ("artControllerFront", "omni.isaac.core_nodes.IsaacArticulationController"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", self._domain_id), ("diffController.inputs:maxLinearSpeed", self._maxLinearSpeed), ("diffController.inputs:wheelDistance", self._wheelDistance), ("diffController.inputs:wheelRadius", self._wheelRadius), ("artControllerRear.inputs:jointNames", self._front_jointNames), ("artControllerRear.inputs:targetPrim", [usdrt.Sdf.Path(self._contorl_targetPrim)]), ("artControllerRear.inputs:usePath", False), ("artControllerFront.inputs:jointNames", self._rear_jointNames), ("artControllerFront.inputs:targetPrim", [usdrt.Sdf.Path(self._contorl_targetPrim)]), ("artControllerFront.inputs:usePath", False), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "subscribeTwist.inputs:execIn"), ("onPlaybackTick.outputs:tick", "artControllerRear.inputs:execIn"), ("onPlaybackTick.outputs:tick", "artControllerFront.inputs:execIn"), ("context.outputs:context", "subscribeTwist.inputs:context"), ("subscribeTwist.outputs:execOut", "diffController.inputs:execIn"), ("subscribeTwist.outputs:angularVelocity", "breakAngVel.inputs:tuple"), ("subscribeTwist.outputs:linearVelocity", "scaleToFromStage.inputs:value"), ("scaleToFromStage.outputs:result", "breakLinVel.inputs:tuple"), ("breakAngVel.outputs:z", "diffController.inputs:angularVelocity"), ("breakLinVel.outputs:x", "diffController.inputs:linearVelocity"), ("diffController.outputs:velocityCommand", "artControllerRear.inputs:velocityCommand"), ("diffController.outputs:velocityCommand", "artControllerFront.inputs:velocityCommand"), ], }, ) # OG reference : https://docs.omniverse.nvidia.com/isaacsim/latest/ros2_tutorials/tutorial_ros2_tf.html og.Controller.edit( {"graph_path": "/ROS2Odom", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("computeOdom", "omni.isaac.core_nodes.IsaacComputeOdometry"), ("publishOdom", "omni.isaac.ros2_bridge.ROS2PublishOdometry"), ("publishRawTF", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", self._domain_id), ("computeOdom.inputs:chassisPrim", [usdrt.Sdf.Path(self._odom_targetPrim)]), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "computeOdom.inputs:execIn"), ("onPlaybackTick.outputs:tick", "publishOdom.inputs:execIn"), ("onPlaybackTick.outputs:tick", "publishRawTF.inputs:execIn"), ("readSimTime.outputs:simulationTime", "publishOdom.inputs:timeStamp"), ("readSimTime.outputs:simulationTime", "publishRawTF.inputs:timeStamp"), ("context.outputs:context", "publishOdom.inputs:context"), ("context.outputs:context", "publishRawTF.inputs:context"), ("computeOdom.outputs:angularVelocity", "publishOdom.inputs:angularVelocity"), ("computeOdom.outputs:linearVelocity", "publishOdom.inputs:linearVelocity"), ("computeOdom.outputs:orientation", "publishOdom.inputs:orientation"), ("computeOdom.outputs:position", "publishOdom.inputs:position"), ("computeOdom.outputs:orientation", "publishRawTF.inputs:rotation"), ("computeOdom.outputs:position", "publishRawTF.inputs:translation"), ], }, ) # Right Camera OG og.Controller.edit( {"graph_path": "/ROS2Camera", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("renderer", "omni.isaac.core_nodes.IsaacCreateRenderProduct"), ("RGBPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("DepthPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("CameraInfoPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", self._domain_id), ("renderer.inputs:cameraPrim", [usdrt.Sdf.Path(self._cameraPath)]), ("RGBPublish.inputs:topicName", "/limo/rgb"), ("RGBPublish.inputs:type", "rgb"), ("RGBPublish.inputs:resetSimulationTimeOnStop", True), ("RGBPublish.inputs:frameId", "limo_rgbd_frame"), ("DepthPublish.inputs:topicName", "/limo/depth"), ("DepthPublish.inputs:type", "depth"), ("DepthPublish.inputs:resetSimulationTimeOnStop", True), ("DepthPublish.inputs:frameId", "limo_rgbd_frame"), ("CameraInfoPublish.inputs:topicName", "/limo/camera_info"), ("CameraInfoPublish.inputs:type", "camera_info"), ("CameraInfoPublish.inputs:resetSimulationTimeOnStop", True), ("CameraInfoPublish.inputs:frameId", "limo_rgbd_frame"), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "renderer.inputs:execIn"), ("context.outputs:context", "RGBPublish.inputs:context"), ("context.outputs:context", "DepthPublish.inputs:context"), ("context.outputs:context", "CameraInfoPublish.inputs:context"), ("renderer.outputs:execOut", "RGBPublish.inputs:execIn"), ("renderer.outputs:execOut", "DepthPublish.inputs:execIn"), ("renderer.outputs:execOut", "CameraInfoPublish.inputs:execIn"), ("renderer.outputs:renderProductPath", "RGBPublish.inputs:renderProductPath"), ("renderer.outputs:renderProductPath", "DepthPublish.inputs:renderProductPath"), ("renderer.outputs:renderProductPath", "CameraInfoPublish.inputs:renderProductPath"), ], }, ) except Exception as e: print(e) def add_background(self): add_reference_to_stage(usd_path=self.TRACK_PATH, prim_path="/World/LimoTrack") bg_mesh = UsdGeom.Mesh.Get(omni.usd.get_context().get_stage(), "/World/LimoTrack") physicsUtils.set_or_add_scale_op(bg_mesh, scale=Gf.Vec3f(0.01, 0.01, 0.01)) def add_robot(self): add_reference_to_stage(usd_path=self.ROBOT_PATH, prim_path="/World/Limo") limo_mesh = UsdGeom.Mesh.Get(omni.usd.get_context().get_stage(), "/World/Limo") physicsUtils.set_or_add_translate_op(limo_mesh, translate=Gf.Vec3f(0.0, -0.18, 0.0)) def add_light(self): distantLight1 = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/distantLight1")) distantLight1.CreateIntensityAttr(3000) distantLight1.AddTranslateOp().Set(Gf.Vec3f(0.0, 0.0, 0.0)) def add_objects(self): # Add Traffic Light add_reference_to_stage(usd_path=self.LIGHT_PATH, prim_path="/World/TrafficLight") light_mesh = UsdGeom.Mesh.Get(omni.usd.get_context().get_stage(), "/World/TrafficLight") physicsUtils.set_or_add_translate_op(light_mesh, translate=Gf.Vec3f(0.8, 0.0, 0.0)) physicsUtils.set_or_add_orient_op(light_mesh, orient=Gf.Quatf( # w, x, y, z 0.5, 0.5, -0.5, -0.5 )) physicsUtils.set_or_add_scale_op(light_mesh, scale=Gf.Vec3f(0.001, 0.001, 0.001)) # Add Stop Sign add_reference_to_stage(usd_path=self.STOP_PATH, prim_path="/World/StopSign") stop_mesh = UsdGeom.Mesh.Get(omni.usd.get_context().get_stage(), "/World/StopSign") physicsUtils.set_or_add_translate_op(stop_mesh, translate=Gf.Vec3f(0.8, -0.1, 0.0)) physicsUtils.set_or_add_orient_op(stop_mesh, orient=Gf.Quatf( 0.5, 0.5, -0.5, -0.5 )) physicsUtils.set_or_add_scale_op(stop_mesh, scale=Gf.Vec3f(0.001, 0.001, 0.001)) # Add Hydrant add_reference_to_stage(usd_path=self.HYDRANT_PATH, prim_path="/World/Hydrant") hydrant_mesh = UsdGeom.Mesh.Get(omni.usd.get_context().get_stage(), "/World/Hydrant") physicsUtils.set_or_add_translate_op(hydrant_mesh, translate=Gf.Vec3f(0.8, -0.2, 0.04)) physicsUtils.set_or_add_orient_op(hydrant_mesh, orient=Gf.Quatf( 0.5, 0.5, -0.5, -0.5 )) physicsUtils.set_or_add_scale_op(hydrant_mesh, scale=Gf.Vec3f(0.001, 0.001, 0.001)) # Add Park Bench add_reference_to_stage(usd_path=self.PARK_BENCH_PATH, prim_path="/World/ParkBench") bench_mesh = UsdGeom.Mesh.Get(omni.usd.get_context().get_stage(), "/World/ParkBench") physicsUtils.set_or_add_translate_op(bench_mesh, translate=Gf.Vec3f(0.8, -0.4, 0.0)) physicsUtils.set_or_add_orient_op(bench_mesh, orient=Gf.Quatf( 0.5, 0.5, 0.5, 0.5 )) physicsUtils.set_or_add_scale_op(bench_mesh, scale=Gf.Vec3f(0.001, 0.001, 0.001)) def setup_scene(self): self._world = self.get_world() self._stage = omni.usd.get_context().get_stage() self.add_background() self.add_light() self.add_robot() self.add_objects() self.og_setup() self._save_count = 0 return async def setup_post_load(self): self._world = self.get_world() # self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) return async def setup_pre_reset(self): if self._world.physics_callback_exists("sim_step"): self._world.remove_physics_callback("sim_step") self._world.pause() return async def setup_post_reset(self): await self._world.play_async() self._world.pause() return def world_cleanup(self): self._world.pause() return
14,810
Python
55.315589
128
0.586496
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoDiffROS2/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/LimoDiffROS2/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIcable/cable_demo.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.franka.controllers import PickPlaceController from omni.isaac.examples.base_sample import BaseSample from omni.isaac.franka import Franka from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.prims.geometry_prim import GeometryPrim from omni.isaac.franka import Franka from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.utils.rotations import euler_angles_to_quat from pxr import UsdGeom, Gf, UsdPhysics, Sdf, Gf, Tf, UsdLux from omni.isaac.core import SimulationContext import omni.physx.bindings._physx as physx_bindings from omni.physx.scripts import utils, physicsUtils import omni.physxdemos as demo from pxr import UsdLux, UsdGeom, Sdf, Gf, UsdPhysics, UsdShade, PhysxSchema import numpy as np import carb import omni def createSdfResolution(stage, primPath, kinematic=False): bodyPrim = stage.GetPrimAtPath(primPath) meshCollision = PhysxSchema.PhysxSDFMeshCollisionAPI.Apply(bodyPrim) meshCollision.CreateSdfResolutionAttr().Set(350) def createRigidBody(stage, primPath, kinematic=False): bodyPrim = stage.GetPrimAtPath(primPath) rigid_api = UsdPhysics.RigidBodyAPI.Apply(bodyPrim) rigid_api.CreateRigidBodyEnabledAttr(True) def addObjectsGeom(scene, name, scale, ini_pos, collision=None, mass=None, orientation=None): scene.add(GeometryPrim(prim_path=f"/World/{name}", name=f"{name}_ref_geom", collision=True)) geom = scene.get_object(f"{name}_ref_geom") if orientation is None: # Usually - (x, y, z, w) # But in Isaac Sim - (w, x, y, z) orientation = np.array([1.0, 0.0, 0.0, 0.0]) geom.set_local_scale(scale) geom.set_world_pose(position=ini_pos) geom.set_default_state(position=ini_pos, orientation=orientation) geom.set_collision_enabled(False) if collision is not None: geom.set_collision_enabled(True) geom.set_collision_approximation(collision) if mass is not None: massAPI = UsdPhysics.MassAPI.Apply(geom.prim.GetPrim()) massAPI.CreateMassAttr().Set(mass) return geom class CableDemo(BaseSample): def __init__(self) -> None: super().__init__() # Nucleus Path Configuration carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) # self.USB_MALE_PATH = self._server_root + "/Projects/ETRI/USB_A/USB_A_2_Male_modi1_3.usd" self.USB_MALE_PATH = self._server_root + "/Projects/ETRI/USB_A/USB_A_2_Male_modi1_3_pure.usd" self.USB_FEMALE_PATH = self._server_root + "/Projects/ETRI/USB_A/USB_A_2_Female_modi1_7.usd" # configure ropes: rope_length = 300 num_ropes = 3 self._defaultPrimPath = Sdf.Path("/World") self._linkHalfLength = 3 self._linkRadius = 0.5 * self._linkHalfLength self._ropeLength = rope_length self._numRopes = num_ropes self._ropeSpacing = 15.0 self._ropeColor = demo.get_primary_color() self._coneAngleLimit = 110 self._rope_damping = 10.0 self._rope_stiffness = 1.0 # configure collider capsule: self._capsuleZ = 50.0 self._capsuleHeight = 400.0 self._capsuleRadius = 20.0 self._capsuleRestOffset = -2.0 self._capsuleColor = demo.get_static_color() return def _createCapsule(self, path: Sdf.Path): capsuleGeom = UsdGeom.Capsule.Define(self._stage, path) capsuleGeom.CreateHeightAttr(self._linkHalfLength) capsuleGeom.CreateRadiusAttr(self._linkRadius) capsuleGeom.CreateAxisAttr("X") capsuleGeom.CreateDisplayColorAttr().Set([self._ropeColor]) UsdPhysics.CollisionAPI.Apply(capsuleGeom.GetPrim()) UsdPhysics.RigidBodyAPI.Apply(capsuleGeom.GetPrim()) massAPI = UsdPhysics.MassAPI.Apply(capsuleGeom.GetPrim()) massAPI.CreateDensityAttr().Set(0.00005) physxCollisionAPI = PhysxSchema.PhysxCollisionAPI.Apply(capsuleGeom.GetPrim()) physxCollisionAPI.CreateRestOffsetAttr().Set(0.0) physxCollisionAPI.CreateContactOffsetAttr().Set(self._contactOffset) physicsUtils.add_physics_material_to_prim(self._stage, capsuleGeom.GetPrim(), self._physicsMaterialPath) def _createJoint(self, jointPath): joint = UsdPhysics.Joint.Define(self._stage, jointPath) # locked DOF (lock - low is greater than high) d6Prim = joint.GetPrim() limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "transX") limitAPI.CreateLowAttr(1.0) limitAPI.CreateHighAttr(-1.0) limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "transY") limitAPI.CreateLowAttr(1.0) limitAPI.CreateHighAttr(-1.0) limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "transZ") limitAPI.CreateLowAttr(1.0) limitAPI.CreateHighAttr(-1.0) limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, "rotX") limitAPI.CreateLowAttr(1.0) limitAPI.CreateHighAttr(-1.0) # Moving DOF: dofs = ["rotY", "rotZ"] for d in dofs: limitAPI = UsdPhysics.LimitAPI.Apply(d6Prim, d) limitAPI.CreateLowAttr(-self._coneAngleLimit) limitAPI.CreateHighAttr(self._coneAngleLimit) # joint drives for rope dynamics: driveAPI = UsdPhysics.DriveAPI.Apply(d6Prim, d) driveAPI.CreateTypeAttr("force") driveAPI.CreateDampingAttr(self._rope_damping) driveAPI.CreateStiffnessAttr(self._rope_stiffness) def _createRopes(self): linkLength = 2.0 * self._linkHalfLength - self._linkRadius numLinks = int(self._ropeLength / linkLength) xStart = -numLinks * linkLength * 0.5 yStart = -(self._numRopes // 2) * self._ropeSpacing for ropeInd in range(self._numRopes): scopePath = self._defaultPrimPath.AppendChild(f"Rope{ropeInd}") UsdGeom.Scope.Define(self._stage, scopePath) # capsule instancer instancerPath = scopePath.AppendChild("rigidBodyInstancer") rboInstancer = UsdGeom.PointInstancer.Define(self._stage, instancerPath) capsulePath = instancerPath.AppendChild("capsule") self._createCapsule(capsulePath) meshIndices = [] positions = [] orientations = [] y = yStart + ropeInd * self._ropeSpacing z = self._capsuleZ + self._capsuleRadius + self._linkRadius * 1.4 for linkInd in range(numLinks): meshIndices.append(0) x = xStart + linkInd * linkLength positions.append(Gf.Vec3f(x, y, z)) orientations.append(Gf.Quath(1.0)) meshList = rboInstancer.GetPrototypesRel() # add mesh reference to point instancer meshList.AddTarget(capsulePath) rboInstancer.GetProtoIndicesAttr().Set(meshIndices) rboInstancer.GetPositionsAttr().Set(positions) rboInstancer.GetOrientationsAttr().Set(orientations) # joint instancer jointInstancerPath = scopePath.AppendChild("jointInstancer") jointInstancer = PhysxSchema.PhysxPhysicsJointInstancer.Define(self._stage, jointInstancerPath) jointPath = jointInstancerPath.AppendChild("joint") self._createJoint(jointPath) meshIndices = [] body0s = [] body0indices = [] localPos0 = [] localRot0 = [] body1s = [] body1indices = [] localPos1 = [] localRot1 = [] body0s.append(instancerPath) body1s.append(instancerPath) jointX = self._linkHalfLength - 0.5 * self._linkRadius for linkInd in range(numLinks - 1): meshIndices.append(0) body0indices.append(linkInd) body1indices.append(linkInd + 1) localPos0.append(Gf.Vec3f(jointX, 0, 0)) localPos1.append(Gf.Vec3f(-jointX, 0, 0)) localRot0.append(Gf.Quath(1.0)) localRot1.append(Gf.Quath(1.0)) meshList = jointInstancer.GetPhysicsPrototypesRel() meshList.AddTarget(jointPath) jointInstancer.GetPhysicsProtoIndicesAttr().Set(meshIndices) jointInstancer.GetPhysicsBody0sRel().SetTargets(body0s) jointInstancer.GetPhysicsBody0IndicesAttr().Set(body0indices) jointInstancer.GetPhysicsLocalPos0sAttr().Set(localPos0) jointInstancer.GetPhysicsLocalRot0sAttr().Set(localRot0) jointInstancer.GetPhysicsBody1sRel().SetTargets(body1s) jointInstancer.GetPhysicsBody1IndicesAttr().Set(body1indices) jointInstancer.GetPhysicsLocalPos1sAttr().Set(localPos1) jointInstancer.GetPhysicsLocalRot1sAttr().Set(localRot1) def setup_scene(self): self._world = self.get_world() self._stage = omni.usd.get_context().get_stage() # self._world.scene.add_default_ground_plane() # physics options: self._contactOffset = 2.0 self._physicsMaterialPath = self._defaultPrimPath.AppendChild("PhysicsMaterial") UsdShade.Material.Define(self._stage, self._physicsMaterialPath) material = UsdPhysics.MaterialAPI.Apply(self._stage.GetPrimAtPath(self._physicsMaterialPath)) material.CreateStaticFrictionAttr().Set(0.5) material.CreateDynamicFrictionAttr().Set(0.5) material.CreateRestitutionAttr().Set(0) self._world.scene.add_ground_plane() # self.setup_simulation() self.add_light(self._world.scene.stage) # self._createRopes() # # USB Male # add_reference_to_stage(usd_path=self.USB_MALE_PATH, prim_path=f"/World/usb_male") # createSdfResolution(self._world.scene.stage, "/World/usb_male") # createRigidBody(self._world.scene.stage, "/World/usb_male") # self._usb_male_geom = addObjectsGeom( # self._world.scene, "usb_male", # scale=np.array([0.02, 0.02, 0.02]), # ini_pos=np.array([0.5, 0.2, -0.01]), # # ini_pos=np.array([0.50037, -0.2, 0.06578]), # collision="sdf", # mass=None, # orientation=None # ) self.simulation_context = SimulationContext() return def add_light(self, stage): sphereLight = UsdLux.SphereLight.Define(stage, Sdf.Path("/World/SphereLight")) sphereLight.CreateRadiusAttr(0.2) sphereLight.CreateIntensityAttr(30000) sphereLight.AddTranslateOp().Set(Gf.Vec3f(0.0, 0.0, 2.0)) def setup_simulation(self): self._scene = PhysicsContext() # self._scene.set_solver_type("TGS") self._scene.set_broadphase_type("GPU") self._scene.enable_gpu_dynamics(flag=True) # self._scene.set_friction_offset_threshold(0.01) # self._scene.set_friction_correlation_distance(0.0005) # self._scene.set_gpu_total_aggregate_pairs_capacity(10 * 1024) # self._scene.set_gpu_found_lost_pairs_capacity(10 * 1024) # self._scene.set_gpu_heap_capacity(64 * 1024 * 1024) # self._scene.set_gpu_found_lost_aggregate_pairs_capacity(10 * 1024) # # added because of new errors regarding collisionstacksize # physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(get_prim_at_path("/physicsScene")) # physxSceneAPI.CreateGpuCollisionStackSizeAttr().Set(76000000) # or whatever min is needed async def setup_post_load(self): self._world.add_physics_callback("sim_step", callback_fn=self.physics_step) return def physics_step(self, step_size): return async def setup_pre_reset(self): return async def setup_post_reset(self): await self._world.play_async() return def world_cleanup(self): return
12,777
Python
40.487013
112
0.648666
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIcable/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIcable/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .cable_demo import CableDemo """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ETRIReal", name="CableDemo", title="CableDemo", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=CableDemo(), ) return
2,035
Python
41.416666
135
0.738575
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIcable/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIcable/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178