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/MirobotFollowTarget/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/MirobotFollowTarget/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 .follow_target_example import FollowTargetExample
"""
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="AddingNewManip2",
name="FollowTarget",
title="FollowTarget",
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=FollowTargetExample(),
)
return
| 2,079 |
Python
| 42.333332 | 135 | 0.743627 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotFollowTarget/__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/MirobotFollowTarget/follow_target_example.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, get_url_root
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.manipulators.grippers import ParallelGripper
from omni.isaac.manipulators import SingleManipulator
import omni.isaac.core.tasks as tasks
from typing import Optional
import numpy as np
import carb
from .ik_solver import KinematicsSolver
from .controllers.rmpflow import RMPFlowController
# Inheriting from the base class Follow Target
class FollowTarget(tasks.FollowTarget):
def __init__(
self,
name: str = "mirobot_follow_target",
target_prim_path: Optional[str] = None,
target_name: Optional[str] = None,
target_position: Optional[np.ndarray] = None,
target_orientation: Optional[np.ndarray] = None,
offset: Optional[np.ndarray] = None,
) -> None:
tasks.FollowTarget.__init__(
self,
name=name,
target_prim_path=target_prim_path,
target_name=target_name,
target_position=target_position,
target_orientation=target_orientation,
offset=offset,
)
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._robot_path = self._server_root + "/Projects/RBROS2/mirobot_ros2/mirobot_description/urdf/mirobot_urdf_2/mirobot_urdf_2.usd"
self._joints_default_positions = np.zeros(6)
return
def set_robot(self) -> SingleManipulator:
# add robot to the scene
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/mirobot")
# #define the gripper
# gripper = ParallelGripper(
# #We chose the following values while inspecting the articulation
# end_effector_prim_path="/World/mirobot/onrobot_rg6_base_link",
# joint_prim_names=["finger_joint", "right_outer_knuckle_joint"],
# joint_opened_positions=np.array([0, 0]),
# joint_closed_positions=np.array([0.628, -0.628]),
# action_deltas=np.array([-0.628, 0.628]),
# )
# define the manipulator
manipulator = SingleManipulator(
prim_path="/World/mirobot",
name="mirobot",
end_effector_prim_name="Link6",
gripper=None,
)
manipulator.set_joints_default_state(positions=self._joints_default_positions)
return manipulator
class FollowTargetExample(BaseSample):
def __init__(self) -> None:
super().__init__()
self._articulation_controller = None
# simulation step counter
self._sim_step = 0
return
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
# We add the task to the world here
my_task = FollowTarget(
name="mirobot_follow_target",
target_position=np.array([0.15, 0, 0.15]),
target_orientation=np.array([1, 0, 0, 0]),
)
self._world.add_task(my_task)
return
async def setup_post_load(self):
self._world = self.get_world()
self._task_params = self._world.get_task("mirobot_follow_target").get_params()
self._target_name = self._task_params["target_name"]["value"]
self._my_mirobot = self._world.scene.get_object(self._task_params["robot_name"]["value"])
# IK controller
self._my_controller = KinematicsSolver(self._my_mirobot)
# RMPFlow controller
# self._my_controller = RMPFlowController(name="target_follower_controller", robot_articulation=self._my_mirobot)
self._articulation_controller = self._my_mirobot.get_articulation_controller()
self._world.add_physics_callback("sim_step", callback_fn=self.sim_step_cb)
return
async def setup_post_reset(self):
self._my_controller.reset()
await self._world.play_async()
return
def sim_step_cb(self, step_size):
observations = self._world.get_observations()
pos = observations[self._target_name]["position"]
ori = observations[self._target_name]["orientation"]
# IK controller
actions, succ = self._my_controller.compute_inverse_kinematics(
target_position=pos
)
if succ:
self._articulation_controller.apply_action(actions)
else:
carb.log_warn("IK did not converge to a solution. No action is being taken.")
# # RMPFlow controller
# actions = self._my_controller.forward(
# target_end_effector_position=pos,
# target_end_effector_orientation=ori,
# )
# self._articulation_controller.apply_action(actions)
return
| 5,519 |
Python
| 35.078431 | 137 | 0.644138 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotFollowTarget/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/MirobotFollowTarget/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/MirobotFollowTarget/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/MirobotFollowTarget/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/MirobotFollowTarget/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/MirobotFollowTarget/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/"
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,696 |
Python
| 46.138888 | 127 | 0.68691 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIusbA/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/ETRIusbA/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/ETRIusbA/franka_usb_insertion.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.prims.geometry_prim import GeometryPrim
from omni.isaac.core.utils.prims import get_prim_at_path
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
from omni.physx.scripts import utils
from pxr import PhysxSchema
import numpy as np
import carb
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 FrankaUSBInsert(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"
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)
# 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 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_scene(self):
self._world = self.get_world()
# self._world.scene.add_default_ground_plane()
self._world.scene.add_ground_plane()
self.setup_simulation()
self.add_light(self._world.scene.stage)
# 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
)
# USB FeMale
add_reference_to_stage(usd_path=self.USB_FEMALE_PATH, prim_path=f"/World/usb_female")
self._usb_female_geom = addObjectsGeom(
self._world.scene, "usb_female",
scale=np.array([0.02, 0.02, 0.02]),
ini_pos=np.array([0.5, -0.2, -0.01]),
collision=None,
mass=None,
orientation=None
)
# Add Franka
self._franka = self._world.scene.add(
Franka(
prim_path="/World/franka",
name="franka",
position=np.array([0.0, 0.0, 0.0]),
)
)
self.simulation_context = SimulationContext()
return
async def setup_post_load(self):
self._franka = self._world.scene.get_object("franka")
# Initialize a pick and place controller
self._controller = PickPlaceController(
name="pick_place_controller",
gripper=self._franka.gripper,
robot_articulation=self._franka,
)
# 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)
self._world.add_physics_callback("sim_step", callback_fn=self.physics_step)
# Auto play
# await self._world.play_async()
return
def physics_step(self, step_size):
usb_male_position, _ = self._usb_male_geom.get_world_pose()
usb_female_position, _ = self._usb_female_geom.get_world_pose()
goal_position = usb_female_position + np.array([0.0008, 0.0, 0.06578])
# ini_pos=np.array([0.50037, -0.2, 0.06578]),
current_joint_positions = self._franka.get_joint_positions()
actions = self._controller.forward(
picking_position=usb_male_position,
placing_position=goal_position,
end_effector_orientation=euler_angles_to_quat(
np.array([0, np.pi*3/4, 0])
),
end_effector_offset=np.array([0, 0, 0.035]),
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
async def setup_pre_reset(self):
self._save_count = 0
self._event = 0
return
async def setup_post_reset(self):
await self._world.play_async()
return
def world_cleanup(self):
return
| 7,980 |
Python
| 37.186603 | 101 | 0.650125 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIusbA/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/ETRIusbA/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_usb_insertion import FrankaUSBInsert
"""
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="FrankaUSBInsert",
title="FrankaUSBInsert",
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=FrankaUSBInsert(),
)
return
| 2,069 |
Python
| 42.124999 | 135 | 0.742388 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIusbA/__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/ETRIusbA/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/ETRIusbA/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/ETRIUR102F85/ur10_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.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.prims.geometry_prim import GeometryPrim
from omni.isaac.core.utils.prims import get_prim_at_path
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
from omni.physx.scripts import utils
from pxr import PhysxSchema
import numpy as np
import carb
from omni.isaac.universal_robots import UR10
from omni.isaac.universal_robots.controllers.rmpflow_controller import RMPFlowController
from .custom_ur10 import UR10 as CustomUR10
class UR102F85(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._root_path = get_assets_root_path()
# self.GRIPPER_PATH = self._server_root + "/Projects/ETRI/Gripper/2f85_fixed.usd"
self.GRIPPER_PATH = self._root_path + "/Isaac/Robots/Robotiq/2F-85/2f85_instanceable.usd"
self.UR_PATH = self._server_root + "/Projects/ETRI/Gripper/ur10_2f85_gripper.usd"
self._sim_count = 0
self._gripper_opened = False
return
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
# Add UR10 robot
self._ur10 = self._world.scene.add(
CustomUR10(
prim_path="/World/UR10",
name="UR10",
usd_path=self.UR_PATH,
attach_gripper=True,
# Temp 실제로는 UR_PATH에 이미 그리펴 박혀있음
gripper_usd=self.GRIPPER_PATH
)
)
self.simulation_context = SimulationContext()
return
async def setup_post_load(self):
self._my_ur10 = self._world.scene.get_object("UR10")
self._my_gripper = self._my_ur10.gripper
# RMPFlow controller
self._controller = RMPFlowController(
name="target_follower_controller",
robot_articulation=self._my_ur10
)
self._articulation_controller = self._my_ur10.get_articulation_controller()
self._world.add_physics_callback("sim_step", callback_fn=self.physics_step)
return
def physics_step(self, step_size):
self._sim_count += 1
if self._sim_count < 200:
# RMPFlow controller
actions = self._controller.forward(
target_end_effector_position=np.array([0.4, 0, 0.5]),
# 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([1, 0, 0, 0]),
)
self._articulation_controller.apply_action(actions)
else:
if self._sim_count % 100 == 0:
# Gripper control
if self._gripper_opened:
self._gripper_opened = False
self._my_gripper.close()
else:
self._gripper_opened = True
self._my_gripper.open()
return
async def setup_pre_reset(self):
self._save_count = 0
self._event = 0
return
async def setup_post_reset(self):
await self._world.play_async()
return
def world_cleanup(self):
return
| 4,497 |
Python
| 33.868217 | 101 | 0.637314 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIUR102F85/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/ETRIUR102F85/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 .ur10_basic import UR102F85
"""
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="UR102F85",
title="UR102F85",
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=UR102F85(),
)
return
| 2,031 |
Python
| 41.333332 | 135 | 0.73806 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIUR102F85/__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/ETRIUR102F85/custom_ur10.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 typing import Optional
import carb
import numpy as np
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.robots.robot import Robot
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.manipulators.grippers.surface_gripper import SurfaceGripper
from omni.isaac.manipulators.grippers.parallel_gripper import ParallelGripper
class UR10(Robot):
"""[summary]
Args:
prim_path (str): [description]
name (str, optional): [description]. Defaults to "ur10_robot".
usd_path (Optional[str], optional): [description]. Defaults to None.
position (Optional[np.ndarray], optional): [description]. Defaults to None.
orientation (Optional[np.ndarray], optional): [description]. Defaults to None.
end_effector_prim_name (Optional[str], optional): [description]. Defaults to None.
attach_gripper (bool, optional): [description]. Defaults to False.
gripper_usd (Optional[str], optional): [description]. Defaults to "default".
Raises:
NotImplementedError: [description]
"""
def __init__(
self,
prim_path: str,
name: str = "ur10_robot",
usd_path: Optional[str] = None,
position: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
end_effector_prim_name: Optional[str] = None,
attach_gripper: bool = False,
gripper_usd: Optional[str] = "default",
) -> None:
prim = get_prim_at_path(prim_path)
self._end_effector = None
self._gripper = None
self._end_effector_prim_name = end_effector_prim_name
if not prim.IsValid():
if usd_path:
add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
else:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
return
usd_path = assets_root_path + "/Isaac/Robots/UR10/ur10.usd"
add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
if self._end_effector_prim_name is None:
self._end_effector_prim_path = prim_path + "/ee_link"
else:
self._end_effector_prim_path = prim_path + "/" + end_effector_prim_name
else:
# TODO: change this
if self._end_effector_prim_name is None:
self._end_effector_prim_path = prim_path + "/ee_link"
else:
self._end_effector_prim_path = prim_path + "/" + end_effector_prim_name
super().__init__(
prim_path=prim_path, name=name, position=position, orientation=orientation, articulation_controller=None
)
self._gripper_usd = gripper_usd
if attach_gripper:
if gripper_usd == "default":
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
return
gripper_usd = assets_root_path + "/Isaac/Robots/UR10/Props/short_gripper.usd"
add_reference_to_stage(usd_path=gripper_usd, prim_path=self._end_effector_prim_path)
self._gripper = SurfaceGripper(
end_effector_prim_path=self._end_effector_prim_path, translate=0.1611, direction="x"
)
elif gripper_usd is None:
carb.log_warn("Not adding a gripper usd, the gripper already exists in the ur10 asset")
self._gripper = SurfaceGripper(
end_effector_prim_path=self._end_effector_prim_path, translate=0.1611, direction="x"
)
else:
# add_reference_to_stage(usd_path=gripper_usd, prim_path=self._end_effector_prim_path)
gripper_dof_names = ["left_inner_knuckle_joint", "right_inner_knuckle_joint"]
gripper_open_position = np.array([0.0, 0.0])
gripper_closed_position = np.array([50.0, 50.0])
deltas = np.array([50.0, 50.0])
self._gripper = ParallelGripper(
end_effector_prim_path=self._end_effector_prim_path,
joint_prim_names=gripper_dof_names,
joint_opened_positions=gripper_open_position,
joint_closed_positions=gripper_closed_position,
action_deltas=deltas,
)
self._attach_gripper = attach_gripper
return
@property
def attach_gripper(self) -> bool:
"""[summary]
Returns:
bool: [description]
"""
return self._attach_gripper
@property
def end_effector(self) -> RigidPrim:
"""[summary]
Returns:
RigidPrim: [description]
"""
return self._end_effector
@property
def gripper(self) -> SurfaceGripper:
"""[summary]
Returns:
SurfaceGripper: [description]
"""
return self._gripper
def initialize(self, physics_sim_view=None) -> None:
"""[summary]"""
super().initialize(physics_sim_view)
# if self._attach_gripper:
# self._gripper.initialize(physics_sim_view=physics_sim_view, articulation_num_dofs=self.num_dof)
self._end_effector = RigidPrim(prim_path=self._end_effector_prim_path, name=self.name + "_end_effector")
self.disable_gravity()
self._end_effector.initialize(physics_sim_view)
self._gripper.initialize(
physics_sim_view=physics_sim_view,
articulation_apply_action_func=self.apply_action,
get_joint_positions_func=self.get_joint_positions,
set_joint_positions_func=self.set_joint_positions,
dof_names=self.dof_names,
)
return
def post_reset(self) -> None:
"""[summary]"""
Robot.post_reset(self)
# self._end_effector.post_reset()
self._gripper.post_reset()
return
| 6,705 |
Python
| 40.9125 | 116 | 0.604027 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIUR102F85/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/ETRIUR102F85/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/ETRIFrankaGripper/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/ETRIFrankaGripper/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_gripper import FrankaGripper
"""
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="FrankaGripper",
title="FrankaGripper",
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=FrankaGripper(),
)
return
| 2,055 |
Python
| 41.833332 | 135 | 0.741119 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIFrankaGripper/__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/ETRIFrankaGripper/custom_franka.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 typing import List, Optional
import carb
import numpy as np
from omni.isaac.core.prims.rigid_prim import RigidPrim
from omni.isaac.core.robots.robot import Robot
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, get_stage_units
from omni.isaac.manipulators.grippers.parallel_gripper import ParallelGripper
class Franka(Robot):
"""[summary]
Args:
prim_path (str): [description]
name (str, optional): [description]. Defaults to "franka_robot".
usd_path (Optional[str], optional): [description]. Defaults to None.
position (Optional[np.ndarray], optional): [description]. Defaults to None.
orientation (Optional[np.ndarray], optional): [description]. Defaults to None.
end_effector_prim_name (Optional[str], optional): [description]. Defaults to None.
gripper_dof_names (Optional[List[str]], optional): [description]. Defaults to None.
gripper_open_position (Optional[np.ndarray], optional): [description]. Defaults to None.
gripper_closed_position (Optional[np.ndarray], optional): [description]. Defaults to None.
"""
def __init__(
self,
prim_path: str,
name: str = "franka_robot",
usd_path: Optional[str] = None,
position: Optional[np.ndarray] = None,
orientation: Optional[np.ndarray] = None,
end_effector_prim_name: Optional[str] = None,
gripper_dof_names: Optional[List[str]] = None,
gripper_open_position: Optional[np.ndarray] = None,
gripper_closed_position: Optional[np.ndarray] = None,
deltas: Optional[np.ndarray] = None,
) -> None:
prim = get_prim_at_path(prim_path)
self._end_effector = None
self._gripper = None
self._end_effector_prim_name = end_effector_prim_name
if not prim.IsValid():
if usd_path:
add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
else:
assets_root_path = get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
usd_path = assets_root_path + "/Isaac/Robots/Franka/franka.usd"
add_reference_to_stage(usd_path=usd_path, prim_path=prim_path)
if self._end_effector_prim_name is None:
self._end_effector_prim_path = prim_path + "/panda_leftfinger"
else:
self._end_effector_prim_path = prim_path + "/" + end_effector_prim_name
if gripper_dof_names is None:
gripper_dof_names = ["panda_finger_joint1", "panda_finger_joint2"]
if gripper_open_position is None:
gripper_open_position = np.array([0.05, 0.05]) / get_stage_units()
if gripper_closed_position is None:
gripper_closed_position = np.array([0.0, 0.0])
else:
if self._end_effector_prim_name is None:
self._end_effector_prim_path = prim_path + "/panda_leftfinger"
else:
self._end_effector_prim_path = prim_path + "/" + end_effector_prim_name
if gripper_dof_names is None:
gripper_dof_names = ["panda_finger_joint1", "panda_finger_joint2"]
if gripper_open_position is None:
gripper_open_position = np.array([0.05, 0.05]) / get_stage_units()
if gripper_closed_position is None:
gripper_closed_position = np.array([0.0, 0.0])
super().__init__(
prim_path=prim_path, name=name, position=position, orientation=orientation, articulation_controller=None
)
print(f"self._end_effector_prim_path: {self._end_effector_prim_path}")
if gripper_dof_names is not None:
if deltas is None:
deltas = np.array([0.05, 0.05]) / get_stage_units()
self._gripper = ParallelGripper(
end_effector_prim_path=self._end_effector_prim_path,
joint_prim_names=gripper_dof_names,
joint_opened_positions=gripper_open_position,
joint_closed_positions=gripper_closed_position,
action_deltas=deltas,
)
return
@property
def end_effector(self) -> RigidPrim:
"""[summary]
Returns:
RigidPrim: [description]
"""
return self._end_effector
@property
def gripper(self) -> ParallelGripper:
"""[summary]
Returns:
ParallelGripper: [description]
"""
return self._gripper
def initialize(self, physics_sim_view=None) -> None:
"""[summary]"""
super().initialize(physics_sim_view)
self._end_effector = RigidPrim(prim_path=self._end_effector_prim_path, name=self.name + "_end_effector")
self._end_effector.initialize(physics_sim_view)
self._gripper.initialize(
physics_sim_view=physics_sim_view,
articulation_apply_action_func=self.apply_action,
get_joint_positions_func=self.get_joint_positions,
set_joint_positions_func=self.set_joint_positions,
dof_names=self.dof_names,
)
return
def post_reset(self) -> None:
"""[summary]"""
super().post_reset()
self._gripper.post_reset()
self._articulation_controller.switch_dof_control_mode(
dof_index=self.gripper.joint_dof_indicies[0], mode="position"
)
self._articulation_controller.switch_dof_control_mode(
dof_index=self.gripper.joint_dof_indicies[1], mode="position"
)
return
| 6,227 |
Python
| 42.552447 | 116 | 0.61956 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIFrankaGripper/franka_gripper.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 import SimulationContext
import carb
from .custom_franka import Franka as CustomFranka
class FrankaGripper(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._sim_count = 0
self._gripper_opened = False
return
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
# Add Franka robot
prim_path = "/World/Fancy_Franka"
self._franka = self._world.scene.add(
CustomFranka(
prim_path=prim_path,
name="fancy_franka"
)
)
self.simulation_context = SimulationContext()
return
async def setup_post_load(self):
self._my_franka = self._world.scene.get_object("fancy_franka")
self._my_gripper = self._my_franka.gripper
self._world.add_physics_callback("sim_step", callback_fn=self.physics_step)
return
def physics_step(self, step_size):
self._sim_count += 1
if self._sim_count % 100 == 0:
if self._gripper_opened:
self._gripper_opened = False
self._my_gripper.close()
else:
self._gripper_opened = True
self._my_gripper.open()
self._sim_count = 0
return
async def setup_pre_reset(self):
self._save_count = 0
self._event = 0
return
async def setup_post_reset(self):
await self._world.play_async()
return
def world_cleanup(self):
return
| 2,451 |
Python
| 27.511628 | 101 | 0.628315 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIFrankaGripper/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/ETRIFrankaGripper/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/HelloWorld/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/HelloWorld/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_world import HelloWorld
"""
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="HelloWorld",
title="HelloWorld",
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=HelloWorld(),
)
return
| 2,032 |
Python
| 41.354166 | 135 | 0.738189 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloWorld/__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/HelloWorld/hello_world.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.objects import DynamicCuboid
class HelloWorld(BaseSample):
def __init__(self) -> None:
super().__init__()
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
fancy_cube = world.scene.add(
DynamicCuboid(
prim_path="/World/random_cube", # The prim path of the cube in the USD stage
name="fancy_cube", # The unique name used to retrieve the object from the scene later on
position=np.array([0, 0, 1.0]), # Using the current stage units which is in meters by default.
scale=np.array([0.5015, 0.5015, 0.5015]), # most arguments accept mainly numpy arrays.
color=np.array([0, 0, 1.0]), # RGB channels, going from 0-1
))
return
# Here we assign the class's variables
# this function is called after load button is pressed
# regardless starting from an empty stage or not
# this is called after setup_scene and after
# one physics time step to propagate appropriate
# physics handles which are needed to retrieve
# many physical properties of the different objects
async def setup_post_load(self):
self._world = self.get_world()
self._cube = self._world.scene.get_object("fancy_cube")
self._world.add_physics_callback("sim_step", callback_fn=self.print_cube_info) #callback names have to be unique
return
# here we define the physics callback to be called before each physics step, all physics callbacks must take
# step_size as an argument
def print_cube_info(self, step_size):
position, orientation = self._cube.get_world_pose()
linear_velocity = self._cube.get_linear_velocity()
# will be shown on terminal
print("Cube position is : " + str(position))
print("Cube's orientation is : " + str(orientation))
print("Cube's linear velocity is : " + str(linear_velocity))
# async def setup_pre_reset(self):
# return
# async def setup_post_reset(self):
# return
# def world_cleanup(self):
# return
| 2,802 |
Python
| 40.83582 | 120 | 0.673091 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloWorld/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/HelloWorld/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/HelloWorld/hello_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.utils.types import ArticulationAction
import numpy as np
class HelloWorld(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()
jetbot_asset_path = assets_root_path + "/Isaac/Robots/Jetbot/jetbot.usd"
self._jetbot = world.scene.add(
WheeledRobot(
prim_path="/World/Fancy_Robot",
name="fancy_robot",
wheel_dof_names=["left_wheel_joint", "right_wheel_joint"],
create_robot=True,
usd_path=jetbot_asset_path,
)
)
return
async def setup_post_load(self):
self._world = self.get_world()
self._jetbot = self._world.scene.get_object("fancy_robot")
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._jetbot.apply_wheel_actions(ArticulationAction(joint_positions=None,
joint_efforts=None,
joint_velocities=5 * np.random.rand(2,)))
return
| 1,954 |
Python
| 39.729166 | 101 | 0.634084 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorSpamRandomPose/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/ReplicatorSpamRandomPose/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 SpamRandomPose
"""
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="SpamRandomPose",
title="SpamRandomPose",
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=SpamRandomPose(),
)
return
| 2,063 |
Python
| 41.999999 | 135 | 0.742123 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorSpamRandomPose/__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/ReplicatorSpamRandomPose/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 SpamRandomPose(BaseSample):
def __init__(self) -> None:
super().__init__()
self._isaac_assets_path = get_assets_root_path()
self._nucleus_server_path = "omniverse://localhost/NVIDIA/"
self.SPAM_URL = self._isaac_assets_path + "/Isaac/Props/YCB/Axis_Aligned/010_potted_meat_can.usd"
# 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)
now_str = now.strftime("%Y-%m-%d_%H:%M:%S")
self._out_dir = str(expanduser("~") + "/Documents/spam_data_" + now_str)
self._sim_step = 0
self.spam_can = None
return
def random_props(self):
with self.spam_can:
rep.modify.pose(
position=rep.distribution.uniform((-0.1, -0.1, 0.5), (0.1, 0.1, 0.5)),
rotation=rep.distribution.uniform((-180,-180, -180), (180, 180, 180)),
scale = rep.distribution.uniform((0.8), (1.2)),
)
def random_sphere_lights(self):
with self.rp_light:
rep.modify.pose(
position=rep.distribution.uniform((-0.5, -0.5, 1.0), (0.5, 0.5, 1.0)),
)
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
self.cam = rep.create.camera(position=(0, 0, 2), look_at=(0, 0, 0))
self.rp = rep.create.render_product(self.cam, resolution=(1024, 1024))
rep.randomizer.register(self.random_props)
rep.randomizer.register(self.random_sphere_lights)
self.spam_can = rep.create.from_usd(self.SPAM_URL)
with self.spam_can:
rep.modify.semantics([('class', "spam_can")])
rep.modify.pose(
position=rep.distribution.uniform((-0.1, -0.1, 0.5), (0.1, 0.1, 0.5)),
rotation=rep.distribution.uniform((-180,-180, -180), (180, 180, 180)),
scale = rep.distribution.uniform((0.8), (1.2)),
)
self.rp_light = rep.create.light(
light_type="sphere",
temperature=3000,
intensity=5000.0,
position=(0.0, 0.0, 1.0),
scale=0.5,
count=1
)
return
async def setup_post_load(self):
with rep.trigger.on_frame(num_frames=20):
rep.modify.timeline(5, "frame")
rep.randomizer.random_props()
rep.randomizer.random_sphere_lights()
# 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,
# distance_to_camera=True
)
# Attach render product to writer
self._writer.attach([self.rp])
return
| 4,008 |
Python
| 35.117117 | 105 | 0.609531 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorSpamRandomPose/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/ReplicatorSpamRandomPose/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/ManipPickandPlace/ik_solver.py
|
from omni.isaac.motion_generation import ArticulationKinematicsSolver, LulaKinematicsSolver
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.articulations import Articulation
from typing import Optional
import carb
class KinematicsSolver(ArticulationKinematicsSolver):
def __init__(self, robot_articulation: Articulation, end_effector_frame_name: Optional[str] = None) -> None:
#TODO: change the config path
# desktop
# my_path = "/home/kimsooyoung/Documents/IsaacSim/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/"
# self._urdf_path = "/home/kimsooyoung/Downloads/USD/cobotta_pro_900/"
# lactop
self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/"
self._urdf_path = "/home/kimsooyoung/Downloads/Source/cobotta_pro_900/"
self._kinematics = LulaKinematicsSolver(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
urdf_path=self._urdf_path+"cobotta_pro_900.urdf"
)
if end_effector_frame_name is None:
end_effector_frame_name = "onrobot_rg6_base_link"
ArticulationKinematicsSolver.__init__(self, robot_articulation, self._kinematics, end_effector_frame_name)
return
| 1,388 |
Python
| 45.299998 | 125 | 0.698127 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipPickandPlace/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/ManipPickandPlace/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 .pick_place_example import PickandPlaceExample
"""
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="AddingNewManip",
name="PickandPlace",
title="PickandPlace",
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=PickandPlaceExample(),
)
return
| 2,075 |
Python
| 42.249999 | 135 | 0.743133 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipPickandPlace/__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/ManipPickandPlace/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/ManipPickandPlace/pick_place_example.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, get_url_root
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.manipulators.grippers import ParallelGripper
from omni.isaac.manipulators import SingleManipulator
import omni.isaac.core.tasks as tasks
from typing import Optional
import numpy as np
import carb
from .ik_solver import KinematicsSolver
from .controllers.rmpflow import RMPFlowController
from .controllers.pick_place import PickPlaceController
# Inheriting from the base class PickPlace
class PickPlace(tasks.PickPlace):
def __init__(
self,
name: str = "denso_pick_place",
cube_initial_position: Optional[np.ndarray] = None,
cube_initial_orientation: Optional[np.ndarray] = None,
target_position: Optional[np.ndarray] = None,
offset: Optional[np.ndarray] = None,
) -> None:
tasks.PickPlace.__init__(
self,
name=name,
cube_initial_position=cube_initial_position,
cube_initial_orientation=cube_initial_orientation,
target_position=target_position,
cube_size=np.array([0.0515, 0.0515, 0.0515]),
offset=offset,
)
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._robot_path = self._server_root + "/Projects/RBROS2/cobotta_pro_900/cobotta_pro_900/cobotta_pro_900.usd"
return
def set_robot(self) -> SingleManipulator:
#TODO: change the asset path here
# laptop
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/cobotta")
gripper = ParallelGripper(
end_effector_prim_path="/World/cobotta/onrobot_rg6_base_link",
joint_prim_names=["finger_joint", "right_outer_knuckle_joint"],
joint_opened_positions=np.array([0, 0]),
joint_closed_positions=np.array([0.628, -0.628]),
action_deltas=np.array([-0.2, 0.2])
)
manipulator = SingleManipulator(
prim_path="/World/cobotta",
name="cobotta_robot",
end_effector_prim_name="onrobot_rg6_base_link",
gripper=gripper
)
joints_default_positions = np.zeros(12)
joints_default_positions[7] = 0.628
joints_default_positions[8] = 0.628
manipulator.set_joints_default_state(positions=joints_default_positions)
return manipulator
class PickandPlaceExample(BaseSample):
def __init__(self) -> None:
super().__init__()
self._articulation_controller = None
# simulation step counter
self._sim_step = 0
self._target_position = np.array([-0.3, 0.6, 0])
self._target_position[2] = 0.0515 / 2.0
return
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
# We add the task to the world here
my_task = PickPlace(
name="denso_pick_place",
target_position=self._target_position
)
self._world.add_task(my_task)
return
async def setup_post_load(self):
self._world = self.get_world()
self._my_denso = self._world.scene.get_object("cobotta_robot")
self._my_controller = PickPlaceController(
name="controller",
robot_articulation=self._my_denso,
gripper=self._my_denso.gripper
)
self._task_params = self._world.get_task("denso_pick_place").get_params()
self._articulation_controller = self._my_denso.get_articulation_controller()
self._world.add_physics_callback("sim_step", callback_fn=self.sim_step_cb)
return
async def setup_post_reset(self):
self._my_controller.reset()
await self._world.play_async()
return
def sim_step_cb(self, step_size):
observations = self._world.get_observations()
actions = self._my_controller.forward(
picking_position=observations[self._task_params["cube_name"]["value"]]["position"],
placing_position=observations[self._task_params["cube_name"]["value"]]["target_position"],
current_joint_positions=observations[self._task_params["robot_name"]["value"]]["joint_positions"],
# This offset needs tuning as well
end_effector_offset=np.array([0, 0, 0.25]),
)
if self._my_controller.is_done():
print("done picking and placing")
self._articulation_controller.apply_action(actions)
return
| 5,318 |
Python
| 35.431507 | 117 | 0.646108 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipPickandPlace/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/ManipPickandPlace/rmpflow/robot_descriptor.yaml
|
api_version: 1.0
cspace:
- joint_1
- joint_2
- joint_3
- joint_4
- joint_5
- joint_6
root_link: world
default_q: [
0.00, 0.00, 0.00, 0.00, 0.00, 0.00
]
cspace_to_urdf_rules: []
composite_task_spaces: []
| 230 |
YAML
| 15.499999 | 38 | 0.56087 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipPickandPlace/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/ManipPickandPlace/tasks/pick_place.py
|
from omni.isaac.manipulators import SingleManipulator
from omni.isaac.manipulators.grippers import ParallelGripper
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
import omni.isaac.core.tasks as tasks
from typing import Optional
import numpy as np
import carb
class PickPlace(tasks.PickPlace):
def __init__(
self,
name: str = "denso_pick_place",
cube_initial_position: Optional[np.ndarray] = None,
cube_initial_orientation: Optional[np.ndarray] = None,
target_position: Optional[np.ndarray] = None,
offset: Optional[np.ndarray] = None,
) -> None:
tasks.PickPlace.__init__(
self,
name=name,
cube_initial_position=cube_initial_position,
cube_initial_orientation=cube_initial_orientation,
target_position=target_position,
cube_size=np.array([0.0515, 0.0515, 0.0515]),
offset=offset,
)
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._robot_path = self._server_root + "/Projects/RBROS2/cobotta_pro_900/cobotta_pro_900/cobotta_pro_900.usd"
return
def set_robot(self) -> SingleManipulator:
#TODO: change the asset path here
# laptop
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/cobotta")
gripper = ParallelGripper(
end_effector_prim_path="/World/cobotta/onrobot_rg6_base_link",
joint_prim_names=["finger_joint", "right_outer_knuckle_joint"],
joint_opened_positions=np.array([0, 0]),
joint_closed_positions=np.array([0.628, -0.628]),
action_deltas=np.array([-0.2, 0.2])
)
manipulator = SingleManipulator(
prim_path="/World/cobotta",
name="cobotta_robot",
end_effector_prim_name="onrobot_rg6_base_link",
gripper=gripper
)
joints_default_positions = np.zeros(12)
joints_default_positions[7] = 0.628
joints_default_positions[8] = 0.628
manipulator.set_joints_default_state(positions=joints_default_positions)
return manipulator
| 2,427 |
Python
| 36.937499 | 117 | 0.639061 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipPickandPlace/controllers/pick_place.py
|
import omni.isaac.manipulators.controllers as manipulators_controllers
from omni.isaac.manipulators.grippers import ParallelGripper
from .rmpflow import RMPFlowController
from omni.isaac.core.articulations import Articulation
class PickPlaceController(manipulators_controllers.PickPlaceController):
def __init__(
self,
name: str,
gripper: ParallelGripper,
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,
#This value can be changed
# start_picking_height=0.6
)
return
| 1,184 |
Python
| 38.499999 | 118 | 0.640203 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipPickandPlace/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/ManipFollowTarget/"
self._urdf_path = "/home/kimsooyoung/Downloads/Source/cobotta_pro_900/"
self.rmpflow = mg.lula.motion_policies.RmpFlow(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
rmpflow_config_path=self._desc_path+"rmpflow/denso_rmpflow_common.yaml",
urdf_path=self._urdf_path+"cobotta_pro_900.urdf",
end_effector_frame_name="onrobot_rg6_base_link",
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,686 |
Python
| 45.86111 | 125 | 0.68446 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummitO3WheelROS2/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/WheeledRobotSummitO3WheelROS2/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 .robotnik_summit import RobotnikSummit
"""
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="RobotnikSummitO3Wheel_ROS2",
title="RobotnikSummitO3Wheel_ROS2",
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=RobotnikSummit(),
)
return
| 2,089 |
Python
| 42.541666 | 135 | 0.744375 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummitO3WheelROS2/__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/WheeledRobotSummitO3WheelROS2/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/WheeledRobotSummitO3WheelROS2/robotnik_summit.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.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.types import ArticulationAction
from omni.isaac.core.utils.stage import add_reference_to_stage
from omni.isaac.core.physics_context.physics_context import PhysicsContext
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
from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController
import omni.graph.core as og
import numpy as np
import usdrt.Sdf
import carb
import omni
class RobotnikSummit(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)
# wheel models referenced from : https://git.openlogisticsfoundation.org/silicon-economy/simulation-model/o3dynsimmodel
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/Collected_summit_xl_omni_four/summit_xl_omni_four.usd"
self._wheel_radius = np.array([ 0.127, 0.127, 0.127, 0.127 ])
self._wheel_positions = np.array([
[0.229, 0.235, 0.11],
[0.229, -0.235, 0.11],
[-0.229, 0.235, 0.11],
[-0.229, -0.235, 0.11],
])
self._wheel_orientations = np.array([
[0.7071068, 0, 0, 0.7071068],
[0.7071068, 0, 0, -0.7071068],
[0.7071068, 0, 0, 0.7071068],
[0.7071068, 0, 0, -0.7071068],
])
self._mecanum_angles = np.array([
-135.0,
-45.0,
-45.0,
-135.0,
])
self._wheel_axis = np.array([1, 0, 0])
self._up_axis = np.array([0, 0, 1])
self._targetPrim = "/World/Summit/summit_xl_base_link"
self._domain_id = 30
return
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 og_setup(self):
try:
og.Controller.edit(
{"graph_path": "/ROS2HolonomicTwist", "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"),
("breakAngVel", "omni.graph.nodes.BreakVector3"),
("breakLinVel", "omni.graph.nodes.BreakVector3"),
("angvelGain", "omni.graph.nodes.ConstantDouble"),
("angvelMult", "omni.graph.nodes.Multiply"),
("linXGain", "omni.graph.nodes.ConstantDouble"),
("linXMult", "omni.graph.nodes.Multiply"),
("linYGain", "omni.graph.nodes.ConstantDouble"),
("linYMult", "omni.graph.nodes.Multiply"),
("velVec3", "omni.graph.nodes.MakeVector3"),
("mecanumAng", "omni.graph.nodes.ConstructArray"),
("holonomicCtrl", "omni.isaac.wheeled_robots.HolonomicController"),
("upAxis", "omni.graph.nodes.ConstantDouble3"),
("wheelAxis", "omni.graph.nodes.ConstantDouble3"),
("wheelOrientation", "omni.graph.nodes.ConstructArray"),
("wheelPosition", "omni.graph.nodes.ConstructArray"),
("wheelRadius", "omni.graph.nodes.ConstructArray"),
("jointNames", "omni.graph.nodes.ConstructArray"),
("articulation", "omni.isaac.core_nodes.IsaacArticulationController"),
],
og.Controller.Keys.SET_VALUES: [
("context.inputs:domain_id", self._domain_id),
("subscribeTwist.inputs:topicName", "cmd_vel"),
("angvelGain.inputs:value", -0.514),
("linXGain.inputs:value", 2.325),
("linYGain.inputs:value", 3.0),
("mecanumAng.inputs:arraySize", 4),
("mecanumAng.inputs:arrayType", "double[]"),
("mecanumAng.inputs:input0", self._mecanum_angles[0]),
("mecanumAng.inputs:input1", self._mecanum_angles[1]),
("mecanumAng.inputs:input2", self._mecanum_angles[2]),
("mecanumAng.inputs:input3", self._mecanum_angles[3]),
("holonomicCtrl.inputs:angularGain", 1.0),
("holonomicCtrl.inputs:linearGain", 1.0),
("holonomicCtrl.inputs:maxWheelSpeed", 1200.0),
("upAxis.inputs:value", self._up_axis),
("wheelAxis.inputs:value", self._wheel_axis),
("wheelOrientation.inputs:arraySize", 4),
("wheelOrientation.inputs:arrayType", "double[4][]"),
("wheelOrientation.inputs:input0", self._wheel_orientations[0]),
("wheelOrientation.inputs:input1", self._wheel_orientations[1]),
("wheelOrientation.inputs:input2", self._wheel_orientations[2]),
("wheelOrientation.inputs:input3", self._wheel_orientations[3]),
("wheelPosition.inputs:arraySize", 4),
("wheelPosition.inputs:arrayType", "double[3][]"),
("wheelPosition.inputs:input0", self._wheel_positions[0]),
("wheelPosition.inputs:input1", self._wheel_positions[1]),
("wheelPosition.inputs:input2", self._wheel_positions[2]),
("wheelPosition.inputs:input3", self._wheel_positions[3]),
("wheelRadius.inputs:arraySize", 4),
("wheelRadius.inputs:arrayType", "double[]"),
("wheelRadius.inputs:input0", self._wheel_radius[0]),
("wheelRadius.inputs:input1", self._wheel_radius[1]),
("wheelRadius.inputs:input2", self._wheel_radius[2]),
("wheelRadius.inputs:input3", self._wheel_radius[3]),
("jointNames.inputs:arraySize", 4),
("jointNames.inputs:arrayType", "token[]"),
("jointNames.inputs:input0", "fl_joint"),
("jointNames.inputs:input1", "fr_joint"),
("jointNames.inputs:input2", "rl_joint"),
("jointNames.inputs:input3", "rr_joint"),
("articulation.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]),
("articulation.inputs:robotPath", self._targetPrim),
("articulation.inputs:usePath", False),
],
og.Controller.Keys.CREATE_ATTRIBUTES: [
("mecanumAng.inputs:input1", "double"),
("mecanumAng.inputs:input2", "double"),
("mecanumAng.inputs:input3", "double"),
("wheelOrientation.inputs:input1", "double[4]"),
("wheelOrientation.inputs:input2", "double[4]"),
("wheelOrientation.inputs:input3", "double[4]"),
("wheelPosition.inputs:input1", "double[3]"),
("wheelPosition.inputs:input2", "double[3]"),
("wheelPosition.inputs:input3", "double[3]"),
("wheelRadius.inputs:input1", "double"),
("wheelRadius.inputs:input2", "double"),
("wheelRadius.inputs:input3", "double"),
("jointNames.inputs:input1", "token"),
("jointNames.inputs:input2", "token"),
("jointNames.inputs:input3", "token"),
],
og.Controller.Keys.CONNECT: [
("onPlaybackTick.outputs:tick", "subscribeTwist.inputs:execIn"),
("context.outputs:context", "subscribeTwist.inputs:context"),
("subscribeTwist.outputs:angularVelocity", "breakAngVel.inputs:tuple"),
("subscribeTwist.outputs:linearVelocity", "scaleToFromStage.inputs:value"),
("scaleToFromStage.outputs:result", "breakLinVel.inputs:tuple"),
("breakAngVel.outputs:z", "angvelMult.inputs:a"),
("angvelGain.inputs:value", "angvelMult.inputs:b"),
("breakLinVel.outputs:x", "linXMult.inputs:a"),
("linXGain.inputs:value", "linXMult.inputs:b"),
("breakLinVel.outputs:y", "linYMult.inputs:a"),
("linYGain.inputs:value", "linYMult.inputs:b"),
("angvelMult.outputs:product", "velVec3.inputs:z"),
("linXMult.outputs:product", "velVec3.inputs:x"),
("linYMult.outputs:product", "velVec3.inputs:y"),
("onPlaybackTick.outputs:tick", "holonomicCtrl.inputs:execIn"),
("velVec3.outputs:tuple", "holonomicCtrl.inputs:velocityCommands"),
("mecanumAng.outputs:array", "holonomicCtrl.inputs:mecanumAngles"),
("onPlaybackTick.outputs:tick", "holonomicCtrl.inputs:execIn"),
("upAxis.inputs:value", "holonomicCtrl.inputs:upAxis"),
("wheelAxis.inputs:value", "holonomicCtrl.inputs:wheelAxis"),
("wheelOrientation.outputs:array", "holonomicCtrl.inputs:wheelOrientations"),
("wheelPosition.outputs:array", "holonomicCtrl.inputs:wheelPositions"),
("wheelRadius.outputs:array", "holonomicCtrl.inputs:wheelRadius"),
("onPlaybackTick.outputs:tick", "articulation.inputs:execIn"),
("holonomicCtrl.outputs:jointVelocityCommand", "articulation.inputs:velocityCommand"),
("jointNames.outputs:array", "articulation.inputs:jointNames"),
],
},
)
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"),
],
},
)
except Exception as e:
print(e)
def setup_scene(self):
world = self.get_world()
self._stage = omni.usd.get_context().get_stage()
self.add_background()
# world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Summit")
self._wheeled_robot = WheeledRobot(
prim_path=self._targetPrim,
name="my_summit",
wheel_dof_names=[
"fl_joint",
"fr_joint",
"rl_joint",
"rr_joint",
],
create_robot=True,
usd_path=self._robot_path,
position=np.array([0, 0.0, 0.02]),
orientation=np.array([1.0, 0.0, 0.0, 0.0]),
)
self._save_count = 0
self._scene = PhysicsContext()
self._scene.set_physics_dt(1 / 30.0)
self.og_setup()
return
async def setup_post_load(self):
self._world = self.get_world()
self._wheeled_robot.initialize()
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
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):
self._summit_controller.reset()
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return
| 15,753 |
Python
| 49.49359 | 132 | 0.538437 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummitO3WheelROS2/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/ReplicatorFactoryDemoROS2/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_ros_camera(self, scene):
add_reference_to_stage(usd_path=self._gemini_usd_path, prim_path=f"/World/Orbbec_Gemini2")
self._cam_ref_geom = addObjectsGeom(
scene, "Orbbec_Gemini2", np.array([1.0, 1.0, 1.0]),
self._gemini_position, 0.0, self._gemini_rotation
)
ldm_light = self._stage.GetPrimAtPath("/World/Orbbec_Gemini2/Orbbec_Gemini2/camera_ldm/camera_ldm/RectLight")
ldm_light_intensity = ldm_light.GetAttribute("intensity")
ldm_light_intensity.Set(0)
def og_setup(self):
camprim1 = "/World/Orbbec_Gemini2/Orbbec_Gemini2/camera_ir_left/camera_left/Stream_depth"
camprim2 = "/World/Orbbec_Gemini2/Orbbec_Gemini2/camera_rgb/camera_rgb/Stream_rgb"
try:
og.Controller.edit(
{"graph_path": "/GeminiROS2OG", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("RenderProduct1", "omni.isaac.core_nodes.IsaacCreateRenderProduct"),
("RenderProduct2", "omni.isaac.core_nodes.IsaacCreateRenderProduct"),
("RGBPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
("CameraInfoPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
],
og.Controller.Keys.SET_VALUES: [
("RenderProduct1.inputs:cameraPrim", camprim1),
("RenderProduct2.inputs:cameraPrim", camprim2),
("RGBPublish.inputs:topicName", "rgb"),
("RGBPublish.inputs:type", "rgb"),
("RGBPublish.inputs:resetSimulationTimeOnStop", True),
("CameraInfoPublish.inputs:topicName", "depth_camera_info"),
("CameraInfoPublish.inputs:type", "camera_info"),
("CameraInfoPublish.inputs:resetSimulationTimeOnStop", True),
],
og.Controller.Keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "RenderProduct1.inputs:execIn"),
("OnPlaybackTick.outputs:tick", "RenderProduct2.inputs:execIn"),
("RenderProduct1.outputs:execOut", "CameraInfoPublish.inputs:execIn"),
("RenderProduct2.outputs:execOut", "RGBPublish.inputs:execIn"),
("RenderProduct1.outputs:renderProductPath", "CameraInfoPublish.inputs:renderProductPath"),
("RenderProduct2.outputs:renderProductPath", "RGBPublish.inputs:renderProductPath"),
],
},
)
except Exception as e:
print(e)
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)
# Uncomment belows if you wanna activate ROS 2 topic publishing
# self.add_ros_camera(self._world.scene)
# self.og_setup()
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]
# TEST
# target_width, target_height = 1280, 720
# image_bgr = cv2.resize(cur_img, (target_width, target_height))
# image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
# cv2.imwrite("/home/kimsooyoung/Documents/test_img.png", image_rgb)
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
| 10,350 |
Python
| 41.772727 | 141 | 0.603671 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemoROS2/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/ReplicatorFactoryDemoROS2/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="ReplicatorFactoryDemoROS2",
title="ReplicatorFactoryDemoROS2",
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,084 |
Python
| 42.437499 | 135 | 0.744722 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorFactoryDemoROS2/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/ReplicatorFactoryDemoROS2/__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/ReplicatorFactoryDemoROS2/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/ReplicatorFactoryDemoROS2/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/ReplicatorFactoryDemoROS2/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/WheeledRobotLimoDiffROS2/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/WheeledRobotLimoDiffROS2/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="WheeledRobots",
name="LimoDiffDrive_ROS2",
title="LimoDiffDrive_ROS2",
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,071 |
Python
| 42.166666 | 135 | 0.741671 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoDiffROS2/__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/WheeledRobotLimoDiffROS2/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.physics_context.physics_context import PhysicsContext
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
import omni.graph.core as og
import numpy as np
import usdrt.Sdf
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._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_base.usd"
self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_diff_thin.usd"
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"
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"),
],
},
)
except Exception as e:
print(e)
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Limo")
self._save_count = 0
self.og_setup()
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
def send_robot_actions(self, step_size):
self._save_count += 1
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):
self._summit_controller.reset()
await self._world.play_async()
self._world.pause()
return
def world_cleanup(self):
self._world.pause()
return
| 8,504 |
Python
| 52.15625 | 128 | 0.589135 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoDiffROS2/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/WheeledRobotLimoDiffROS2/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/SurfaceGripper/__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 .surface_gripper import *
| 463 |
Python
| 41.181814 | 76 | 0.807775 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SurfaceGripper/surface_gripper.py
|
# Copyright (c) 2018-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 weakref
import numpy as np
import omni
import omni.ext
import omni.kit.commands
import omni.kit.usd
import omni.physx as _physx
import omni.ui as ui
from omni.isaac.core.utils.viewports import set_camera_view
from omni.isaac.dynamic_control import _dynamic_control as dc
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.surface_gripper._surface_gripper import Surface_Gripper, Surface_Gripper_Properties
from omni.isaac.ui.menu import make_menu_item_description
from omni.isaac.ui.ui_utils import (
add_separator,
btn_builder,
combo_floatfield_slider_builder,
get_style,
setup_ui_headers,
state_btn_builder,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from pxr import Gf, Sdf, UsdGeom, UsdLux, UsdPhysics
import omni.isaac.core.utils.stage as stage_utils
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 omni.physx.scripts import deformableUtils, physicsUtils
import carb
EXTENSION_NAME = "SurfaceGripper"
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
"""Initialize extension and UI elements"""
self._ext_id = ext_id
# Loads interfaces
self._timeline = omni.timeline.get_timeline_interface()
self._dc = dc.acquire_dynamic_control_interface()
self._usd_context = omni.usd.get_context()
self._window = None
self._models = {}
# Creates UI window with default size of 600x300
# self._window = omni.ui.Window(
# title=EXTENSION_NAME, width=300, height=200, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
# )
menu_items = [
make_menu_item_description(ext_id, EXTENSION_NAME, lambda a=weakref.proxy(self): a._menu_callback())
]
self._menu_items = [MenuItemDescription(name="RoadBalanceEdu", sub_menu=menu_items)]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
self.surface_gripper = None
self.cone = None
self.box = None
self._stage_id = -1
def _build_ui(self):
if not self._window:
self._window = ui.Window(
title=EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.set_visibility_changed_fn(self._on_window)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Surface Gripper Example"
doc_link = "https://docs.omniverse.nvidia.com/isaacsim/latest/features/robots_simulation/ext_omni_isaac_surface_gripper.html"
overview = "This Example shows how to simulate a suction-cup gripper in Isaac Sim. "
overview += "It simulates suction by creating a Joint between two bodies when the parent and child bodies are close at the gripper's point of contact."
overview += "\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
args = {
"label": "Load Scene",
"type": "button",
"text": "Load",
"tooltip": "Load a gripper into the Scene",
"on_clicked_fn": self._on_create_scenario_button_clicked,
}
self._models["create_button"] = btn_builder(**args)
args = {
"label": "Gripper State",
"type": "button",
"a_text": "Close",
"b_text": "Open",
"tooltip": "Open and Close the Gripper",
"on_clicked_fn": self._on_toggle_gripper_button_clicked,
}
self._models["toggle_button"] = state_btn_builder(**args)
add_separator()
args = {
"label": "Gripper Force (UP)",
"default_val": 0,
"min": 0,
"max": 1.0e2,
"step": 1,
"tooltip": ["Force in ()", "Force in ()"],
}
self._models["force_slider"], slider = combo_floatfield_slider_builder(**args)
args = {
"label": "Set Force",
"type": "button",
"text": "APPLY",
"tooltip": "Apply the Gripper Force to the Z-Axis of the Cone",
"on_clicked_fn": self._on_force_button_clicked,
}
self._models["force_button"] = btn_builder(**args)
args = {
"label": "Gripper Speed (UP)",
"default_val": 0,
"min": 0,
"max": 5.0e1,
"step": 1,
"tooltip": ["Speed in ()", "Speed in ()"],
}
add_separator()
self._models["speed_slider"], slider = combo_floatfield_slider_builder(**args)
args = {
"label": "Set Speed",
"type": "button",
"text": "APPLY",
"tooltip": "Apply Cone Velocity in the Z-Axis",
"on_clicked_fn": self._on_speed_button_clicked,
}
self._models["speed_button"] = btn_builder(**args)
ui.Spacer()
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._physx_subs = None
self._window = None
def _on_window(self, status):
if status:
self._usd_context = omni.usd.get_context()
if self._usd_context is not None:
self._stage_event_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update_ui)
)
else:
self._stage_event_sub = None
self._physx_subs = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_update_ui(self, widget):
self._models["create_button"].enabled = self._timeline.is_playing()
self._models["toggle_button"].enabled = self._timeline.is_playing()
self._models["force_button"].enabled = self._timeline.is_playing()
self._models["speed_button"].enabled = self._timeline.is_playing()
# If the scene has been reloaded, reset UI to create Scenario
if self._usd_context.get_stage_id() != self._stage_id:
self._models["create_button"].enabled = True
# self._models["create_button"].text = "Create Scenario"
self._models["create_button"].set_tooltip("Creates a new scenario with the cone on top of the Cube")
self._models["create_button"].set_clicked_fn(self._on_create_scenario_button_clicked)
self.cone = None
self.box = None
self._stage_id = -1
def _toggle_gripper_button_ui(self):
# Checks if the surface gripper has been created
if self.surface_gripper is not None:
if self.surface_gripper.is_closed():
self._models["toggle_button"].text = "OPEN"
else:
self._models["toggle_button"].text = "CLOSE"
pass
def _on_simulation_step(self, step):
# Checks if the simulation is playing, and if the stage has been loaded
if self._timeline.is_playing() and self._stage_id != -1:
# Check if the handles for cone and box have been loaded
if self.cone is None:
# self.cone = self._dc.get_rigid_body("/GripperCone")
self.cone = self._dc.get_rigid_body("/mirobot_ee/Link6")
self.box = self._dc.get_rigid_body("/Box")
# If the surface Gripper has been created, update wheter it has been broken or not
if self.surface_gripper is not None:
self.surface_gripper.update()
# if self.surface_gripper.is_closed():
# self.coneGeom.GetDisplayColorAttr().Set([self.color_closed])
# else:
# self.coneGeom.GetDisplayColorAttr().Set([self.color_open])
self._toggle_gripper_button_ui()
def _on_reset_scenario_button_clicked(self):
if self._timeline.is_playing() and self._stage_id != -1:
if self.surface_gripper is not None:
self.surface_gripper.open()
self._dc.set_rigid_body_linear_velocity(self.cone, [0, 0, 0])
self._dc.set_rigid_body_linear_velocity(self.box, [0, 0, 0])
self._dc.set_rigid_body_angular_velocity(self.cone, [0, 0, 0])
self._dc.set_rigid_body_angular_velocity(self.box, [0, 0, 0])
self._dc.set_rigid_body_pose(self.cone, self.gripper_start_pose)
self._dc.set_rigid_body_pose(self.box, self.box_start_pose)
async def _create_scenario(self, task):
done, pending = await asyncio.wait({task})
if task in done:
# Repurpose button to reset Scene
# self._models["create_button"].text = "Reset Scene"
self._models["create_button"].set_tooltip("Resets scenario with the cone on top of the Cube")
# Get Handle for stage and stage ID to check if stage was reloaded
self._stage = self._usd_context.get_stage()
self._stage_id = self._usd_context.get_stage_id()
self._timeline.stop()
self._models["create_button"].set_clicked_fn(self._on_reset_scenario_button_clicked)
# Adds a light to the scene
distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
distantLight.AddOrientOp().Set(Gf.Quatf(-0.3748, -0.42060, -0.0716, 0.823))
# Set up stage with Z up, treat units as cm, set up gravity and ground plane
UsdGeom.SetStageUpAxis(self._stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(self._stage, 1.0)
self.scene = UsdPhysics.Scene.Define(self._stage, Sdf.Path("/physicsScene"))
self.scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
self.scene.CreateGravityMagnitudeAttr().Set(9.81)
omni.kit.commands.execute(
"AddGroundPlaneCommand",
stage=self._stage,
planePath="/groundPlane",
axis="Z",
size=10.000,
position=Gf.Vec3f(0),
color=Gf.Vec3f(0.5),
)
# Colors to represent when gripper is open or closed
self.color_closed = Gf.Vec3f(1.0, 0.2, 0.2)
self.color_open = Gf.Vec3f(0.2, 1.0, 0.2)
# Cone that will represent the gripper
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._ee_path = self._server_root + "/Projects/RBROS2/mirobot_ros2/mirobot_description/urdf/mirobot_urdf_2/Link6.usd"
add_reference_to_stage(usd_path=self._ee_path, prim_path="/mirobot_ee")
ee_mesh = UsdGeom.Mesh.Get(self._stage, "/mirobot_ee")
physicsUtils.set_or_add_translate_op(ee_mesh, translate=Gf.Vec3f(0.0, 0.0, 0.30))
self.gripper_start_pose = dc.Transform([0.0, 0.0, 0.30], [1, 0, 0, 0])
# Box to be picked
self.box_start_pose = dc.Transform([0, 0, 0.10], [1, 0, 0, 0])
self.boxGeom = self.createRigidBody(
UsdGeom.Cube, "/Box", 0.0010, [0.01, 0.01, 0.01], self.box_start_pose.p, self.box_start_pose.r, [0.2, 0.2, 1]
)
# Reordering the quaternion to follow DC convention for later use.
self.gripper_start_pose = dc.Transform([0, 0, 0.301], [0, 0, 0, 1])
self.box_start_pose = dc.Transform([0, 0, 0.10], [0, 0, 0, 1])
# Gripper properties
self.sgp = Surface_Gripper_Properties()
self.sgp.d6JointPath = "/mirobot_ee/Link6/SurfaceGripper"
self.sgp.parentPath = "/mirobot_ee/Link6"
self.sgp.offset = dc.Transform()
self.sgp.offset.p.x = 0
self.sgp.offset.p.z = -0.02947
# 0, 1.5707963, 0 in Euler angles
self.sgp.offset.r = [0.7071, 0, 0.7071, 0] # Rotate to point gripper in Z direction
self.sgp.gripThreshold = 0.02
self.sgp.forceLimit = 1.0e2
self.sgp.torqueLimit = 1.0e3
self.sgp.bendAngle = np.pi / 4
self.sgp.stiffness = 1.0e4
self.sgp.damping = 1.0e3
self.surface_gripper = Surface_Gripper(self._dc)
self.surface_gripper.initialize(self.sgp)
# Set camera to a nearby pose and looking directly at the Gripper cone
set_camera_view(
eye=[4.00, 4.00, 4.00],
target=self.gripper_start_pose.p,
camera_prim_path="/OmniverseKit_Persp"
)
self._physx_subs = _physx.get_physx_interface().subscribe_physics_step_events(self._on_simulation_step)
self._timeline.play()
def _on_create_scenario_button_clicked(self):
# wait for new stage before creating scenario
task = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._create_scenario(task))
def _on_toggle_gripper_button_clicked(self, val=False):
if self._timeline.is_playing():
print(f"self.surface_gripper : {self.surface_gripper}")
print(f"self.surface_gripper.is_closed() : {self.surface_gripper.is_closed()}")
if self.surface_gripper.is_closed():
self.surface_gripper.open()
else:
self.surface_gripper.close()
if self.surface_gripper.is_closed():
self._models["toggle_button"].text = "OPEN"
else:
self._models["toggle_button"].text = "CLOSE"
def _on_speed_button_clicked(self):
if self._timeline.is_playing():
self._dc.set_rigid_body_linear_velocity(
self.cone, [0, 0, self._models["speed_slider"].get_value_as_float()]
)
def _on_force_button_clicked(self):
if self._timeline.is_playing():
self._dc.apply_body_force(
self.cone, [0, 0, self._models["force_slider"].get_value_as_float()], [0, 0, 0], True
)
def createRigidBody(self, bodyType, boxActorPath, mass, scale, position, rotation, color):
p = Gf.Vec3f(position[0], position[1], position[2])
orientation = Gf.Quatf(rotation[0], rotation[1], rotation[2], rotation[3])
scale = Gf.Vec3f(scale[0], scale[1], scale[2])
bodyGeom = bodyType.Define(self._stage, boxActorPath)
bodyPrim = self._stage.GetPrimAtPath(boxActorPath)
bodyGeom.AddTranslateOp().Set(p)
bodyGeom.AddOrientOp().Set(orientation)
bodyGeom.AddScaleOp().Set(scale)
bodyGeom.CreateDisplayColorAttr().Set([color])
UsdPhysics.CollisionAPI.Apply(bodyPrim)
if mass > 0:
massAPI = UsdPhysics.MassAPI.Apply(bodyPrim)
massAPI.CreateMassAttr(mass)
UsdPhysics.RigidBodyAPI.Apply(bodyPrim)
UsdPhysics.CollisionAPI(bodyPrim)
print(bodyPrim.GetPath().pathString)
return bodyGeom
| 17,570 |
Python
| 45.607427 | 171 | 0.552703 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SurfaceGripper/temp.py
|
# Copyright (c) 2018-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 weakref
import numpy as np
import omni
import omni.ext
import omni.kit.commands
import omni.kit.usd
import omni.physx as _physx
import omni.ui as ui
from omni.isaac.core.utils.viewports import set_camera_view
from omni.isaac.dynamic_control import _dynamic_control as dc
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.surface_gripper._surface_gripper import Surface_Gripper, Surface_Gripper_Properties
from omni.isaac.ui.menu import make_menu_item_description
from omni.isaac.ui.ui_utils import (
add_separator,
btn_builder,
combo_floatfield_slider_builder,
get_style,
setup_ui_headers,
state_btn_builder,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from pxr import Gf, Sdf, UsdGeom, UsdLux, UsdPhysics
import omni.isaac.core.utils.stage as stage_utils
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 omni.physx.scripts import deformableUtils, physicsUtils
import carb
EXTENSION_NAME = "Surface Gripper"
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
"""Initialize extension and UI elements"""
self._ext_id = ext_id
# Loads interfaces
self._timeline = omni.timeline.get_timeline_interface()
self._dc = dc.acquire_dynamic_control_interface()
self._usd_context = omni.usd.get_context()
self._window = None
self._models = {}
# Creates UI window with default size of 600x300
# self._window = omni.ui.Window(
# title=EXTENSION_NAME, width=300, height=200, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
# )
menu_items = [
make_menu_item_description(ext_id, EXTENSION_NAME, lambda a=weakref.proxy(self): a._menu_callback())
]
self._menu_items = [MenuItemDescription(name="Manipulation", sub_menu=menu_items)]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
self.surface_gripper = None
self.cone = None
self.box = None
self._stage_id = -1
def _build_ui(self):
if not self._window:
self._window = ui.Window(
title=EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.set_visibility_changed_fn(self._on_window)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Surface Gripper Example"
doc_link = "https://docs.omniverse.nvidia.com/isaacsim/latest/features/robots_simulation/ext_omni_isaac_surface_gripper.html"
overview = "This Example shows how to simulate a suction-cup gripper in Isaac Sim. "
overview += "It simulates suction by creating a Joint between two bodies when the parent and child bodies are close at the gripper's point of contact."
overview += "\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
args = {
"label": "Load Scene",
"type": "button",
"text": "Load",
"tooltip": "Load a gripper into the Scene",
"on_clicked_fn": self._on_create_scenario_button_clicked,
}
self._models["create_button"] = btn_builder(**args)
args = {
"label": "Gripper State",
"type": "button",
"a_text": "Close",
"b_text": "Open",
"tooltip": "Open and Close the Gripper",
"on_clicked_fn": self._on_toggle_gripper_button_clicked,
}
self._models["toggle_button"] = state_btn_builder(**args)
add_separator()
args = {
"label": "Gripper Force (UP)",
"default_val": 0,
"min": 0,
"max": 1.0e2,
"step": 1,
"tooltip": ["Force in ()", "Force in ()"],
}
self._models["force_slider"], slider = combo_floatfield_slider_builder(**args)
args = {
"label": "Set Force",
"type": "button",
"text": "APPLY",
"tooltip": "Apply the Gripper Force to the Z-Axis of the Cone",
"on_clicked_fn": self._on_force_button_clicked,
}
self._models["force_button"] = btn_builder(**args)
args = {
"label": "Gripper Speed (UP)",
"default_val": 0,
"min": 0,
"max": 5.0e1,
"step": 1,
"tooltip": ["Speed in ()", "Speed in ()"],
}
add_separator()
self._models["speed_slider"], slider = combo_floatfield_slider_builder(**args)
args = {
"label": "Set Speed",
"type": "button",
"text": "APPLY",
"tooltip": "Apply Cone Velocity in the Z-Axis",
"on_clicked_fn": self._on_speed_button_clicked,
}
self._models["speed_button"] = btn_builder(**args)
ui.Spacer()
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._physx_subs = None
self._window = None
def _on_window(self, status):
if status:
self._usd_context = omni.usd.get_context()
if self._usd_context is not None:
self._stage_event_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update_ui)
)
else:
self._stage_event_sub = None
self._physx_subs = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_update_ui(self, widget):
self._models["create_button"].enabled = self._timeline.is_playing()
self._models["toggle_button"].enabled = self._timeline.is_playing()
self._models["force_button"].enabled = self._timeline.is_playing()
self._models["speed_button"].enabled = self._timeline.is_playing()
# If the scene has been reloaded, reset UI to create Scenario
if self._usd_context.get_stage_id() != self._stage_id:
self._models["create_button"].enabled = True
# self._models["create_button"].text = "Create Scenario"
self._models["create_button"].set_tooltip("Creates a new scenario with the cone on top of the Cube")
self._models["create_button"].set_clicked_fn(self._on_create_scenario_button_clicked)
self.cone = None
self.box = None
self._stage_id = -1
def _toggle_gripper_button_ui(self):
# Checks if the surface gripper has been created
if self.surface_gripper is not None:
if self.surface_gripper.is_closed():
self._models["toggle_button"].text = "OPEN"
else:
self._models["toggle_button"].text = "CLOSE"
pass
def _on_simulation_step(self, step):
# Checks if the simulation is playing, and if the stage has been loaded
if self._timeline.is_playing() and self._stage_id != -1:
# Check if the handles for cone and box have been loaded
if self.cone is None:
# self.cone = self._dc.get_rigid_body("/GripperCone")
self.cone = self._dc.get_rigid_body("/mirobot_ee/Link6")
self.box = self._dc.get_rigid_body("/Box")
# If the surface Gripper has been created, update wheter it has been broken or not
if self.surface_gripper is not None:
self.surface_gripper.update()
# if self.surface_gripper.is_closed():
# self.coneGeom.GetDisplayColorAttr().Set([self.color_closed])
# else:
# self.coneGeom.GetDisplayColorAttr().Set([self.color_open])
self._toggle_gripper_button_ui()
def _on_reset_scenario_button_clicked(self):
if self._timeline.is_playing() and self._stage_id != -1:
if self.surface_gripper is not None:
self.surface_gripper.open()
self._dc.set_rigid_body_linear_velocity(self.cone, [0, 0, 0])
self._dc.set_rigid_body_linear_velocity(self.box, [0, 0, 0])
self._dc.set_rigid_body_angular_velocity(self.cone, [0, 0, 0])
self._dc.set_rigid_body_angular_velocity(self.box, [0, 0, 0])
self._dc.set_rigid_body_pose(self.cone, self.gripper_start_pose)
self._dc.set_rigid_body_pose(self.box, self.box_start_pose)
async def _create_scenario(self, task):
done, pending = await asyncio.wait({task})
if task in done:
# Repurpose button to reset Scene
# self._models["create_button"].text = "Reset Scene"
self._models["create_button"].set_tooltip("Resets scenario with the cone on top of the Cube")
# Get Handle for stage and stage ID to check if stage was reloaded
self._stage = self._usd_context.get_stage()
self._stage_id = self._usd_context.get_stage_id()
self._timeline.stop()
self._models["create_button"].set_clicked_fn(self._on_reset_scenario_button_clicked)
# Adds a light to the scene
distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
distantLight.AddOrientOp().Set(Gf.Quatf(-0.3748, -0.42060, -0.0716, 0.823))
# Set up stage with Z up, treat units as cm, set up gravity and ground plane
UsdGeom.SetStageUpAxis(self._stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(self._stage, 1.0)
self.scene = UsdPhysics.Scene.Define(self._stage, Sdf.Path("/physicsScene"))
self.scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
self.scene.CreateGravityMagnitudeAttr().Set(9.81)
omni.kit.commands.execute(
"AddGroundPlaneCommand",
stage=self._stage,
planePath="/groundPlane",
axis="Z",
size=10.000,
position=Gf.Vec3f(0),
color=Gf.Vec3f(0.5),
)
# Colors to represent when gripper is open or closed
self.color_closed = Gf.Vec3f(1.0, 0.2, 0.2)
self.color_open = Gf.Vec3f(0.2, 1.0, 0.2)
# Cone that will represent the gripper
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._ee_path = self._server_root + "/Projects/RBROS2/mirobot_ros2/mirobot_description/urdf/mirobot_urdf_2/Link6.usd"
add_reference_to_stage(usd_path=self._ee_path, prim_path="/mirobot_ee")
ee_mesh = UsdGeom.Mesh.Get(self._stage, "/mirobot_ee")
physicsUtils.set_or_add_translate_op(ee_mesh, translate=Gf.Vec3f(0.0, 0.0, 0.30))
self.gripper_start_pose = dc.Transform([0.0, 0.0, 0.30], [1, 0, 0, 0])
# Box to be picked
self.box_start_pose = dc.Transform([0, 0, 0.10], [1, 0, 0, 0])
self.boxGeom = self.createRigidBody(
UsdGeom.Cube, "/Box", 0.0010, [0.01, 0.01, 0.01], self.box_start_pose.p, self.box_start_pose.r, [0.2, 0.2, 1]
)
# Reordering the quaternion to follow DC convention for later use.
self.gripper_start_pose = dc.Transform([0, 0, 0.301], [0, 0, 0, 1])
self.box_start_pose = dc.Transform([0, 0, 0.10], [0, 0, 0, 1])
# Gripper properties
self.sgp = Surface_Gripper_Properties()
self.sgp.d6JointPath = "/mirobot_ee/Link6/SurfaceGripper"
self.sgp.parentPath = "/mirobot_ee/Link6"
self.sgp.offset = dc.Transform()
self.sgp.offset.p.x = 0
self.sgp.offset.p.z = -0.02947
# 0, 1.5707963, 0 in Euler angles
self.sgp.offset.r = [0.7071, 0, 0.7071, 0] # Rotate to point gripper in Z direction
self.sgp.gripThreshold = 0.02
self.sgp.forceLimit = 1.0e2
self.sgp.torqueLimit = 1.0e3
self.sgp.bendAngle = np.pi / 4
self.sgp.stiffness = 1.0e4
self.sgp.damping = 1.0e3
self.surface_gripper = Surface_Gripper(self._dc)
self.surface_gripper.initialize(self.sgp)
# Set camera to a nearby pose and looking directly at the Gripper cone
set_camera_view(
eye=[4.00, 4.00, 4.00],
target=self.gripper_start_pose.p,
camera_prim_path="/OmniverseKit_Persp"
)
self._physx_subs = _physx.get_physx_interface().subscribe_physics_step_events(self._on_simulation_step)
self._timeline.play()
def _on_create_scenario_button_clicked(self):
# wait for new stage before creating scenario
task = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._create_scenario(task))
def _on_toggle_gripper_button_clicked(self, val=False):
if self._timeline.is_playing():
print(f"self.surface_gripper : {self.surface_gripper}")
print(f"self.surface_gripper.is_closed() : {self.surface_gripper.is_closed()}")
if self.surface_gripper.is_closed():
self.surface_gripper.open()
else:
self.surface_gripper.close()
if self.surface_gripper.is_closed():
self._models["toggle_button"].text = "OPEN"
else:
self._models["toggle_button"].text = "CLOSE"
def _on_speed_button_clicked(self):
if self._timeline.is_playing():
self._dc.set_rigid_body_linear_velocity(
self.cone, [0, 0, self._models["speed_slider"].get_value_as_float()]
)
def _on_force_button_clicked(self):
if self._timeline.is_playing():
self._dc.apply_body_force(
self.cone, [0, 0, self._models["force_slider"].get_value_as_float()], [0, 0, 0], True
)
def createRigidBody(self, bodyType, boxActorPath, mass, scale, position, rotation, color):
p = Gf.Vec3f(position[0], position[1], position[2])
orientation = Gf.Quatf(rotation[0], rotation[1], rotation[2], rotation[3])
scale = Gf.Vec3f(scale[0], scale[1], scale[2])
bodyGeom = bodyType.Define(self._stage, boxActorPath)
bodyPrim = self._stage.GetPrimAtPath(boxActorPath)
bodyGeom.AddTranslateOp().Set(p)
bodyGeom.AddOrientOp().Set(orientation)
bodyGeom.AddScaleOp().Set(scale)
bodyGeom.CreateDisplayColorAttr().Set([color])
UsdPhysics.CollisionAPI.Apply(bodyPrim)
if mass > 0:
massAPI = UsdPhysics.MassAPI.Apply(bodyPrim)
massAPI.CreateMassAttr(mass)
UsdPhysics.RigidBodyAPI.Apply(bodyPrim)
UsdPhysics.CollisionAPI(bodyPrim)
print(bodyPrim.GetPath().pathString)
return bodyGeom
| 17,569 |
Python
| 45.604774 | 171 | 0.552621 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/SurfaceGripper/surface_gripper copy.py
|
# Copyright (c) 2018-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 weakref
import numpy as np
import omni
import omni.ext
import omni.kit.commands
import omni.kit.usd
import omni.physx as _physx
import omni.ui as ui
from omni.isaac.core.utils.viewports import set_camera_view
from omni.isaac.dynamic_control import _dynamic_control as dc
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.isaac.surface_gripper._surface_gripper import Surface_Gripper, Surface_Gripper_Properties
from omni.isaac.ui.menu import make_menu_item_description
from omni.isaac.ui.ui_utils import (
add_separator,
btn_builder,
combo_floatfield_slider_builder,
get_style,
setup_ui_headers,
state_btn_builder,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from pxr import Gf, Sdf, UsdGeom, UsdLux, UsdPhysics
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
import carb
EXTENSION_NAME = "Surface Gripper"
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
"""Initialize extension and UI elements"""
self._ext_id = ext_id
# Loads interfaces
self._timeline = omni.timeline.get_timeline_interface()
self._dc = dc.acquire_dynamic_control_interface()
self._usd_context = omni.usd.get_context()
self._window = None
self._models = {}
# Creates UI window with default size of 600x300
# self._window = omni.ui.Window(
# title=EXTENSION_NAME, width=300, height=200, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
# )
menu_items = [
make_menu_item_description(ext_id, EXTENSION_NAME, lambda a=weakref.proxy(self): a._menu_callback())
]
self._menu_items = [MenuItemDescription(name="Manipulation", sub_menu=menu_items)]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
self.surface_gripper = None
self.cone = None
self.box = None
self._stage_id = -1
def _build_ui(self):
if not self._window:
self._window = ui.Window(
title=EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.set_visibility_changed_fn(self._on_window)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Surface Gripper Example"
doc_link = "https://docs.omniverse.nvidia.com/isaacsim/latest/features/robots_simulation/ext_omni_isaac_surface_gripper.html"
overview = "This Example shows how to simulate a suction-cup gripper in Isaac Sim. "
overview += "It simulates suction by creating a Joint between two bodies when the parent and child bodies are close at the gripper's point of contact."
overview += "\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
args = {
"label": "Load Scene",
"type": "button",
"text": "Load",
"tooltip": "Load a gripper into the Scene",
"on_clicked_fn": self._on_create_scenario_button_clicked,
}
self._models["create_button"] = btn_builder(**args)
args = {
"label": "Gripper State",
"type": "button",
"a_text": "Close",
"b_text": "Open",
"tooltip": "Open and Close the Gripper",
"on_clicked_fn": self._on_toggle_gripper_button_clicked,
}
self._models["toggle_button"] = state_btn_builder(**args)
add_separator()
args = {
"label": "Gripper Force (UP)",
"default_val": 0,
"min": 0,
"max": 1.0e2,
"step": 1,
"tooltip": ["Force in ()", "Force in ()"],
}
self._models["force_slider"], slider = combo_floatfield_slider_builder(**args)
args = {
"label": "Set Force",
"type": "button",
"text": "APPLY",
"tooltip": "Apply the Gripper Force to the Z-Axis of the Cone",
"on_clicked_fn": self._on_force_button_clicked,
}
self._models["force_button"] = btn_builder(**args)
args = {
"label": "Gripper Speed (UP)",
"default_val": 0,
"min": 0,
"max": 5.0e1,
"step": 1,
"tooltip": ["Speed in ()", "Speed in ()"],
}
add_separator()
self._models["speed_slider"], slider = combo_floatfield_slider_builder(**args)
args = {
"label": "Set Speed",
"type": "button",
"text": "APPLY",
"tooltip": "Apply Cone Velocity in the Z-Axis",
"on_clicked_fn": self._on_speed_button_clicked,
}
self._models["speed_button"] = btn_builder(**args)
ui.Spacer()
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._physx_subs = None
self._window = None
def _on_window(self, status):
if status:
self._usd_context = omni.usd.get_context()
if self._usd_context is not None:
self._stage_event_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update_ui)
)
else:
self._stage_event_sub = None
self._physx_subs = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_update_ui(self, widget):
self._models["create_button"].enabled = self._timeline.is_playing()
self._models["toggle_button"].enabled = self._timeline.is_playing()
self._models["force_button"].enabled = self._timeline.is_playing()
self._models["speed_button"].enabled = self._timeline.is_playing()
# If the scene has been reloaded, reset UI to create Scenario
if self._usd_context.get_stage_id() != self._stage_id:
self._models["create_button"].enabled = True
# self._models["create_button"].text = "Create Scenario"
self._models["create_button"].set_tooltip("Creates a new scenario with the cone on top of the Cube")
self._models["create_button"].set_clicked_fn(self._on_create_scenario_button_clicked)
self.cone = None
self.box = None
self._stage_id = -1
def _toggle_gripper_button_ui(self):
# Checks if the surface gripper has been created
if self.surface_gripper is not None:
if self.surface_gripper.is_closed():
self._models["toggle_button"].text = "OPEN"
else:
self._models["toggle_button"].text = "CLOSE"
pass
def _on_simulation_step(self, step):
# Checks if the simulation is playing, and if the stage has been loaded
if self._timeline.is_playing() and self._stage_id != -1:
# Check if the handles for cone and box have been loaded
if self.cone is None:
self.cone = self._dc.get_rigid_body("/GripperCone")
self.box = self._dc.get_rigid_body("/Box")
# If the surface Gripper has been created, update wheter it has been broken or not
if self.surface_gripper is not None:
self.surface_gripper.update()
if self.surface_gripper.is_closed():
self.coneGeom.GetDisplayColorAttr().Set([self.color_closed])
else:
self.coneGeom.GetDisplayColorAttr().Set([self.color_open])
self._toggle_gripper_button_ui()
def _on_reset_scenario_button_clicked(self):
if self._timeline.is_playing() and self._stage_id != -1:
if self.surface_gripper is not None:
self.surface_gripper.open()
self._dc.set_rigid_body_linear_velocity(self.cone, [0, 0, 0])
self._dc.set_rigid_body_linear_velocity(self.box, [0, 0, 0])
self._dc.set_rigid_body_angular_velocity(self.cone, [0, 0, 0])
self._dc.set_rigid_body_angular_velocity(self.box, [0, 0, 0])
self._dc.set_rigid_body_pose(self.cone, self.gripper_start_pose)
self._dc.set_rigid_body_pose(self.box, self.box_start_pose)
async def _create_scenario(self, task):
done, pending = await asyncio.wait({task})
if task in done:
# Repurpose button to reset Scene
# self._models["create_button"].text = "Reset Scene"
self._models["create_button"].set_tooltip("Resets scenario with the cone on top of the Cube")
# Get Handle for stage and stage ID to check if stage was reloaded
self._stage = self._usd_context.get_stage()
self._stage_id = self._usd_context.get_stage_id()
self._timeline.stop()
self._models["create_button"].set_clicked_fn(self._on_reset_scenario_button_clicked)
# Adds a light to the scene
distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
distantLight.AddOrientOp().Set(Gf.Quatf(-0.3748, -0.42060, -0.0716, 0.823))
# Set up stage with Z up, treat units as cm, set up gravity and ground plane
UsdGeom.SetStageUpAxis(self._stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(self._stage, 1.0)
self.scene = UsdPhysics.Scene.Define(self._stage, Sdf.Path("/physicsScene"))
self.scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
self.scene.CreateGravityMagnitudeAttr().Set(9.81)
omni.kit.commands.execute(
"AddGroundPlaneCommand",
stage=self._stage,
planePath="/groundPlane",
axis="Z",
size=10.000,
position=Gf.Vec3f(0),
color=Gf.Vec3f(0.5),
)
# Colors to represent when gripper is open or closed
self.color_closed = Gf.Vec3f(1.0, 0.2, 0.2)
self.color_open = Gf.Vec3f(0.2, 1.0, 0.2)
# Cone that will represent the gripper
self.gripper_start_pose = dc.Transform([0, 0, 0.301], [1, 0, 0, 0])
self.coneGeom = self.createRigidBody(
UsdGeom.Cone,
"/GripperCone",
0.100,
[0.10, 0.10, 0.10],
self.gripper_start_pose.p,
self.gripper_start_pose.r,
self.color_open,
)
# Box to be picked
self.box_start_pose = dc.Transform([0, 0, 0.10], [1, 0, 0, 0])
self.boxGeom = self.createRigidBody(
UsdGeom.Cube, "/Box", 0.10, [0.1, 0.1, 0.1], self.box_start_pose.p, self.box_start_pose.r, [0.2, 0.2, 1]
)
# Reordering the quaternion to follow DC convention for later use.
self.gripper_start_pose = dc.Transform([0, 0, 0.301], [0, 0, 0, 1])
self.box_start_pose = dc.Transform([0, 0, 0.10], [0, 0, 0, 1])
# Gripper properties
self.sgp = Surface_Gripper_Properties()
self.sgp.d6JointPath = "/GripperCone/SurfaceGripper"
self.sgp.parentPath = "/GripperCone"
self.sgp.offset = dc.Transform()
self.sgp.offset.p.x = 0
self.sgp.offset.p.z = -0.1001
# 0, 1.5707963, 0 in Euler angles
self.sgp.offset.r = [0.7071, 0, 0.7071, 0] # Rotate to point gripper in Z direction
self.sgp.gripThreshold = 0.02
self.sgp.forceLimit = 1.0e2
self.sgp.torqueLimit = 1.0e3
self.sgp.bendAngle = np.pi / 4
self.sgp.stiffness = 1.0e4
self.sgp.damping = 1.0e3
self.surface_gripper = Surface_Gripper(self._dc)
self.surface_gripper.initialize(self.sgp)
# Set camera to a nearby pose and looking directly at the Gripper cone
set_camera_view(
eye=[4.00, 4.00, 4.00], target=self.gripper_start_pose.p, camera_prim_path="/OmniverseKit_Persp"
)
self._physx_subs = _physx.get_physx_interface().subscribe_physics_step_events(self._on_simulation_step)
self._timeline.play()
def _on_create_scenario_button_clicked(self):
# wait for new stage before creating scenario
task = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._create_scenario(task))
def _on_toggle_gripper_button_clicked(self, val=False):
if self._timeline.is_playing():
if self.surface_gripper.is_closed():
self.surface_gripper.open()
else:
self.surface_gripper.close()
if self.surface_gripper.is_closed():
self._models["toggle_button"].text = "OPEN"
else:
self._models["toggle_button"].text = "CLOSE"
def _on_speed_button_clicked(self):
if self._timeline.is_playing():
self._dc.set_rigid_body_linear_velocity(
self.cone, [0, 0, self._models["speed_slider"].get_value_as_float()]
)
def _on_force_button_clicked(self):
if self._timeline.is_playing():
self._dc.apply_body_force(
self.cone, [0, 0, self._models["force_slider"].get_value_as_float()], [0, 0, 0], True
)
def createRigidBody(self, bodyType, boxActorPath, mass, scale, position, rotation, color):
p = Gf.Vec3f(position[0], position[1], position[2])
orientation = Gf.Quatf(rotation[0], rotation[1], rotation[2], rotation[3])
scale = Gf.Vec3f(scale[0], scale[1], scale[2])
bodyGeom = bodyType.Define(self._stage, boxActorPath)
bodyPrim = self._stage.GetPrimAtPath(boxActorPath)
bodyGeom.AddTranslateOp().Set(p)
bodyGeom.AddOrientOp().Set(orientation)
bodyGeom.AddScaleOp().Set(scale)
bodyGeom.CreateDisplayColorAttr().Set([color])
UsdPhysics.CollisionAPI.Apply(bodyPrim)
if mass > 0:
massAPI = UsdPhysics.MassAPI.Apply(bodyPrim)
massAPI.CreateMassAttr(mass)
UsdPhysics.RigidBodyAPI.Apply(bodyPrim)
UsdPhysics.CollisionAPI(bodyPrim)
print(bodyPrim.GetPath().pathString)
return bodyGeom
| 16,836 |
Python
| 44.505405 | 171 | 0.544904 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloMultiTask/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/HelloMultiTask/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_multi_task import HelloMultiTask
"""
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="HelloMultiTask",
title="HelloMultiTask",
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=HelloMultiTask(),
)
return
| 2,053 |
Python
| 41.791666 | 135 | 0.74038 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloMultiTask/__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/HelloMultiTask/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/HelloMultiTask/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/HelloMultiTask/hello_multi_task.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.tasks import PickPlace
from omni.isaac.franka.controllers import PickPlaceController
from omni.isaac.wheeled_robots.robots import WheeledRobot
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.wheeled_robots.controllers import WheelBasePoseController
from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController
from omni.isaac.core.tasks import BaseTask
from omni.isaac.core.utils.types import ArticulationAction
# Find a unique string name, to use it for prim paths and scene names
from omni.isaac.core.utils.string import find_unique_string_name # Creates a unique prim path
from omni.isaac.core.utils.prims import is_prim_path_valid # Checks if a prim path is valid
from omni.isaac.core.objects.cuboid import VisualCuboid
import numpy as np
class RobotsPlaying(BaseTask):
def __init__(self, name, offset=None):
super().__init__(name=name, offset=offset)
self._task_event = 0
# Randomize the task a bit
self._jetbot_goal_position = np.array([np.random.uniform(1.2, 1.6), 0.3, 0]) + self._offset
self._pick_place_task = PickPlace(cube_initial_position=np.array([0.1, 0.3, 0.05]),
target_position=np.array([0.7, -0.3, 0.0515 / 2.0]),
offset=offset)
return
def set_up_scene(self, scene):
super().set_up_scene(scene)
self._pick_place_task.set_up_scene(scene)
jetbot_name = find_unique_string_name(
initial_name="fancy_jetbot", is_unique_fn=lambda x: not self.scene.object_exists(x)
)
jetbot_prim_path = find_unique_string_name(
initial_name="/World/Fancy_Jetbot", is_unique_fn=lambda x: not is_prim_path_valid(x)
)
assets_root_path = get_assets_root_path()
jetbot_asset_path = assets_root_path + "/Isaac/Robots/Jetbot/jetbot.usd"
self._jetbot = scene.add(
WheeledRobot(
prim_path=jetbot_prim_path,
name=jetbot_name,
wheel_dof_names=["left_wheel_joint", "right_wheel_joint"],
create_robot=True,
usd_path=jetbot_asset_path,
position=np.array([0, 0.3, 0]),
)
)
self._task_objects[self._jetbot.name] = self._jetbot
pick_place_params = self._pick_place_task.get_params()
self._franka = scene.get_object(pick_place_params["robot_name"]["value"])
current_position, _ = self._franka.get_world_pose()
self._franka.set_world_pose(position=current_position + np.array([1.0, 0, 0]))
self._franka.set_default_state(position=current_position + np.array([1.0, 0, 0]))
self._move_task_objects_to_their_frame()
return
def get_observations(self):
current_jetbot_position, current_jetbot_orientation = self._jetbot.get_world_pose()
observations= {
self.name + "_event": self._task_event, #change task event to make it unique
self._jetbot.name: {
"position": current_jetbot_position,
"orientation": current_jetbot_orientation,
"goal_position": self._jetbot_goal_position
}
}
observations.update(self._pick_place_task.get_observations())
return observations
def get_params(self):
pick_place_params = self._pick_place_task.get_params()
params_representation = pick_place_params
params_representation["jetbot_name"] = {"value": self._jetbot.name, "modifiable": False}
params_representation["franka_name"] = pick_place_params["robot_name"]
return params_representation
def pre_step(self, control_index, simulation_time):
if self._task_event == 0:
current_jetbot_position, _ = self._jetbot.get_world_pose()
if np.mean(np.abs(current_jetbot_position[:2] - self._jetbot_goal_position[:2])) < 0.04:
self._task_event += 1
self._cube_arrive_step_index = control_index
elif self._task_event == 1:
if control_index - self._cube_arrive_step_index == 200:
self._task_event += 1
return
def post_reset(self):
self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions)
self._task_event = 0
return
class HelloMultiTask(BaseSample):
def __init__(self) -> None:
super().__init__()
# Add lists for tasks,
self._tasks = []
self._num_of_tasks = 3
# Add lists for controllers
self._franka_controllers = []
self._jetbot_controllers = []
# Add lists for variables needed for control
self._jetbots = []
self._frankas = []
self._cube_names = []
return
def setup_scene(self):
world = self.get_world()
for i in range(self._num_of_tasks):
world.add_task(RobotsPlaying(name="my_awesome_task_" + str(i), offset=np.array([0, (i * 2) - 3, 0])))
return
async def setup_post_load(self):
self._world = self.get_world()
for i in range(self._num_of_tasks):
self._tasks.append(self._world.get_task(name="my_awesome_task_" + str(i)))
# Get variables needed for control
task_params = self._tasks[i].get_params()
self._frankas.append(self._world.scene.get_object(task_params["franka_name"]["value"]))
self._jetbots.append(self._world.scene.get_object(task_params["jetbot_name"]["value"]))
self._cube_names.append(task_params["cube_name"]["value"])
# Define controllers
self._franka_controllers.append(PickPlaceController(name="pick_place_controller",
gripper=self._frankas[i].gripper,
robot_articulation=self._frankas[i],
# Change the default events dt of the
# pick and place controller to slow down some of the transitions
# to pick up further blocks
# Note: this is a simple pick and place state machine
# based on events dt and not event success
# check the different events description in the api
# documentation
events_dt=[0.008, 0.002, 0.5, 0.1, 0.05, 0.05, 0.0025, 1, 0.008, 0.08]))
self._jetbot_controllers.append(WheelBasePoseController(name="cool_controller",
open_loop_wheel_controller=
DifferentialController(name="simple_control",
wheel_radius=0.03, wheel_base=0.1125)))
self._world.add_physics_callback("sim_step", callback_fn=self.physics_step)
await self._world.play_async()
return
async def setup_post_reset(self):
for i in range(len(self._tasks)):
# Reset all controllers
self._franka_controllers[i].reset()
self._jetbot_controllers[i].reset()
await self._world.play_async()
return
def physics_step(self, step_size):
current_observations = self._world.get_observations()
for i in range(len(self._tasks)):
# Apply actions for each task
if current_observations[self._tasks[i].name + "_event"] == 0:
self._jetbots[i].apply_wheel_actions(
self._jetbot_controllers[i].forward(
start_position=current_observations[self._jetbots[i].name]["position"],
start_orientation=current_observations[self._jetbots[i].name]["orientation"],
goal_position=current_observations[self._jetbots[i].name]["goal_position"]))
elif current_observations[self._tasks[i].name + "_event"] == 1:
self._jetbots[i].apply_wheel_actions(ArticulationAction(joint_velocities=[-8.0, -8.0]))
elif current_observations[self._tasks[i].name + "_event"] == 2:
self._jetbots[i].apply_wheel_actions(ArticulationAction(joint_velocities=[0.0, 0.0]))
actions = self._franka_controllers[i].forward(
picking_position=current_observations[self._cube_names[i]]["position"],
placing_position=current_observations[self._cube_names[i]]["target_position"],
current_joint_positions=current_observations[self._frankas[i].name]["joint_positions"])
self._frankas[i].apply_action(actions)
return
# This function is called after a hot reload or a clear
# to delete the variables defined in this extension application
def world_cleanup(self):
self._tasks = []
self._franka_controllers = []
self._jetbot_controllers = []
self._jetbots = []
self._frankas = []
self._cube_names = []
return
| 10,052 |
Python
| 51.088083 | 136 | 0.575308 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloLight/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/HelloLight/hello_light.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
import omni.usd
# Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html
from omni.isaac.core.objects import DynamicCuboid
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf, UsdLux
class HelloLight(BaseSample):
def __init__(self) -> None:
super().__init__()
return
def setup_scene(self):
world = self.get_world()
world.scene.add_default_ground_plane()
fancy_cube = world.scene.add(
DynamicCuboid(
prim_path="/World/random_cube", # The prim path of the cube in the USD stage
name="fancy_cube", # The unique name used to retrieve the object from the scene later on
position=np.array([0, 0, 1.0]), # Using the current stage units which is in meters by default.
scale=np.array([0.5015, 0.5015, 0.5015]), # most arguments accept mainly numpy arrays.
color=np.array([0, 0, 1.0]), # RGB channels, going from 0-1
))
stage = omni.usd.get_context().get_stage()
## Create a Sphere light
# sphereLight = UsdLux.SphereLight.Define(stage, Sdf.Path("/World/SphereLight"))
# sphereLight.CreateRadiusAttr(150)
# sphereLight.CreateIntensityAttr(30000)
# sphereLight.AddTranslateOp().Set(Gf.Vec3f(650.0, 0.0, 1150.0))
## Create a distant light
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/World/distantLight"))
distantLight.CreateIntensityAttr(1000)
## Rotatation and translation of the light
# distantLight.AddRotateXYZOp().Set((-36, 36, 0))
# distantLight.AddTranslateOp().Set(Gf.Vec3f(650.0, 0.0, 1150.0))
return
# Here we assign the class's variables
# this function is called after load button is pressed
# regardless starting from an empty stage or not
# this is called after setup_scene and after
# one physics time step to propagate appropriate
# physics handles which are needed to retrieve
# many physical properties of the different objects
async def setup_post_load(self):
self._world = self.get_world()
self._cube = self._world.scene.get_object("fancy_cube")
self._world.add_physics_callback("sim_step", callback_fn=self.print_cube_info) #callback names have to be unique
return
# here we define the physics callback to be called before each physics step, all physics callbacks must take
# step_size as an argument
def print_cube_info(self, step_size):
position, orientation = self._cube.get_world_pose()
linear_velocity = self._cube.get_linear_velocity()
# will be shown on terminal
print("Cube position is : " + str(position))
print("Cube's orientation is : " + str(orientation))
print("Cube's linear velocity is : " + str(linear_velocity))
# async def setup_pre_reset(self):
# return
# async def setup_post_reset(self):
# return
# def world_cleanup(self):
# return
| 3,588 |
Python
| 40.732558 | 120 | 0.671126 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloLight/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_light import HelloLight
"""
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="HelloLight",
title="HelloLight",
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=HelloLight(),
)
return
| 2,032 |
Python
| 41.354166 | 135 | 0.738189 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloLight/__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/HelloLight/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/HelloLight/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/HelloLight/hello_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.utils.types import ArticulationAction
import numpy as np
class HelloWorld(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()
jetbot_asset_path = assets_root_path + "/Isaac/Robots/Jetbot/jetbot.usd"
self._jetbot = world.scene.add(
WheeledRobot(
prim_path="/World/Fancy_Robot",
name="fancy_robot",
wheel_dof_names=["left_wheel_joint", "right_wheel_joint"],
create_robot=True,
usd_path=jetbot_asset_path,
)
)
return
async def setup_post_load(self):
self._world = self.get_world()
self._jetbot = self._world.scene.get_object("fancy_robot")
self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions)
return
def send_robot_actions(self, step_size):
self._jetbot.apply_wheel_actions(ArticulationAction(joint_positions=None,
joint_efforts=None,
joint_velocities=5 * np.random.rand(2,)))
return
| 1,954 |
Python
| 39.729166 | 101 | 0.634084 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/ik_solver.py
|
from omni.isaac.motion_generation import ArticulationKinematicsSolver, LulaKinematicsSolver
from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root
from omni.isaac.core.articulations import Articulation
from typing import Optional
import carb
class KinematicsSolver(ArticulationKinematicsSolver):
def __init__(self, robot_articulation: Articulation, end_effector_frame_name: Optional[str] = None) -> None:
#TODO: change the config path
# desktop
# my_path = "/home/kimsooyoung/Documents/IsaacSim/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/"
# self._urdf_path = "/home/kimsooyoung/Downloads/USD/cobotta_pro_900/"
# lactop
self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/MirobotFollowTarget/"
self._urdf_path = "/home/kimsooyoung/Downloads/Source/mirobot_ros2/mirobot_description/urdf/"
self._kinematics = LulaKinematicsSolver(
robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml",
urdf_path=self._urdf_path+"mirobot_urdf_2.urdf"
)
if end_effector_frame_name is None:
end_effector_frame_name = "Link6"
ArticulationKinematicsSolver.__init__(self, robot_articulation, self._kinematics, end_effector_frame_name)
return
| 1,395 |
Python
| 45.533332 | 127 | 0.700358 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/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/MirobotPickandPlace/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 .pick_place_example import PickandPlaceExample
"""
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="AddingNewManip2",
name="PickandPlace",
title="PickandPlace",
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=PickandPlaceExample(),
)
return
| 2,076 |
Python
| 42.270832 | 135 | 0.743256 |
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotPickandPlace/__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/MirobotPickandPlace/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/MirobotPickandPlace/pick_place_example.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, get_url_root
from omni.isaac.manipulators.grippers.surface_gripper import SurfaceGripper
from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units
from omni.isaac.core.utils.rotations import euler_angles_to_quat
from omni.isaac.manipulators import SingleManipulator
from omni.isaac.dynamic_control import _dynamic_control as dc
from omni.isaac.core.prims import RigidPrim, GeometryPrim
from pxr import Gf, Sdf, UsdGeom, UsdLux, UsdPhysics
import numpy as np
import omni
import carb
from .controllers.pick_place import PickPlaceController
def createRigidBody(stage, bodyType, boxActorPath, mass, scale, position, rotation, color):
p = Gf.Vec3f(position[0], position[1], position[2])
orientation = Gf.Quatf(rotation[0], rotation[1], rotation[2], rotation[3])
scale = Gf.Vec3f(scale[0], scale[1], scale[2])
bodyGeom = bodyType.Define(stage, boxActorPath)
bodyPrim = stage.GetPrimAtPath(boxActorPath)
bodyGeom.AddTranslateOp().Set(p)
bodyGeom.AddOrientOp().Set(orientation)
bodyGeom.AddScaleOp().Set(scale)
bodyGeom.CreateDisplayColorAttr().Set([color])
UsdPhysics.CollisionAPI.Apply(bodyPrim)
if mass > 0:
massAPI = UsdPhysics.MassAPI.Apply(bodyPrim)
massAPI.CreateMassAttr(mass)
UsdPhysics.RigidBodyAPI.Apply(bodyPrim)
UsdPhysics.CollisionAPI(bodyPrim)
return bodyGeom
class PickandPlaceExample(BaseSample):
def __init__(self) -> None:
super().__init__()
self._gripper = None
self._my_mirobot = None
self._articulation_controller = None
# simulation step counter
self._sim_step = 0
self._target_position = np.array([0.2, -0.08, 0.06])
return
def setup_robot(self):
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._robot_path = self._server_root + "/Projects/RBROS2/mirobot_ros2/mirobot_description/urdf/mirobot_urdf_2/mirobot_urdf_2_ee.usd"
add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/mirobot")
# define the gripper
self._gripper = SurfaceGripper(
end_effector_prim_path="/World/mirobot/ee_link",
translate=0.02947,
direction="x",
# kp=1.0e4,
# kd=1.0e3,
# disable_gravity=False,
)
self._gripper.set_force_limit(value=1.0e2)
self._gripper.set_torque_limit(value=1.0e3)
# define the manipulator
self._my_mirobot = self._world.scene.add(
SingleManipulator(
prim_path="/World/mirobot",
name="mirobot",
end_effector_prim_name="ee_link",
gripper=self._gripper
)
)
self._joints_default_positions = np.zeros(6)
self._my_mirobot.set_joints_default_state(positions=self._joints_default_positions)
def setup_bin(self):
self._nucleus_server = get_assets_root_path()
table_path = self._nucleus_server + "/Isaac/Props/KLT_Bin/small_KLT.usd"
add_reference_to_stage(usd_path=table_path, prim_path=f"/World/bin")
self._bin_initial_position = np.array([0.2, 0.08, 0.06]) / get_stage_units()
self._packing_bin = self._world.scene.add(
GeometryPrim(
prim_path="/World/bin",
name=f"packing_bin",
position=self._bin_initial_position,
orientation=euler_angles_to_quat(np.array([np.pi, 0, 0])),
scale=np.array([0.25, 0.25, 0.25]),
collision=True
)
)
self._packing_bin_geom = self._world.scene.get_object(f"packing_bin")
massAPI = UsdPhysics.MassAPI.Apply(self._packing_bin_geom.prim.GetPrim())
massAPI.CreateMassAttr().Set(0.001)
def setup_box(self):
# Box to be picked
self.box_start_pose = dc.Transform([0.2, 0.08, 0.06], [1, 0, 0, 0])
self._stage = omni.usd.get_context().get_stage()
self._boxGeom = createRigidBody(
self._stage,
UsdGeom.Cube,
"/World/Box",
0.0010,
[0.015, 0.015, 0.015],
self.box_start_pose.p,
self.box_start_pose.r,
[0.2, 0.2, 1]
)
def setup_scene(self):
self._world = self.get_world()
self._world.scene.add_default_ground_plane()
self.setup_robot()
# self.setup_bin()
self.setup_box()
return
async def setup_post_load(self):
self._world = self.get_world()
self._my_controller = PickPlaceController(
name="controller",
gripper=self._gripper,
robot_articulation=self._my_mirobot,
events_dt=[
0.008,
0.005,
0.1,
0.1,
0.0025,
0.001,
0.0025,
0.5,
0.008,
0.08
],
)
self._articulation_controller = self._my_mirobot.get_articulation_controller()
self._world.add_physics_callback("sim_step", callback_fn=self.sim_step_cb)
return
async def setup_post_reset(self):
self._my_controller.reset()
await self._world.play_async()
return
def sim_step_cb(self, step_size):
# # bin case
# bin_pose, _ = self._packing_bin_geom.get_world_pose()
# pick_position = bin_pose
# place_position = self._target_position
# box case
box_matrix = omni.usd.get_world_transform_matrix(self._boxGeom)
box_trans = box_matrix.ExtractTranslation()
pick_position = np.array(box_trans)
place_position = self._target_position
joints_state = self._my_mirobot.get_joints_state()
actions = self._my_controller.forward(
picking_position=pick_position,
placing_position=place_position,
current_joint_positions=joints_state.positions,
# This offset needs tuning as well
end_effector_offset=np.array([0, 0, 0.02947+0.02]),
end_effector_orientation=euler_angles_to_quat(np.array([0, 0, 0])),
)
if self._my_controller.is_done():
print("done picking and placing")
self._articulation_controller.apply_action(actions)
return
| 7,121 |
Python
| 34.969697 | 140 | 0.611852 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.