file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/extension.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import gc import os import weakref import carb import omni.client import omni.ext import omni.ui as ui from omni.importer.urdf import _urdf from omni.importer.urdf.scripts.ui import ( btn_builder, cb_builder, dropdown_builder, float_builder, get_style, make_menu_item_description, setup_ui_headers, str_builder, ) from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items from pxr import Sdf, Usd, UsdGeom, UsdPhysics # from .menu import make_menu_item_description # from .ui_utils import ( # btn_builder, # cb_builder, # dropdown_builder, # float_builder, # get_style, # setup_ui_headers, # str_builder, # ) EXTENSION_NAME = "URDF Importer" def is_urdf_file(path: str): _, ext = os.path.splitext(path.lower()) return ext in [".urdf", ".URDF"] def on_filter_item(item) -> bool: if not item or item.is_folder: return not (item.name == "Omniverse" or item.path.startswith("omniverse:")) return is_urdf_file(item.path) def on_filter_folder(item) -> bool: if item and item.is_folder: return True else: return False class Extension(omni.ext.IExt): def on_startup(self, ext_id): self._ext_id = ext_id self._urdf_interface = _urdf.acquire_urdf_interface() self._usd_context = omni.usd.get_context() self._window = omni.ui.Window( EXTENSION_NAME, width=400, height=500, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) self._window.set_visibility_changed_fn(self._on_window) menu_items = [ make_menu_item_description(ext_id, EXTENSION_NAME, lambda a=weakref.proxy(self): a._menu_callback()) ] self._menu_items = [MenuItemDescription(name="Workflows", sub_menu=menu_items)] add_menu_items(self._menu_items, "Isaac Utils") self._file_picker = None self._models = {} result, self._config = omni.kit.commands.execute("URDFCreateImportConfig") self._filepicker = None self._last_folder = None self._content_browser = None self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) self._imported_robot = None # Set defaults self._config.set_merge_fixed_joints(False) self._config.set_replace_cylinders_with_capsules(False) self._config.set_convex_decomp(False) self._config.set_fix_base(True) self._config.set_import_inertia_tensor(False) self._config.set_distance_scale(1.0) self._config.set_density(0.0) self._config.set_default_drive_type(1) self._config.set_default_drive_strength(1e7) self._config.set_default_position_drive_damping(1e5) self._config.set_self_collision(False) self._config.set_up_vector(0, 0, 1) self._config.set_make_default_prim(True) self._config.set_create_physics_scene(True) self._config.set_collision_from_visuals(False) def build_ui(self): with self._window.frame: with ui.VStack(spacing=5, height=0): self._build_info_ui() self._build_options_ui() self._build_import_ui() stage = self._usd_context.get_stage() if stage: if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.y: self._config.set_up_vector(0, 1, 0) if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z: self._config.set_up_vector(0, 0, 1) units_per_meter = 1.0 / UsdGeom.GetStageMetersPerUnit(stage) self._models["scale"].set_value(units_per_meter) async def dock_window(): await omni.kit.app.get_app().next_update_async() def dock(space, name, location, pos=0.5): window = omni.ui.Workspace.get_window(name) if window and space: window.dock_in(space, location, pos) return window tgt = ui.Workspace.get_window("Viewport") dock(tgt, EXTENSION_NAME, omni.ui.DockPosition.LEFT, 0.33) await omni.kit.app.get_app().next_update_async() self._task = asyncio.ensure_future(dock_window()) def _build_info_ui(self): title = EXTENSION_NAME doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = "This utility is used to import URDF representations of robots into Isaac Sim. " overview += "URDF is an XML format for representing a robot model in ROS." overview += "\n\nPress the 'Open in IDE' button to view the source code." setup_ui_headers(self._ext_id, __file__, title, doc_link, overview) def _build_options_ui(self): frame = ui.CollapsableFrame( title="Import Options", 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, height=0): cb_builder( label="Merge Fixed Joints", tooltip="Consolidate links that are connected by fixed joints.", on_clicked_fn=lambda m, config=self._config: config.set_merge_fixed_joints(m), ) cb_builder( label="Replace Cylinders with Capsules", tooltip="Replace Cylinder collision bodies by capsules.", on_clicked_fn=lambda m, config=self._config: config.set_replace_cylinders_with_capsules(m), ) cb_builder( "Fix Base Link", tooltip="Fix the robot base robot to where it's imported in world coordinates.", default_val=True, on_clicked_fn=lambda m, config=self._config: config.set_fix_base(m), ) cb_builder( "Import Inertia Tensor", tooltip="Load inertia tensor directly from the URDF.", on_clicked_fn=lambda m, config=self._config: config.set_import_inertia_tensor(m), ) self._models["scale"] = float_builder( "Stage Units Per Meter", default_val=1.0, tooltip="Sets the scaling factor to match the units used in the URDF. Default Stage units are (cm).", ) self._models["scale"].add_value_changed_fn( lambda m, config=self._config: config.set_distance_scale(m.get_value_as_float()) ) self._models["density"] = float_builder( "Link Density", default_val=0.0, tooltip="Density value to compute mass based on link volume. Use 0.0 to automatically compute density.", ) self._models["density"].add_value_changed_fn( lambda m, config=self._config: config.set_density(m.get_value_as_float()) ) dropdown_builder( "Joint Drive Type", items=["None", "Position", "Velocity"], default_val=1, on_clicked_fn=lambda i, config=self._config: config.set_default_drive_type( 0 if i == "None" else (1 if i == "Position" else 2) ), tooltip="Default Joint drive type.", ) self._models["drive_strength"] = float_builder( "Joint Drive Strength", default_val=1e4, tooltip="Joint stiffness for position drive, or damping for velocity driven joints. Set to -1 to prevent this parameter from getting used.", ) self._models["drive_strength"].add_value_changed_fn( lambda m, config=self._config: config.set_default_drive_strength(m.get_value_as_float()) ) self._models["position_drive_damping"] = float_builder( "Joint Position Damping", default_val=1e3, tooltip="Default damping value when drive type is set to Position. Set to -1 to prevent this parameter from getting used.", ) self._models["position_drive_damping"].add_value_changed_fn( lambda m, config=self._config: config.set_default_position_drive_damping(m.get_value_as_float()) ) self._models["clean_stage"] = cb_builder( label="Clear Stage", tooltip="Clear the Stage prior to loading the URDF." ) dropdown_builder( "Normals Subdivision", items=["catmullClark", "loop", "bilinear", "none"], default_val=2, on_clicked_fn=lambda i, dict={ "catmullClark": 0, "loop": 1, "bilinear": 2, "none": 3, }, config=self._config: config.set_subdivision_scheme(dict[i]), tooltip="Mesh surface normal subdivision scheme. Use `none` to avoid overriding authored values.", ) cb_builder( "Convex Decomposition", tooltip="Decompose non-convex meshes into convex collision shapes. If false, convex hull will be used.", on_clicked_fn=lambda m, config=self._config: config.set_convex_decomp(m), ) cb_builder( "Self Collision", tooltip="Enables self collision between adjacent links.", on_clicked_fn=lambda m, config=self._config: config.set_self_collision(m), ) cb_builder( "Collision From Visuals", tooltip="Creates collision geometry from visual geometry.", on_clicked_fn=lambda m, config=self._config: config.set_collision_from_visuals(m), ) cb_builder( "Create Physics Scene", tooltip="Creates a default physics scene on the stage on import.", default_val=True, on_clicked_fn=lambda m, config=self._config: config.set_create_physics_scene(m), ) cb_builder( "Create Instanceable Asset", tooltip="If true, creates an instanceable version of the asset. Meshes will be saved in a separate USD file", default_val=False, on_clicked_fn=lambda m, config=self._config: config.set_make_instanceable(m), ) self._models["instanceable_usd_path"] = str_builder( "Instanceable USD Path", tooltip="USD file to store instanceable meshes in", default_val="./instanceable_meshes.usd", use_folder_picker=True, folder_dialog_title="Select Output File", folder_button_title="Select File", ) self._models["instanceable_usd_path"].add_value_changed_fn( lambda m, config=self._config: config.set_instanceable_usd_path(m.get_value_as_string()) ) def _build_import_ui(self): frame = ui.CollapsableFrame( title="Import", 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, height=0): def check_file_type(model=None): path = model.get_value_as_string() if is_urdf_file(path) and "omniverse:" not in path.lower(): self._models["import_btn"].enabled = True else: carb.log_warn(f"Invalid path to URDF: {path}") kwargs = { "label": "Input File", "default_val": "", "tooltip": "Click the Folder Icon to Set Filepath", "use_folder_picker": True, "item_filter_fn": on_filter_item, "bookmark_label": "Built In URDF Files", "bookmark_path": f"{self._extension_path}/data/urdf", "folder_dialog_title": "Select URDF File", "folder_button_title": "Select URDF", } self._models["input_file"] = str_builder(**kwargs) self._models["input_file"].add_value_changed_fn(check_file_type) kwargs = { "label": "Output Directory", "type": "stringfield", "default_val": self.get_dest_folder(), "tooltip": "Click the Folder Icon to Set Filepath", "use_folder_picker": True, } self.dest_model = str_builder(**kwargs) # btn_builder("Import URDF", text="Select and Import", on_clicked_fn=self._parse_urdf) self._models["import_btn"] = btn_builder("Import", text="Import", on_clicked_fn=self._load_robot) self._models["import_btn"].enabled = False def get_dest_folder(self): stage = omni.usd.get_context().get_stage() if stage: path = stage.GetRootLayer().identifier if not path.startswith("anon"): basepath = path[: path.rfind("/")] if path.rfind("/") < 0: basepath = path[: path.rfind("\\")] return basepath return "(same as source)" def _menu_callback(self): self._window.visible = not self._window.visible def _on_window(self, visible): if self._window.visible: self.build_ui() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="urdf importer stage event" ) else: self._events = None self._stage_event_sub = None def _on_stage_event(self, event): stage = self._usd_context.get_stage() if event.type == int(omni.usd.StageEventType.OPENED) and stage: if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.y: self._config.set_up_vector(0, 1, 0) if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z: self._config.set_up_vector(0, 0, 1) units_per_meter = 1.0 / UsdGeom.GetStageMetersPerUnit(stage) self._models["scale"].set_value(units_per_meter) self.dest_model.set_value(self.get_dest_folder()) def _load_robot(self, path=None): path = self._models["input_file"].get_value_as_string() if path: dest_path = self.dest_model.get_value_as_string() base_path = path[: path.rfind("/")] basename = path[path.rfind("/") + 1 :] basename = basename[: basename.rfind(".")] if path.rfind("/") < 0: base_path = path[: path.rfind("\\")] basename = path[path.rfind("\\") + 1] if dest_path != "(same as source)": base_path = dest_path # + "/" + basename dest_path = "{}/{}/{}.usd".format(base_path, basename, basename) # counter = 1 # while result[0] == Result.OK: # dest_path = "{}/{}_{:02}.usd".format(base_path, basename, counter) # result = omni.client.read_file(dest_path) # counter +=1 # result = omni.client.read_file(dest_path) # if # stage = Usd.Stage.Open(dest_path) # else: # stage = Usd.Stage.CreateNew(dest_path) # UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=path, import_config=self._config, dest_path=dest_path ) # print("Created file, instancing it now") stage = Usd.Stage.Open(dest_path) prim_name = str(stage.GetDefaultPrim().GetName()) # print(prim_name) # stage.Save() def add_reference_to_stage(): current_stage = omni.usd.get_context().get_stage() if current_stage: prim_path = omni.usd.get_stage_next_free_path( current_stage, str(current_stage.GetDefaultPrim().GetPath()) + "/" + prim_name, False ) robot_prim = current_stage.OverridePrim(prim_path) if "anon:" in current_stage.GetRootLayer().identifier: robot_prim.GetReferences().AddReference(dest_path) else: robot_prim.GetReferences().AddReference( omni.client.make_relative_url(current_stage.GetRootLayer().identifier, dest_path) ) if self._config.create_physics_scene: UsdPhysics.Scene.Define(current_stage, Sdf.Path("/physicsScene")) async def import_with_clean_stage(): await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() add_reference_to_stage() await omni.kit.app.get_app().next_update_async() if self._models["clean_stage"].get_value_as_bool(): asyncio.ensure_future(import_with_clean_stage()) else: add_reference_to_stage() def on_shutdown(self): _urdf.release_urdf_interface(self._urdf_interface) remove_menu_items(self._menu_items, "Isaac Utils") if self._window: self._window = None gc.collect()
19,344
Python
43.267734
160
0.549783
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/__init__.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. #
431
Python
46.999995
76
0.812065
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/ui/style.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import carb.settings import omni.ui as ui from omni.kit.window.extensions.common import get_icons_path # Pilaged from omni.kit.widnow.property style.py LABEL_WIDTH = 120 BUTTON_WIDTH = 120 HORIZONTAL_SPACING = 4 VERTICAL_SPACING = 5 COLOR_X = 0xFF5555AA COLOR_Y = 0xFF76A371 COLOR_Z = 0xFFA07D4F COLOR_W = 0xFFAA5555 def get_style(): icons_path = get_icons_path() KIT_GREEN = 0xFF8A8777 KIT_GREEN_CHECKBOX = 0xFF9A9A9A BORDER_RADIUS = 1.5 FONT_SIZE = 14.0 TOOLTIP_STYLE = ( { "background_color": 0xFFD1F7FF, "color": 0xFF333333, "margin_width": 0, "margin_height": 0, "padding": 0, "border_width": 0, "border_radius": 1.5, "border_color": 0x0, }, ) style_settings = carb.settings.get_settings().get("/persistent/app/window/uiStyle") if not style_settings: style_settings = "NvidiaDark" if style_settings == "NvidiaLight": WINDOW_BACKGROUND_COLOR = 0xFF444444 BUTTON_BACKGROUND_COLOR = 0xFF545454 BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778 BUTTON_LABEL_DISABLED_COLOR = 0xFF606060 FRAME_TEXT_COLOR = 0xFF545454 FIELD_BACKGROUND = 0xFF545454 FIELD_SECONDARY = 0xFFABABAB FIELD_TEXT_COLOR = 0xFFD6D6D6 FIELD_TEXT_COLOR_READ_ONLY = 0xFF9C9C9C FIELD_TEXT_COLOR_HIDDEN = 0x01000000 COLLAPSABLEFRAME_BORDER_COLOR = 0x0 COLLAPSABLEFRAME_BACKGROUND_COLOR = 0x7FD6D6D6 COLLAPSABLEFRAME_TEXT_COLOR = 0xFF545454 COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFFC9C9C9 COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFFD6D6D6 COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFFCCCFBF COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR = 0xFFD6D6D6 COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR = 0xFFE6E6E6 LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD LABEL_MIXED_COLOR = 0xFFD6D6D6 LIGHT_FONT_SIZE = 14.0 LIGHT_BORDER_RADIUS = 3 style = { "Window": {"background_color": WINDOW_BACKGROUND_COLOR}, "Button": {"background_color": BUTTON_BACKGROUND_COLOR, "margin": 0, "padding": 3, "border_radius": 2}, "Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR}, "Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR}, "Button.Label:disabled": {"color": 0xFFD6D6D6}, "Button.Label": {"color": 0xFFD6D6D6}, "Field::models": { "background_color": FIELD_BACKGROUND, "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": LIGHT_BORDER_RADIUS, "secondary_color": FIELD_SECONDARY, }, "Field::models_mixed": { "background_color": FIELD_BACKGROUND, "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR_HIDDEN, "border_radius": LIGHT_BORDER_RADIUS, }, "Field::models_readonly": { "background_color": FIELD_BACKGROUND, "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR_READ_ONLY, "border_radius": LIGHT_BORDER_RADIUS, "secondary_color": FIELD_SECONDARY, }, "Field::models_readonly_mixed": { "background_color": FIELD_BACKGROUND, "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR_HIDDEN, "border_radius": LIGHT_BORDER_RADIUS, }, "Field::models:pressed": {"background_color": 0xFFCECECE}, "Field": {"background_color": 0xFF535354, "color": 0xFFCCCCCC}, "Label": {"font_size": 12, "color": FRAME_TEXT_COLOR}, "Label::label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR}, "Label::label": { "font_size": LIGHT_FONT_SIZE, "background_color": FIELD_BACKGROUND, "color": FRAME_TEXT_COLOR, }, "Label::title": { "font_size": LIGHT_FONT_SIZE, "background_color": FIELD_BACKGROUND, "color": FRAME_TEXT_COLOR, }, "Label::mixed_overlay": { "font_size": LIGHT_FONT_SIZE, "background_color": FIELD_BACKGROUND, "color": FRAME_TEXT_COLOR, }, "Label::mixed_overlay_normal": { "font_size": LIGHT_FONT_SIZE, "background_color": FIELD_BACKGROUND, "color": FRAME_TEXT_COLOR, }, "ComboBox::choices": { "font_size": 12, "color": 0xFFD6D6D6, "background_color": FIELD_BACKGROUND, "secondary_color": FIELD_BACKGROUND, "border_radius": LIGHT_BORDER_RADIUS * 2, }, "ComboBox::xform_op": { "font_size": 10, "color": 0xFF333333, "background_color": 0xFF9C9C9C, "secondary_color": 0x0, "selected_color": 0xFFACACAF, "border_radius": LIGHT_BORDER_RADIUS * 2, }, "ComboBox::xform_op:hovered": {"background_color": 0x0}, "ComboBox::xform_op:selected": {"background_color": 0xFF545454}, "ComboBox": { "font_size": 10, "color": 0xFFE6E6E6, "background_color": 0xFF545454, "secondary_color": 0xFF545454, "selected_color": 0xFFACACAF, "border_radius": LIGHT_BORDER_RADIUS * 2, }, # "ComboBox": {"background_color": 0xFF535354, "selected_color": 0xFFACACAF, "color": 0xFFD6D6D6}, "ComboBox:hovered": {"background_color": 0xFF545454}, "ComboBox:selected": {"background_color": 0xFF545454}, "ComboBox::choices_mixed": { "font_size": LIGHT_FONT_SIZE, "color": 0xFFD6D6D6, "background_color": FIELD_BACKGROUND, "secondary_color": FIELD_BACKGROUND, "secondary_selected_color": FIELD_TEXT_COLOR, "border_radius": LIGHT_BORDER_RADIUS * 2, }, "ComboBox:hovered:choices": {"background_color": FIELD_BACKGROUND, "secondary_color": FIELD_BACKGROUND}, "Slider": { "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": LIGHT_BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": WINDOW_BACKGROUND_COLOR, "draw_mode": ui.SliderDrawMode.FILLED, }, "Slider::value": { "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR, # COLLAPSABLEFRAME_TEXT_COLOR "border_radius": LIGHT_BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": KIT_GREEN, }, "Slider::value_mixed": { "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR_HIDDEN, "border_radius": LIGHT_BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": KIT_GREEN, }, "Slider::multivalue": { "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": LIGHT_BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": KIT_GREEN, "draw_mode": ui.SliderDrawMode.HANDLE, }, "Slider::multivalue_mixed": { "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR_HIDDEN, "border_radius": LIGHT_BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": KIT_GREEN, "draw_mode": ui.SliderDrawMode.HANDLE, }, "Checkbox": { "margin": 0, "padding": 0, "radius": 0, "font_size": 10, "background_color": 0xFFA8A8A8, "background_color": 0xFFA8A8A8, }, "CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F}, "CheckBox::greenCheck_mixed": { "font_size": 10, "background_color": KIT_GREEN, "color": FIELD_TEXT_COLOR_HIDDEN, "border_radius": LIGHT_BORDER_RADIUS, }, "CollapsableFrame": { "background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR, "color": COLLAPSABLEFRAME_TEXT_COLOR, "border_radius": LIGHT_BORDER_RADIUS, "border_color": 0x0, "border_width": 1, "font_size": LIGHT_FONT_SIZE, "padding": 6, "Tooltip": TOOLTIP_STYLE, }, "CollapsableFrame::groupFrame": { "background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "border_radius": BORDER_RADIUS * 2, "padding": 6, }, "CollapsableFrame::groupFrame:hovered": { "background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, }, "CollapsableFrame::groupFrame:pressed": { "background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, }, "CollapsableFrame::subFrame": { "background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, }, "CollapsableFrame::subFrame:hovered": { "background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR, }, "CollapsableFrame::subFrame:pressed": { "background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR, }, "CollapsableFrame.Header": { "font_size": LIGHT_FONT_SIZE, "background_color": FRAME_TEXT_COLOR, "color": FRAME_TEXT_COLOR, }, "CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR}, "CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR}, "ScrollingFrame": {"margin": 0, "padding": 3, "border_radius": LIGHT_BORDER_RADIUS}, "TreeView": { "background_color": 0xFFE0E0E0, "background_selected_color": 0x109D905C, "secondary_color": 0xFFACACAC, }, "TreeView.ScrollingFrame": {"background_color": 0xFFE0E0E0}, "TreeView.Header": {"color": 0xFFCCCCCC}, "TreeView.Header::background": { "background_color": 0xFF535354, "border_color": 0xFF707070, "border_width": 0.5, }, "TreeView.Header::columnname": {"margin": 3}, "TreeView.Image::object_icon_grey": {"color": 0x80FFFFFF}, "TreeView.Item": {"color": 0xFF535354, "font_size": 16}, "TreeView.Item::object_name": {"margin": 3}, "TreeView.Item::object_name_grey": {"color": 0xFFACACAC}, "TreeView.Item::object_name_missing": {"color": 0xFF6F72FF}, "TreeView.Item:selected": {"color": 0xFF2A2825}, "TreeView:selected": {"background_color": 0x409D905C}, "Label::vector_label": {"font_size": 14, "color": LABEL_VECTORLABEL_COLOR}, "Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT}, "Rectangle::mixed_overlay": { "border_radius": LIGHT_BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "border_width": 3, }, "Rectangle": { "border_radius": LIGHT_BORDER_RADIUS, "color": 0xFFC2C2C2, "background_color": 0xFFC2C2C2, }, # FIELD_BACKGROUND}, "Rectangle::xform_op:hovered": {"background_color": 0x0}, "Rectangle::xform_op": {"background_color": 0x0}, # text remove "Button::remove": {"background_color": FIELD_BACKGROUND, "margin": 0}, "Button::remove:hovered": {"background_color": FIELD_BACKGROUND}, "Button::options": {"background_color": 0x0, "margin": 0}, "Button.Image::options": {"image_url": f"{icons_path}/options.svg", "color": 0xFF989898}, "Button.Image::options:hovered": {"color": 0xFFC2C2C2}, "IconButton": {"margin": 0, "padding": 0, "background_color": 0x0}, "IconButton:hovered": {"background_color": 0x0}, "IconButton:checked": {"background_color": 0x0}, "IconButton:pressed": {"background_color": 0x0}, "IconButton.Image": {"color": 0xFFA8A8A8}, "IconButton.Image:hovered": {"color": 0xFF929292}, "IconButton.Image:pressed": {"color": 0xFFA4A4A4}, "IconButton.Image:checked": {"color": 0xFFFFFFFF}, "IconButton.Tooltip": {"color": 0xFF9E9E9E}, "IconButton.Image::OpenFolder": { "image_url": f"{icons_path}/open-folder.svg", "background_color": 0x0, "color": 0xFFA8A8A8, "tooltip": TOOLTIP_STYLE, }, "IconButton.Image::OpenConfig": { "image_url": f"{icons_path}/open-config.svg", "background_color": 0x0, "color": 0xFFA8A8A8, "tooltip": TOOLTIP_STYLE, }, "IconButton.Image::OpenLink": { "image_url": "resources/glyphs/link.svg", "background_color": 0x0, "color": 0xFFA8A8A8, "tooltip": TOOLTIP_STYLE, }, "IconButton.Image::OpenDocs": { "image_url": "resources/glyphs/docs.svg", "background_color": 0x0, "color": 0xFFA8A8A8, "tooltip": TOOLTIP_STYLE, }, "IconButton.Image::CopyToClipboard": { "image_url": "resources/glyphs/copy.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "IconButton.Image::Export": { "image_url": f"{icons_path}/export.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "IconButton.Image::Sync": { "image_url": "resources/glyphs/sync.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "IconButton.Image::Upload": { "image_url": "resources/glyphs/upload.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "IconButton.Image::FolderPicker": { "image_url": "resources/glyphs/folder.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4}, "ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B}, "ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6}, "ItemButton:hovered": {"background_color": 0xFF333333}, "ItemButton:pressed": {"background_color": 0xFF222222}, "Tooltip": TOOLTIP_STYLE, } else: LABEL_COLOR = 0xFF8F8E86 FIELD_BACKGROUND = 0xFF23211F FIELD_TEXT_COLOR = 0xFFD5D5D5 FIELD_TEXT_COLOR_READ_ONLY = 0xFF5C5C5C FIELD_TEXT_COLOR_HIDDEN = 0x01000000 FRAME_TEXT_COLOR = 0xFFCCCCCC WINDOW_BACKGROUND_COLOR = 0xFF444444 BUTTON_BACKGROUND_COLOR = 0xFF292929 BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778 BUTTON_LABEL_DISABLED_COLOR = 0xFF606060 LABEL_LABEL_COLOR = 0xFF9E9E9E LABEL_TITLE_COLOR = 0xFFAAAAAA LABEL_MIXED_COLOR = 0xFFE6B067 LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD COLORWIDGET_BORDER_COLOR = 0xFF1E1E1E COMBOBOX_HOVERED_BACKGROUND_COLOR = 0xFF33312F COLLAPSABLEFRAME_BORDER_COLOR = 0x0 COLLAPSABLEFRAME_BACKGROUND_COLOR = 0xFF343432 COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFF23211F COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFF343432 COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFF2E2E2B COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B style = { "Window": {"background_color": WINDOW_BACKGROUND_COLOR}, "Button": {"background_color": BUTTON_BACKGROUND_COLOR, "margin": 0, "padding": 3, "border_radius": 2}, "Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR}, "Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR}, "Button.Label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR}, "Field::models": { "background_color": FIELD_BACKGROUND, "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, }, "Field::models_mixed": { "background_color": FIELD_BACKGROUND, "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR_HIDDEN, "border_radius": BORDER_RADIUS, }, "Field::models_readonly": { "background_color": FIELD_BACKGROUND, "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR_READ_ONLY, "border_radius": BORDER_RADIUS, }, "Field::models_readonly_mixed": { "background_color": FIELD_BACKGROUND, "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR_HIDDEN, "border_radius": BORDER_RADIUS, }, "Label": {"font_size": FONT_SIZE, "color": LABEL_COLOR}, "Label::label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR}, "Label::label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR}, "Label::title": {"font_size": FONT_SIZE, "color": LABEL_TITLE_COLOR}, "Label::mixed_overlay": {"font_size": FONT_SIZE, "color": LABEL_MIXED_COLOR}, "Label::mixed_overlay_normal": {"font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR}, "Label::path_label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR}, "Label::stage_label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR}, "ComboBox::choices": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "background_color": FIELD_BACKGROUND, "secondary_color": FIELD_BACKGROUND, "secondary_selected_color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, }, "ComboBox::choices_mixed": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR_HIDDEN, "background_color": FIELD_BACKGROUND, "secondary_color": FIELD_BACKGROUND, "secondary_selected_color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, }, "ComboBox:hovered:choices": { "background_color": COMBOBOX_HOVERED_BACKGROUND_COLOR, "secondary_color": COMBOBOX_HOVERED_BACKGROUND_COLOR, }, "Slider": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": WINDOW_BACKGROUND_COLOR, "draw_mode": ui.SliderDrawMode.FILLED, }, "Slider::value": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": WINDOW_BACKGROUND_COLOR, }, "Slider::value_mixed": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR_HIDDEN, "border_radius": BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": WINDOW_BACKGROUND_COLOR, }, "Slider::multivalue": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": WINDOW_BACKGROUND_COLOR, "draw_mode": ui.SliderDrawMode.HANDLE, }, "Slider::multivalue_mixed": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": WINDOW_BACKGROUND_COLOR, "draw_mode": ui.SliderDrawMode.HANDLE, }, "CheckBox::greenCheck": { "font_size": 12, "background_color": KIT_GREEN_CHECKBOX, "color": FIELD_BACKGROUND, "border_radius": BORDER_RADIUS, }, "CheckBox::greenCheck_mixed": { "font_size": 12, "background_color": KIT_GREEN_CHECKBOX, "color": FIELD_TEXT_COLOR_HIDDEN, "border_radius": BORDER_RADIUS, }, "CollapsableFrame": { "background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR, "border_radius": BORDER_RADIUS * 2, "border_color": COLLAPSABLEFRAME_BORDER_COLOR, "border_width": 1, "padding": 6, }, "CollapsableFrame::groupFrame": { "background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "border_radius": BORDER_RADIUS * 2, "padding": 6, }, "CollapsableFrame::groupFrame:hovered": { "background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, }, "CollapsableFrame::groupFrame:pressed": { "background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, }, "CollapsableFrame::subFrame": { "background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, }, "CollapsableFrame::subFrame:hovered": { "background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR, }, "CollapsableFrame::subFrame:pressed": { "background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR, }, "CollapsableFrame.Header": { "font_size": FONT_SIZE, "background_color": FRAME_TEXT_COLOR, "color": FRAME_TEXT_COLOR, }, "CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR}, "CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR}, "ScrollingFrame": {"margin": 0, "padding": 3, "border_radius": BORDER_RADIUS}, "TreeView": { "background_color": 0xFF23211F, "background_selected_color": 0x664F4D43, "secondary_color": 0xFF403B3B, }, "TreeView.ScrollingFrame": {"background_color": 0xFF23211F}, "TreeView.Header": {"background_color": 0xFF343432, "color": 0xFFCCCCCC, "font_size": 12}, "TreeView.Image::object_icon_grey": {"color": 0x80FFFFFF}, "TreeView.Image:disabled": {"color": 0x60FFFFFF}, "TreeView.Item": {"color": 0xFF8A8777}, "TreeView.Item:disabled": {"color": 0x608A8777}, "TreeView.Item::object_name_grey": {"color": 0xFF4D4B42}, "TreeView.Item::object_name_missing": {"color": 0xFF6F72FF}, "TreeView.Item:selected": {"color": 0xFF23211F}, "TreeView:selected": {"background_color": 0xFF8A8777}, "ColorWidget": { "border_radius": BORDER_RADIUS, "border_color": COLORWIDGET_BORDER_COLOR, "border_width": 0.5, }, "Label::vector_label": {"font_size": 16, "color": LABEL_VECTORLABEL_COLOR}, "PlotLabel::X": {"color": 0xFF1515EA, "background_color": 0x0}, "PlotLabel::Y": {"color": 0xFF5FC054, "background_color": 0x0}, "PlotLabel::Z": {"color": 0xFFC5822A, "background_color": 0x0}, "PlotLabel::W": {"color": 0xFFAA5555, "background_color": 0x0}, "Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT}, "Rectangle::mixed_overlay": { "border_radius": BORDER_RADIUS, "background_color": LABEL_MIXED_COLOR, "border_width": 3, }, "Rectangle": { "border_radius": BORDER_RADIUS, "background_color": FIELD_TEXT_COLOR_READ_ONLY, }, # FIELD_BACKGROUND}, "Rectangle::xform_op:hovered": {"background_color": 0xFF444444}, "Rectangle::xform_op": {"background_color": 0xFF333333}, # text remove "Button::remove": {"background_color": FIELD_BACKGROUND, "margin": 0}, "Button::remove:hovered": {"background_color": FIELD_BACKGROUND}, "Button::options": {"background_color": 0x0, "margin": 0}, "Button.Image::options": {"image_url": f"{icons_path}/options.svg", "color": 0xFF989898}, "Button.Image::options:hovered": {"color": 0xFFC2C2C2}, "IconButton": {"margin": 0, "padding": 0, "background_color": 0x0}, "IconButton:hovered": {"background_color": 0x0}, "IconButton:checked": {"background_color": 0x0}, "IconButton:pressed": {"background_color": 0x0}, "IconButton.Image": {"color": 0xFFA8A8A8}, "IconButton.Image:hovered": {"color": 0xFFC2C2C2}, "IconButton.Image:pressed": {"color": 0xFFA4A4A4}, "IconButton.Image:checked": {"color": 0xFFFFFFFF}, "IconButton.Tooltip": {"color": 0xFF9E9E9E}, "IconButton.Image::OpenFolder": { "image_url": f"{icons_path}/open-folder.svg", "background_color": 0x0, "color": 0xFFA8A8A8, "tooltip": TOOLTIP_STYLE, }, "IconButton.Image::OpenConfig": { "tooltip": TOOLTIP_STYLE, "image_url": f"{icons_path}/open-config.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "IconButton.Image::OpenLink": { "image_url": "resources/glyphs/link.svg", "background_color": 0x0, "color": 0xFFA8A8A8, "tooltip": TOOLTIP_STYLE, }, "IconButton.Image::OpenDocs": { "image_url": "resources/glyphs/docs.svg", "background_color": 0x0, "color": 0xFFA8A8A8, "tooltip": TOOLTIP_STYLE, }, "IconButton.Image::CopyToClipboard": { "image_url": "resources/glyphs/copy.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "IconButton.Image::Export": { "image_url": f"{icons_path}/export.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "IconButton.Image::Sync": { "image_url": "resources/glyphs/sync.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "IconButton.Image::Upload": { "image_url": "resources/glyphs/upload.svg", "background_color": 0x0, "color": 0xFFA8A8A8, }, "IconButton.Image::FolderPicker": { "image_url": "resources/glyphs/folder.svg", "background_color": 0x0, "color": 0xFF929292, }, "ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4}, "ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B}, "ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6}, "ItemButton:hovered": {"background_color": 0xFF333333}, "ItemButton:pressed": {"background_color": 0xFF222222}, "Tooltip": TOOLTIP_STYLE, } return style
31,271
Python
45.884558
116
0.53903
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/ui/__init__.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .menu import * from .style import * from .ui_utils import *
745
Python
38.263156
98
0.765101
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/ui/menu.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ext from omni.kit.menu.utils import MenuItemDescription def make_menu_item_description(ext_id: str, name: str, onclick_fun, action_name: str = "") -> None: """Easily replace the onclick_fn with onclick_action when creating a menu description Args: ext_id (str): The extension you are adding the menu item to. name (str): Name of the menu item displayed in UI. onclick_fun (Function): The function to run when clicking the menu item. action_name (str): name for the action, in case ext_id+name don't make a unique string Note: ext_id + name + action_name must concatenate to a unique identifier. """ # TODO, fix errors when reloading extensions # action_unique = f'{ext_id.replace(" ", "_")}{name.replace(" ", "_")}{action_name.replace(" ", "_")}' # action_registry = omni.kit.actions.core.get_action_registry() # action_registry.register_action(ext_id, action_unique, onclick_fun) return MenuItemDescription(name=name, onclick_fn=onclick_fun)
1,716
Python
44.184209
106
0.716783
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/ui/ui_utils.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import os import subprocess import sys from cmath import inf import carb.settings import omni.appwindow import omni.ext import omni.ui as ui from omni.kit.window.extensions import SimpleCheckBox from omni.kit.window.filepicker import FilePickerDialog from omni.kit.window.property.templates import LABEL_HEIGHT, LABEL_WIDTH # from .callbacks import on_copy_to_clipboard, on_docs_link_clicked, on_open_folder_clicked, on_open_IDE_clicked from .style import BUTTON_WIDTH, COLOR_W, COLOR_X, COLOR_Y, COLOR_Z, get_style def btn_builder(label="", type="button", text="button", tooltip="", on_clicked_fn=None): """Creates a stylized button. Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "button". text (str, optional): Text rendered on the button. Defaults to "button". tooltip (str, optional): Tooltip to display over the Label. Defaults to "". on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None. Returns: ui.Button: Button """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) btn = ui.Button( text.upper(), name="Button", width=BUTTON_WIDTH, clicked_fn=on_clicked_fn, style=get_style(), alignment=ui.Alignment.LEFT_CENTER, ) ui.Spacer(width=5) add_line_rect_flourish(True) # ui.Spacer(width=ui.Fraction(1)) # ui.Spacer(width=10) # with ui.Frame(width=0): # with ui.VStack(): # with ui.Placer(offset_x=0, offset_y=7): # ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER) # ui.Spacer(width=5) return btn def state_btn_builder( label="", type="state_button", a_text="STATE A", b_text="STATE B", tooltip="", on_clicked_fn=None ): """Creates a State Change Button that changes text when pressed. Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "button". a_text (str, optional): Text rendered on the button for State A. Defaults to "STATE A". b_text (str, optional): Text rendered on the button for State B. Defaults to "STATE B". tooltip (str, optional): Tooltip to display over the Label. Defaults to "". on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None. """ def toggle(): if btn.text == a_text.upper(): btn.text = b_text.upper() on_clicked_fn(True) else: btn.text = a_text.upper() on_clicked_fn(False) with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) btn = ui.Button( a_text.upper(), name="Button", width=BUTTON_WIDTH, clicked_fn=toggle, style=get_style(), alignment=ui.Alignment.LEFT_CENTER, ) ui.Spacer(width=5) # add_line_rect_flourish(False) ui.Spacer(width=ui.Fraction(1)) ui.Spacer(width=10) with ui.Frame(width=0): with ui.VStack(): with ui.Placer(offset_x=0, offset_y=7): ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER) ui.Spacer(width=5) return btn def cb_builder(label="", type="checkbox", default_val=False, tooltip="", on_clicked_fn=None): """Creates a Stylized Checkbox Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "checkbox". default_val (bool, optional): Checked is True, Unchecked is False. Defaults to False. tooltip (str, optional): Tooltip to display over the Label. Defaults to "". on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None. Returns: ui.SimpleBoolModel: model """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) model = ui.SimpleBoolModel() callable = on_clicked_fn if callable is None: callable = lambda x: None SimpleCheckBox(default_val, callable, model=model) add_line_rect_flourish() return model def multi_btn_builder( label="", type="multi_button", count=2, text=["button", "button"], tooltip=["", "", ""], on_clicked_fn=[None, None] ): """Creates a Row of Stylized Buttons Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "multi_button". count (int, optional): Number of UI elements to create. Defaults to 2. text (list, optional): List of text rendered on the UI elements. Defaults to ["button", "button"]. tooltip (list, optional): List of tooltips to display over the UI elements. Defaults to ["", "", ""]. on_clicked_fn (list, optional): List of call-backs function when clicked. Defaults to [None, None]. Returns: list(ui.Button): List of Buttons """ btns = [] with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0])) for i in range(count): btn = ui.Button( text[i].upper(), name="Button", width=BUTTON_WIDTH, clicked_fn=on_clicked_fn[i], tooltip=format_tt(tooltip[i + 1]), style=get_style(), alignment=ui.Alignment.LEFT_CENTER, ) btns.append(btn) if i < count: ui.Spacer(width=5) add_line_rect_flourish() return btns def multi_cb_builder( label="", type="multi_checkbox", count=2, text=[" ", " "], default_val=[False, False], tooltip=["", "", ""], on_clicked_fn=[None, None], ): """Creates a Row of Stylized Checkboxes. Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "multi_checkbox". count (int, optional): Number of UI elements to create. Defaults to 2. text (list, optional): List of text rendered on the UI elements. Defaults to [" ", " "]. default_val (list, optional): List of default values. Checked is True, Unchecked is False. Defaults to [False, False]. tooltip (list, optional): List of tooltips to display over the UI elements. Defaults to ["", "", ""]. on_clicked_fn (list, optional): List of call-backs function when clicked. Defaults to [None, None]. Returns: list(ui.SimpleBoolModel): List of models """ cbs = [] with ui.HStack(): ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0])) for i in range(count): cb = ui.SimpleBoolModel(default_value=default_val[i]) callable = on_clicked_fn[i] if callable is None: callable = lambda x: None SimpleCheckBox(default_val[i], callable, model=cb) ui.Label( text[i], width=BUTTON_WIDTH / 2, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[i + 1]) ) if i < count - 1: ui.Spacer(width=5) cbs.append(cb) add_line_rect_flourish() return cbs def str_builder( label="", type="stringfield", default_val=" ", tooltip="", on_clicked_fn=None, use_folder_picker=False, read_only=False, item_filter_fn=None, bookmark_label=None, bookmark_path=None, folder_dialog_title="Select Output Folder", folder_button_title="Select Folder", ): """Creates a Stylized Stringfield Widget Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "stringfield". default_val (str, optional): Text to initialize in Stringfield. Defaults to " ". tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "". use_folder_picker (bool, optional): Add a folder picker button to the right. Defaults to False. read_only (bool, optional): Prevents editing. Defaults to False. item_filter_fn (Callable, optional): filter function to pass to the FilePicker bookmark_label (str, optional): bookmark label to pass to the FilePicker bookmark_path (str, optional): bookmark path to pass to the FilePicker Returns: AbstractValueModel: model of Stringfield """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) str_field = ui.StringField( name="StringField", width=ui.Fraction(1), height=0, alignment=ui.Alignment.LEFT_CENTER, read_only=read_only ).model str_field.set_value(default_val) if use_folder_picker: def update_field(filename, path): if filename == "": val = path elif filename[0] != "/" and path[-1] != "/": val = path + "/" + filename elif filename[0] == "/" and path[-1] == "/": val = path + filename[1:] else: val = path + filename str_field.set_value(val) add_folder_picker_icon( update_field, item_filter_fn, bookmark_label, bookmark_path, dialog_title=folder_dialog_title, button_title=folder_button_title, ) else: add_line_rect_flourish(False) return str_field def int_builder(label="", type="intfield", default_val=0, tooltip="", min=sys.maxsize * -1, max=sys.maxsize): """Creates a Stylized Intfield Widget Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "intfield". default_val (int, optional): Default Value of UI element. Defaults to 0. tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "". min (int, optional): Minimum limit for int field. Defaults to sys.maxsize * -1 max (int, optional): Maximum limit for int field. Defaults to sys.maxsize * 1 Returns: AbstractValueModel: model """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) int_field = ui.IntDrag( name="Field", height=LABEL_HEIGHT, min=min, max=max, alignment=ui.Alignment.LEFT_CENTER ).model int_field.set_value(default_val) add_line_rect_flourish(False) return int_field def float_builder(label="", type="floatfield", default_val=0, tooltip="", min=-inf, max=inf, step=0.1, format="%.2f"): """Creates a Stylized Floatfield Widget Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "floatfield". default_val (int, optional): Default Value of UI element. Defaults to 0. tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "". Returns: AbstractValueModel: model """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) float_field = ui.FloatDrag( name="FloatField", width=ui.Fraction(1), height=0, alignment=ui.Alignment.LEFT_CENTER, min=min, max=max, step=step, format=format, ).model float_field.set_value(default_val) add_line_rect_flourish(False) return float_field def combo_cb_str_builder( label="", type="checkbox_stringfield", default_val=[False, " "], tooltip="", on_clicked_fn=lambda x: None, use_folder_picker=False, read_only=False, folder_dialog_title="Select Output Folder", folder_button_title="Select Folder", ): """Creates a Stylized Checkbox + Stringfield Widget Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "checkbox_stringfield". default_val (str, optional): Text to initialize in Stringfield. Defaults to [False, " "]. tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "". use_folder_picker (bool, optional): Add a folder picker button to the right. Defaults to False. read_only (bool, optional): Prevents editing. Defaults to False. Returns: Tuple(ui.SimpleBoolModel, AbstractValueModel): (cb_model, str_field_model) """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) cb = ui.SimpleBoolModel(default_value=default_val[0]) SimpleCheckBox(default_val[0], on_clicked_fn, model=cb) str_field = ui.StringField( name="StringField", width=ui.Fraction(1), height=0, alignment=ui.Alignment.LEFT_CENTER, read_only=read_only ).model str_field.set_value(default_val[1]) if use_folder_picker: def update_field(val): str_field.set_value(val) add_folder_picker_icon(update_field, dialog_title=folder_dialog_title, button_title=folder_button_title) else: add_line_rect_flourish(False) return cb, str_field def dropdown_builder( label="", type="dropdown", default_val=0, items=["Option 1", "Option 2", "Option 3"], tooltip="", on_clicked_fn=None ): """Creates a Stylized Dropdown Combobox Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "dropdown". default_val (int, optional): Default index of dropdown items. Defaults to 0. items (list, optional): List of items for dropdown box. Defaults to ["Option 1", "Option 2", "Option 3"]. tooltip (str, optional): Tooltip to display over the Label. Defaults to "". on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None. Returns: AbstractItemModel: model """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) combo_box = ui.ComboBox( default_val, *items, name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER ).model add_line_rect_flourish(False) def on_clicked_wrapper(model, val): on_clicked_fn(items[model.get_item_value_model().as_int]) if on_clicked_fn is not None: combo_box.add_item_changed_fn(on_clicked_wrapper) return combo_box def combo_intfield_slider_builder( label="", type="intfield_stringfield", default_val=0.5, min=0, max=1, step=0.01, tooltip=["", ""] ): """Creates a Stylized IntField + Stringfield Widget Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "intfield_stringfield". default_val (float, optional): Default Value. Defaults to 0.5. min (int, optional): Minimum Value. Defaults to 0. max (int, optional): Maximum Value. Defaults to 1. step (float, optional): Step. Defaults to 0.01. tooltip (list, optional): List of tooltips. Defaults to ["", ""]. Returns: Tuple(AbstractValueModel, IntSlider): (flt_field_model, flt_slider_model) """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0])) ff = ui.IntDrag( name="Field", width=BUTTON_WIDTH / 2, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[1]) ).model ff.set_value(default_val) ui.Spacer(width=5) fs = ui.IntSlider( width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER, min=min, max=max, step=step, model=ff ) add_line_rect_flourish(False) return ff, fs def combo_floatfield_slider_builder( label="", type="floatfield_stringfield", default_val=0.5, min=0, max=1, step=0.01, tooltip=["", ""] ): """Creates a Stylized FloatField + FloatSlider Widget Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "floatfield_stringfield". default_val (float, optional): Default Value. Defaults to 0.5. min (int, optional): Minimum Value. Defaults to 0. max (int, optional): Maximum Value. Defaults to 1. step (float, optional): Step. Defaults to 0.01. tooltip (list, optional): List of tooltips. Defaults to ["", ""]. Returns: Tuple(AbstractValueModel, IntSlider): (flt_field_model, flt_slider_model) """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0])) ff = ui.FloatField( name="Field", width=BUTTON_WIDTH / 2, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[1]) ).model ff.set_value(default_val) ui.Spacer(width=5) fs = ui.FloatSlider( width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER, min=min, max=max, step=step, model=ff ) add_line_rect_flourish(False) return ff, fs def multi_dropdown_builder( label="", type="multi_dropdown", count=2, default_val=[0, 0], items=[["Option 1", "Option 2", "Option 3"], ["Option A", "Option B", "Option C"]], tooltip="", on_clicked_fn=[None, None], ): """Creates a Stylized Multi-Dropdown Combobox Returns: AbstractItemModel: model Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "multi_dropdown". count (int, optional): Number of UI elements. Defaults to 2. default_val (list(int), optional): List of default indices of dropdown items. Defaults to 0.. Defaults to [0, 0]. items (list(list), optional): List of list of items for dropdown boxes. Defaults to [["Option 1", "Option 2", "Option 3"], ["Option A", "Option B", "Option C"]]. tooltip (str, optional): Tooltip to display over the Label. Defaults to "". on_clicked_fn (list(Callable), optional): List of call-back function when clicked. Defaults to [None, None]. Returns: list(AbstractItemModel): list(models) """ elems = [] with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) for i in range(count): elem = ui.ComboBox( default_val[i], *items[i], name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER ) def on_clicked_wrapper(model, val, index): on_clicked_fn[index](items[index][model.get_item_value_model().as_int]) elem.model.add_item_changed_fn(lambda m, v, index=i: on_clicked_wrapper(m, v, index)) elems.append(elem) if i < count - 1: ui.Spacer(width=5) add_line_rect_flourish(False) return elems def combo_cb_dropdown_builder( label="", type="checkbox_dropdown", default_val=[False, 0], items=["Option 1", "Option 2", "Option 3"], tooltip="", on_clicked_fn=[lambda x: None, None], ): """Creates a Stylized Dropdown Combobox with an Enable Checkbox Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "checkbox_dropdown". default_val (list, optional): list(cb_default, dropdown_default). Defaults to [False, 0]. items (list, optional): List of items for dropdown box. Defaults to ["Option 1", "Option 2", "Option 3"]. tooltip (str, optional): Tooltip to display over the Label. Defaults to "". on_clicked_fn (list, optional): List of callback functions. Defaults to [lambda x: None, None]. Returns: Tuple(ui.SimpleBoolModel, ui.ComboBox): (cb_model, combobox) """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) cb = ui.SimpleBoolModel(default_value=default_val[0]) SimpleCheckBox(default_val[0], on_clicked_fn[0], model=cb) combo_box = ui.ComboBox( default_val[1], *items, name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER ) def on_clicked_wrapper(model, val): on_clicked_fn[1](items[model.get_item_value_model().as_int]) combo_box.model.add_item_changed_fn(on_clicked_wrapper) add_line_rect_flourish(False) return cb, combo_box def scrolling_frame_builder(label="", type="scrolling_frame", default_val="No Data", tooltip=""): """Creates a Labeled Scrolling Frame with CopyToClipboard button Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "scrolling_frame". default_val (str, optional): Default Text. Defaults to "No Data". tooltip (str, optional): Tooltip to display over the Label. Defaults to "". Returns: ui.Label: label """ with ui.VStack(style=get_style(), spacing=5): with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip)) with ui.ScrollingFrame( height=LABEL_HEIGHT * 5, style_type_name_override="ScrollingFrame", alignment=ui.Alignment.LEFT_TOP, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): text = ui.Label( default_val, style_type_name_override="Label::label", word_wrap=True, alignment=ui.Alignment.LEFT_TOP, ) with ui.Frame(width=0, tooltip="Copy To Clipboard"): ui.Button( name="IconButton", width=20, height=20, clicked_fn=lambda: on_copy_to_clipboard(to_copy=text.text), style=get_style()["IconButton.Image::CopyToClipboard"], alignment=ui.Alignment.RIGHT_TOP, ) return text def combo_cb_scrolling_frame_builder( label="", type="cb_scrolling_frame", default_val=[False, "No Data"], tooltip="", on_clicked_fn=lambda x: None ): """Creates a Labeled, Checkbox-enabled Scrolling Frame with CopyToClipboard button Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "cb_scrolling_frame". default_val (list, optional): List of Checkbox and Frame Defaults. Defaults to [False, "No Data"]. tooltip (str, optional): Tooltip to display over the Label. Defaults to "". on_clicked_fn (Callable, optional): Callback function when clicked. Defaults to lambda x : None. Returns: list(SimpleBoolModel, ui.Label): (model, label) """ with ui.VStack(style=get_style(), spacing=5): with ui.HStack(): ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip)) with ui.VStack(width=0): cb = ui.SimpleBoolModel(default_value=default_val[0]) SimpleCheckBox(default_val[0], on_clicked_fn, model=cb) ui.Spacer(height=18 * 4) with ui.ScrollingFrame( height=18 * 5, style_type_name_override="ScrollingFrame", alignment=ui.Alignment.LEFT_TOP, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): text = ui.Label( default_val[1], style_type_name_override="Label::label", word_wrap=True, alignment=ui.Alignment.LEFT_TOP, ) with ui.Frame(width=0, tooltip="Copy to Clipboard"): ui.Button( name="IconButton", width=20, height=20, clicked_fn=lambda: on_copy_to_clipboard(to_copy=text.text), style=get_style()["IconButton.Image::CopyToClipboard"], alignment=ui.Alignment.RIGHT_TOP, ) return cb, text def xyz_builder( label="", tooltip="", axis_count=3, default_val=[0.0, 0.0, 0.0, 0.0], min=float("-inf"), max=float("inf"), step=0.001, on_value_changed_fn=[None, None, None, None], ): """[summary] Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "". axis_count (int, optional): Number of Axes to Display. Max 4. Defaults to 3. default_val (list, optional): List of default values. Defaults to [0.0, 0.0, 0.0, 0.0]. min (float, optional): Minimum Float Value. Defaults to float("-inf"). max (float, optional): Maximum Float Value. Defaults to float("inf"). step (float, optional): Step. Defaults to 0.001. on_value_changed_fn (list, optional): List of callback functions for each axes. Defaults to [None, None, None, None]. Returns: list(AbstractValueModel): list(model) """ # These styles & colors are taken from omni.kit.property.transform_builder.py _create_multi_float_drag_matrix_with_labels if axis_count <= 0 or axis_count > 4: import builtins carb.log_warn("Invalid axis_count: must be in range 1 to 4. Clamping to default range.") axis_count = builtins.max(builtins.min(axis_count, 4), 1) field_labels = [("X", COLOR_X), ("Y", COLOR_Y), ("Z", COLOR_Z), ("W", COLOR_W)] field_tooltips = ["X Value", "Y Value", "Z Value", "W Value"] RECT_WIDTH = 13 # SPACING = 4 val_models = [None] * axis_count with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) with ui.ZStack(): with ui.HStack(): ui.Spacer(width=RECT_WIDTH) for i in range(axis_count): val_models[i] = ui.FloatDrag( name="Field", height=LABEL_HEIGHT, min=min, max=max, step=step, alignment=ui.Alignment.LEFT_CENTER, tooltip=field_tooltips[i], ).model val_models[i].set_value(default_val[i]) if on_value_changed_fn[i] is not None: val_models[i].add_value_changed_fn(on_value_changed_fn[i]) if i != axis_count - 1: ui.Spacer(width=19) with ui.HStack(): for i in range(axis_count): if i != 0: ui.Spacer() # width=BUTTON_WIDTH - 1) field_label = field_labels[i] with ui.ZStack(width=RECT_WIDTH + 2 * i): ui.Rectangle(name="vector_label", style={"background_color": field_label[1]}) ui.Label(field_label[0], name="vector_label", alignment=ui.Alignment.CENTER) ui.Spacer() add_line_rect_flourish(False) return val_models def color_picker_builder(label="", type="color_picker", default_val=[1.0, 1.0, 1.0, 1.0], tooltip="Color Picker"): """Creates a Color Picker Widget Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "color_picker". default_val (list, optional): List of (R,G,B,A) default values. Defaults to [1.0, 1.0, 1.0, 1.0]. tooltip (str, optional): Tooltip to display over the Label. Defaults to "Color Picker". Returns: AbstractItemModel: ui.ColorWidget.model """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip)) model = ui.ColorWidget(*default_val, width=BUTTON_WIDTH).model ui.Spacer(width=5) add_line_rect_flourish() return model def progress_bar_builder(label="", type="progress_bar", default_val=0, tooltip="Progress"): """Creates a Progress Bar Widget Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "progress_bar". default_val (int, optional): Starting Value. Defaults to 0. tooltip (str, optional): Tooltip to display over the Label. Defaults to "Progress". Returns: AbstractValueModel: ui.ProgressBar().model """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER) model = ui.ProgressBar().model model.set_value(default_val) add_line_rect_flourish(False) return model def plot_builder(label="", data=None, min=-1, max=1, type=ui.Type.LINE, value_stride=1, color=None, tooltip=""): """Creates a stylized static plot Args: label (str, optional): Label to the left of the UI element. Defaults to "". data (list(float), optional): Data to plot. Defaults to None. min (int, optional): Minimum Y Value. Defaults to -1. max (int, optional): Maximum Y Value. Defaults to 1. type (ui.Type, optional): Plot Type. Defaults to ui.Type.LINE. value_stride (int, optional): Width of plot stride. Defaults to 1. color (int, optional): Plot color. Defaults to None. tooltip (str, optional): Tooltip to display over the Label. Defaults to "". Returns: ui.Plot: plot """ with ui.VStack(spacing=5): with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip)) plot_height = LABEL_HEIGHT * 2 + 13 plot_width = ui.Fraction(1) with ui.ZStack(): ui.Rectangle(width=plot_width, height=plot_height) if not color: color = 0xFFDDDDDD plot = ui.Plot( type, min, max, *data, value_stride=value_stride, width=plot_width, height=plot_height, style={"color": color, "background_color": 0x0}, ) def update_min(model): plot.scale_min = model.as_float def update_max(model): plot.scale_max = model.as_float ui.Spacer(width=5) with ui.Frame(width=0): with ui.VStack(spacing=5): max_model = ui.FloatDrag( name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max" ).model max_model.set_value(max) min_model = ui.FloatDrag( name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min" ).model min_model.set_value(min) min_model.add_value_changed_fn(update_min) max_model.add_value_changed_fn(update_max) ui.Spacer(width=20) add_separator() return plot def xyz_plot_builder(label="", data=[], min=-1, max=1, tooltip=""): """Creates a stylized static XYZ plot Args: label (str, optional): Label to the left of the UI element. Defaults to "". data (list(float), optional): Data to plot. Defaults to []. min (int, optional): Minimum Y Value. Defaults to -1. max (int, optional): Maximum Y Value. Defaults to "". tooltip (str, optional): Tooltip to display over the Label.. Defaults to "". Returns: list(ui.Plot): list(x_plot, y_plot, z_plot) """ with ui.VStack(spacing=5): with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip)) plot_height = LABEL_HEIGHT * 2 + 13 plot_width = ui.Fraction(1) with ui.ZStack(): ui.Rectangle(width=plot_width, height=plot_height) plot_0 = ui.Plot( ui.Type.LINE, min, max, *data[0], width=plot_width, height=plot_height, style=get_style()["PlotLabel::X"], ) plot_1 = ui.Plot( ui.Type.LINE, min, max, *data[1], width=plot_width, height=plot_height, style=get_style()["PlotLabel::Y"], ) plot_2 = ui.Plot( ui.Type.LINE, min, max, *data[2], width=plot_width, height=plot_height, style=get_style()["PlotLabel::Z"], ) def update_min(model): plot_0.scale_min = model.as_float plot_1.scale_min = model.as_float plot_2.scale_min = model.as_float def update_max(model): plot_0.scale_max = model.as_float plot_1.scale_max = model.as_float plot_2.scale_max = model.as_float ui.Spacer(width=5) with ui.Frame(width=0): with ui.VStack(spacing=5): max_model = ui.FloatDrag( name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max" ).model max_model.set_value(max) min_model = ui.FloatDrag( name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min" ).model min_model.set_value(min) min_model.add_value_changed_fn(update_min) max_model.add_value_changed_fn(update_max) ui.Spacer(width=20) add_separator() return [plot_0, plot_1, plot_2] def combo_cb_plot_builder( label="", default_val=False, on_clicked_fn=lambda x: None, data=None, min=-1, max=1, type=ui.Type.LINE, value_stride=1, color=None, tooltip="", ): """Creates a Checkbox-Enabled dyanamic plot Args: label (str, optional): Label to the left of the UI element. Defaults to "". default_val (bool, optional): Checkbox default. Defaults to False. on_clicked_fn (Callable, optional): Checkbox Callback function. Defaults to lambda x: None. data (list(), optional): Data to plat. Defaults to None. min (int, optional): Min Y Value. Defaults to -1. max (int, optional): Max Y Value. Defaults to 1. type (ui.Type, optional): Plot Type. Defaults to ui.Type.LINE. value_stride (int, optional): Width of plot stride. Defaults to 1. color (int, optional): Plot color. Defaults to None. tooltip (str, optional): Tooltip to display over the Label. Defaults to "". Returns: list(SimpleBoolModel, ui.Plot): (cb_model, plot) """ with ui.VStack(spacing=5): with ui.HStack(): # Label ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip)) # Checkbox with ui.Frame(width=0): with ui.Placer(offset_x=-10, offset_y=0): with ui.VStack(): SimpleCheckBox(default_val, on_clicked_fn) ui.Spacer(height=ui.Fraction(1)) ui.Spacer() # Plot plot_height = LABEL_HEIGHT * 2 + 13 plot_width = ui.Fraction(1) with ui.ZStack(): ui.Rectangle(width=plot_width, height=plot_height) if not color: color = 0xFFDDDDDD plot = ui.Plot( type, min, max, *data, value_stride=value_stride, width=plot_width, height=plot_height, style={"color": color, "background_color": 0x0}, ) # Min/Max Helpers def update_min(model): plot.scale_min = model.as_float def update_max(model): plot.scale_max = model.as_float ui.Spacer(width=5) with ui.Frame(width=0): with ui.VStack(spacing=5): # Min/Max Fields max_model = ui.FloatDrag( name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max" ).model max_model.set_value(max) min_model = ui.FloatDrag( name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min" ).model min_model.set_value(min) min_model.add_value_changed_fn(update_min) max_model.add_value_changed_fn(update_max) ui.Spacer(width=20) with ui.HStack(): ui.Spacer(width=LABEL_WIDTH + 29) # Current Value Field (disabled by default) val_model = ui.FloatDrag( name="Field", width=BUTTON_WIDTH, height=LABEL_HEIGHT, enabled=False, alignment=ui.Alignment.LEFT_CENTER, tooltip="Value", ).model add_separator() return plot, val_model def combo_cb_xyz_plot_builder( label="", default_val=False, on_clicked_fn=lambda x: None, data=[], min=-1, max=1, type=ui.Type.LINE, value_stride=1, tooltip="", ): """[summary] Args: label (str, optional): Label to the left of the UI element. Defaults to "". default_val (bool, optional): Checkbox default. Defaults to False. on_clicked_fn (Callable, optional): Checkbox Callback function. Defaults to lambda x: None. data list(), optional): Data to plat. Defaults to None. min (int, optional): Min Y Value. Defaults to -1. max (int, optional): Max Y Value. Defaults to 1. type (ui.Type, optional): Plot Type. Defaults to ui.Type.LINE. value_stride (int, optional): Width of plot stride. Defaults to 1. tooltip (str, optional): Tooltip to display over the Label. Defaults to "". Returns: Tuple(list(ui.Plot), list(AbstractValueModel)): ([plot_0, plot_1, plot_2], [val_model_x, val_model_y, val_model_z]) """ with ui.VStack(spacing=5): with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip)) # Checkbox with ui.Frame(width=0): with ui.Placer(offset_x=-10, offset_y=0): with ui.VStack(): SimpleCheckBox(default_val, on_clicked_fn) ui.Spacer(height=ui.Fraction(1)) ui.Spacer() # Plots plot_height = LABEL_HEIGHT * 2 + 13 plot_width = ui.Fraction(1) with ui.ZStack(): ui.Rectangle(width=plot_width, height=plot_height) plot_0 = ui.Plot( type, min, max, *data[0], value_stride=value_stride, width=plot_width, height=plot_height, style=get_style()["PlotLabel::X"], ) plot_1 = ui.Plot( type, min, max, *data[1], value_stride=value_stride, width=plot_width, height=plot_height, style=get_style()["PlotLabel::Y"], ) plot_2 = ui.Plot( type, min, max, *data[2], value_stride=value_stride, width=plot_width, height=plot_height, style=get_style()["PlotLabel::Z"], ) def update_min(model): plot_0.scale_min = model.as_float plot_1.scale_min = model.as_float plot_2.scale_min = model.as_float def update_max(model): plot_0.scale_max = model.as_float plot_1.scale_max = model.as_float plot_2.scale_max = model.as_float ui.Spacer(width=5) with ui.Frame(width=0): with ui.VStack(spacing=5): max_model = ui.FloatDrag( name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max" ).model max_model.set_value(max) min_model = ui.FloatDrag( name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min" ).model min_model.set_value(min) min_model.add_value_changed_fn(update_min) max_model.add_value_changed_fn(update_max) ui.Spacer(width=20) # with ui.HStack(): # ui.Spacer(width=40) # val_models = xyz_builder()#**{"args":args}) field_labels = [("X", COLOR_X), ("Y", COLOR_Y), ("Z", COLOR_Z), ("W", COLOR_W)] RECT_WIDTH = 13 # SPACING = 4 with ui.HStack(): ui.Spacer(width=LABEL_WIDTH + 29) with ui.ZStack(): with ui.HStack(): ui.Spacer(width=RECT_WIDTH) # value_widget = ui.MultiFloatDragField( # *args, name="multivalue", min=min, max=max, step=step, h_spacing=RECT_WIDTH + SPACING, v_spacing=2 # ).model val_model_x = ui.FloatDrag( name="Field", width=BUTTON_WIDTH - 5, height=LABEL_HEIGHT, enabled=False, alignment=ui.Alignment.LEFT_CENTER, tooltip="X Value", ).model ui.Spacer(width=19) val_model_y = ui.FloatDrag( name="Field", width=BUTTON_WIDTH - 5, height=LABEL_HEIGHT, enabled=False, alignment=ui.Alignment.LEFT_CENTER, tooltip="Y Value", ).model ui.Spacer(width=19) val_model_z = ui.FloatDrag( name="Field", width=BUTTON_WIDTH - 5, height=LABEL_HEIGHT, enabled=False, alignment=ui.Alignment.LEFT_CENTER, tooltip="Z Value", ).model with ui.HStack(): for i in range(3): if i != 0: ui.Spacer(width=BUTTON_WIDTH - 1) field_label = field_labels[i] with ui.ZStack(width=RECT_WIDTH + 1): ui.Rectangle(name="vector_label", style={"background_color": field_label[1]}) ui.Label(field_label[0], name="vector_label", alignment=ui.Alignment.CENTER) add_separator() return [plot_0, plot_1, plot_2], [val_model_x, val_model_y, val_model_z] def add_line_rect_flourish(draw_line=True): """Aesthetic element that adds a Line + Rectangle after all UI elements in the row. Args: draw_line (bool, optional): Set false to only draw rectangle. Defaults to True. """ if draw_line: ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1), alignment=ui.Alignment.CENTER) ui.Spacer(width=10) with ui.Frame(width=0): with ui.VStack(): with ui.Placer(offset_x=0, offset_y=7): ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER) ui.Spacer(width=5) def add_separator(): """Aesthetic element to adds a Line Separator.""" with ui.VStack(spacing=5): ui.Spacer() with ui.HStack(): ui.Spacer(width=LABEL_WIDTH) ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1)) ui.Spacer(width=20) ui.Spacer() def add_folder_picker_icon( on_click_fn, item_filter_fn=None, bookmark_label=None, bookmark_path=None, dialog_title="Select Output Folder", button_title="Select Folder", ): def open_file_picker(): def on_selected(filename, path): on_click_fn(filename, path) file_picker.hide() def on_canceled(a, b): file_picker.hide() file_picker = FilePickerDialog( dialog_title, allow_multi_selection=False, apply_button_label=button_title, click_apply_handler=lambda a, b: on_selected(a, b), click_cancel_handler=lambda a, b: on_canceled(a, b), item_filter_fn=item_filter_fn, enable_versioning_pane=True, ) if bookmark_label and bookmark_path: file_picker.toggle_bookmark_from_path(bookmark_label, bookmark_path, True) with ui.Frame(width=0, tooltip=button_title): ui.Button( name="IconButton", width=24, height=24, clicked_fn=open_file_picker, style=get_style()["IconButton.Image::FolderPicker"], alignment=ui.Alignment.RIGHT_TOP, ) def add_folder_picker_btn(on_click_fn): def open_folder_picker(): def on_selected(a, b): on_click_fn(a, b) folder_picker.hide() def on_canceled(a, b): folder_picker.hide() folder_picker = FilePickerDialog( "Select Output Folder", allow_multi_selection=False, apply_button_label="Select Folder", click_apply_handler=lambda a, b: on_selected(a, b), click_cancel_handler=lambda a, b: on_canceled(a, b), ) with ui.Frame(width=0): ui.Button("SELECT", width=BUTTON_WIDTH, clicked_fn=open_folder_picker, tooltip="Select Folder") def format_tt(tt): import string formated = "" i = 0 for w in tt.split(): if w.isupper(): formated += w + " " elif len(w) > 3 or i == 0: formated += string.capwords(w) + " " else: formated += w.lower() + " " i += 1 return formated def setup_ui_headers( ext_id, file_path, title="My Custom Extension", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html", overview="", ): """Creates the Standard UI Elements at the top of each Isaac Extension. Args: ext_id (str): Extension ID. file_path (str): File path to source code. title (str, optional): Name of Extension. Defaults to "My Custom Extension". doc_link (str, optional): Hyperlink to Documentation. Defaults to "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html". overview (str, optional): Overview Text explaining the Extension. Defaults to "". """ ext_manager = omni.kit.app.get_app().get_extension_manager() extension_path = ext_manager.get_extension_path(ext_id) ext_path = os.path.dirname(extension_path) if os.path.isfile(extension_path) else extension_path build_header(ext_path, file_path, title, doc_link) build_info_frame(overview) def build_header( ext_path, file_path, title="My Custom Extension", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html", ): """Title Header with Quick Access Utility Buttons.""" def build_icon_bar(): """Adds the Utility Buttons to the Title Header""" with ui.Frame(style=get_style(), width=0): with ui.VStack(): with ui.HStack(): icon_size = 24 with ui.Frame(tooltip="Open Source Code"): ui.Button( name="IconButton", width=icon_size, height=icon_size, clicked_fn=lambda: on_open_IDE_clicked(ext_path, file_path), style=get_style()["IconButton.Image::OpenConfig"], # style_type_name_override="IconButton.Image::OpenConfig", alignment=ui.Alignment.LEFT_CENTER, # tooltip="Open in IDE", ) with ui.Frame(tooltip="Open Containing Folder"): ui.Button( name="IconButton", width=icon_size, height=icon_size, clicked_fn=lambda: on_open_folder_clicked(file_path), style=get_style()["IconButton.Image::OpenFolder"], alignment=ui.Alignment.LEFT_CENTER, ) with ui.Placer(offset_x=0, offset_y=3): with ui.Frame(tooltip="Link to Docs"): ui.Button( name="IconButton", width=icon_size - icon_size * 0.25, height=icon_size - icon_size * 0.25, clicked_fn=lambda: on_docs_link_clicked(doc_link), style=get_style()["IconButton.Image::OpenLink"], alignment=ui.Alignment.LEFT_TOP, ) with ui.ZStack(): ui.Rectangle(style={"border_radius": 5}) with ui.HStack(): ui.Spacer(width=5) ui.Label(title, width=0, name="title", style={"font_size": 16}) ui.Spacer(width=ui.Fraction(1)) build_icon_bar() ui.Spacer(width=5) def build_info_frame(overview=""): """Info Frame with Overview, Instructions, and Metadata for an Extension""" frame = ui.CollapsableFrame( title="Information", height=0, collapsed=True, horizontal_clipping=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: label = "Overview" default_val = overview tooltip = "Overview" with ui.VStack(style=get_style(), spacing=5): with ui.HStack(): ui.Label(label, width=LABEL_WIDTH / 2, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip)) with ui.ScrollingFrame( height=LABEL_HEIGHT * 5, style_type_name_override="ScrollingFrame", alignment=ui.Alignment.LEFT_TOP, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): text = ui.Label( default_val, style_type_name_override="Label::label", word_wrap=True, alignment=ui.Alignment.LEFT_TOP, ) with ui.Frame(width=0, tooltip="Copy To Clipboard"): ui.Button( name="IconButton", width=20, height=20, clicked_fn=lambda: on_copy_to_clipboard(to_copy=text.text), style=get_style()["IconButton.Image::CopyToClipboard"], alignment=ui.Alignment.RIGHT_TOP, ) return # def build_settings_frame(log_filename="extension.log", log_to_file=False, save_settings=False): # """Settings Frame for Common Utilities Functions""" # frame = ui.CollapsableFrame( # title="Settings", # height=0, # collapsed=True, # horizontal_clipping=False, # style=get_style(), # style_type_name_override="CollapsableFrame", # ) # def on_log_to_file_enabled(val): # # TO DO # carb.log_info(f"Logging to {model.get_value_as_string()}:", val) # def on_save_out_settings(val): # # TO DO # carb.log_info("Save Out Settings?", val) # with frame: # with ui.VStack(style=get_style(), spacing=5): # # # Log to File Settings # # default_output_path = os.path.realpath(os.getcwd()) # # kwargs = { # # "label": "Log to File", # # "type": "checkbox_stringfield", # # "default_val": [log_to_file, default_output_path + "/" + log_filename], # # "on_clicked_fn": on_log_to_file_enabled, # # "tooltip": "Log Out to File", # # "use_folder_picker": True, # # } # # model = combo_cb_str_builder(**kwargs)[1] # # Save Settings on Exit # # kwargs = { # # "label": "Save Settings", # # "type": "checkbox", # # "default_val": save_settings, # # "on_clicked_fn": on_save_out_settings, # # "tooltip": "Save out GUI Settings on Exit.", # # } # # cb_builder(**kwargs) class SearchListItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) def __repr__(self): return f'"{self.name_model.as_string}"' def name(self): return self.name_model.as_string class SearchListItemModel(ui.AbstractItemModel): """ Represents the model for lists. It's very easy to initialize it with any string list: string_list = ["Hello", "World"] model = ListModel(*string_list) ui.TreeView(model) """ def __init__(self, *args): super().__init__() self._children = [SearchListItem(t) for t in args] self._filtered = [SearchListItem(t) for t in args] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._filtered def filter_text(self, text): import fnmatch self._filtered = [] if len(text) == 0: for c in self._children: self._filtered.append(c) else: parts = text.split() # for i in range(len(parts) - 1, -1, -1): # w = parts[i] leftover = " ".join(parts) if len(leftover) > 0: filter_str = f"*{leftover.lower()}*" for c in self._children: if fnmatch.fnmatch(c.name().lower(), filter_str): self._filtered.append(c) # This tells the Delegate to update the TreeView self._item_changed(None) def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model class SearchListItemDelegate(ui.AbstractItemDelegate): """ Delegate is the representation layer. TreeView calls the methods of the delegate to create custom widgets for each item. """ def __init__(self, on_double_click_fn=None): super().__init__() self._on_double_click_fn = on_double_click_fn def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" pass def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" stack = ui.ZStack(height=20, style=get_style()) with stack: with ui.HStack(): ui.Spacer(width=5) value_model = model.get_item_value_model(item, column_id) label = ui.Label(value_model.as_string, name="TreeView.Item") if not self._on_double_click_fn: self._on_double_click_fn = self.on_double_click # Set a double click function stack.set_mouse_double_clicked_fn(lambda x, y, b, m, l=label: self._on_double_click_fn(b, m, l)) def on_double_click(self, button, model, label): """Called when the user double-clicked the item in TreeView""" if button != 0: return def build_simple_search(label="", type="search", model=None, delegate=None, tooltip=""): """A Simple Search Bar + TreeView Widget.\n Pass a list of items through the model, and a custom on_click_fn through the delegate.\n Returns the SearchWidget so user can destroy it on_shutdown. Args: label (str, optional): Label to the left of the UI element. Defaults to "". type (str, optional): Type of UI element. Defaults to "search". model (ui.AbstractItemModel, optional): Item Model for Search. Defaults to None. delegate (ui.AbstractItemDelegate, optional): Item Delegate for Search. Defaults to None. tooltip (str, optional): Tooltip to display over the Label. Defaults to "". Returns: Tuple(Search Widget, Treeview): """ with ui.HStack(): ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip)) with ui.VStack(spacing=5): def filter_text(item): model.filter_text(item) from omni.kit.window.extensions.ext_components import SearchWidget search_bar = SearchWidget(filter_text) with ui.ScrollingFrame( height=LABEL_HEIGHT * 5, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style=get_style(), style_type_name_override="TreeView.ScrollingFrame", ): treeview = ui.TreeView( model, delegate=delegate, root_visible=False, header_visible=False, style={ "TreeView.ScrollingFrame": {"background_color": 0xFFE0E0E0}, "TreeView.Item": {"color": 0xFF535354, "font_size": 16}, "TreeView.Item:selected": {"color": 0xFF23211F}, "TreeView:selected": {"background_color": 0x409D905C}, } # name="TreeView", # style_type_name_override="TreeView", ) add_line_rect_flourish(False) return search_bar, treeview
62,248
Python
38.373182
169
0.558958
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/common.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import carb.tokens import omni from pxr import PhysxSchema, UsdGeom, UsdPhysics def set_drive_parameters(drive, target_type, target_value, stiffness=None, damping=None, max_force=None): """Enable velocity drive for a given joint""" if target_type == "position": if not drive.GetTargetPositionAttr(): drive.CreateTargetPositionAttr(target_value) else: drive.GetTargetPositionAttr().Set(target_value) elif target_type == "velocity": if not drive.GetTargetVelocityAttr(): drive.CreateTargetVelocityAttr(target_value) else: drive.GetTargetVelocityAttr().Set(target_value) if stiffness is not None: if not drive.GetStiffnessAttr(): drive.CreateStiffnessAttr(stiffness) else: drive.GetStiffnessAttr().Set(stiffness) if damping is not None: if not drive.GetDampingAttr(): drive.CreateDampingAttr(damping) else: drive.GetDampingAttr().Set(damping) if max_force is not None: if not drive.GetMaxForceAttr(): drive.CreateMaxForceAttr(max_force) else: drive.GetMaxForceAttr().Set(max_force)
1,900
Python
34.203703
105
0.693158
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/import_franka.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import math import weakref import omni import omni.ui as ui from omni.importer.urdf.scripts.ui import ( btn_builder, get_style, make_menu_item_description, setup_ui_headers, ) from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items from omni.kit.viewport.utility.camera_state import ViewportCameraState from pxr import Gf, PhysicsSchemaTools, PhysxSchema, Sdf, UsdLux, UsdPhysics from .common import set_drive_parameters EXTENSION_NAME = "Import Franka" class Extension(omni.ext.IExt): def on_startup(self, ext_id: str): ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_id = ext_id self._extension_path = ext_manager.get_extension_path(ext_id) self._menu_items = [ MenuItemDescription( name="Import Robots", sub_menu=[ make_menu_item_description(ext_id, "Franka URDF", lambda a=weakref.proxy(self): a._menu_callback()) ], ) ] add_menu_items(self._menu_items, "Isaac Examples") self._build_ui() def _build_ui(self): self._window = omni.ui.Window( EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): title = "Import a Franka Panda via URDF" doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = ( "This Example shows you import a URDF.\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): dict = { "label": "Load Robot", "type": "button", "text": "Load", "tooltip": "Load a UR10 Robot into the Scene", "on_clicked_fn": self._on_load_robot, } btn_builder(**dict) dict = { "label": "Configure Drives", "type": "button", "text": "Configure", "tooltip": "Configure Joint Drives", "on_clicked_fn": self._on_config_robot, } btn_builder(**dict) dict = { "label": "Move to Pose", "type": "button", "text": "move", "tooltip": "Drive the Robot to a specific pose", "on_clicked_fn": self._on_config_drives, } btn_builder(**dict) def on_shutdown(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None def _menu_callback(self): self._window.visible = not self._window.visible def _on_load_robot(self): load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async()) asyncio.ensure_future(self._load_franka(load_stage)) async def _load_franka(self, task): done, pending = await asyncio.wait({task}) if task in done: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.fix_base = True import_config.make_default_prim = True import_config.create_physics_scene = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._extension_path + "/data/urdf/robots/franka_description/robots/panda_arm_hand.urdf", import_config=import_config, ) camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(Gf.Vec3d(1.22, -1.24, 1.13), True) camera_state.set_target_world(Gf.Vec3d(-0.96, 1.08, 0.0), True) stage = omni.usd.get_context().get_stage() scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) plane_path = "/groundPlane" PhysicsSchemaTools.addGroundPlane( stage, plane_path, "Z", 1500.0, Gf.Vec3f(0, 0, 0), Gf.Vec3f([0.5, 0.5, 0.5]), ) # make sure the ground plane is under root prim and not robot omni.kit.commands.execute( "MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True ) distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) def _on_config_robot(self): stage = omni.usd.get_context().get_stage() # Set the solver parameters on the articulation PhysxSchema.PhysxArticulationAPI.Get(stage, "/panda").CreateSolverPositionIterationCountAttr(64) PhysxSchema.PhysxArticulationAPI.Get(stage, "/panda").CreateSolverVelocityIterationCountAttr(64) self.joint_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link0/panda_joint1"), "angular") self.joint_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link1/panda_joint2"), "angular") self.joint_3 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link2/panda_joint3"), "angular") self.joint_4 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link3/panda_joint4"), "angular") self.joint_5 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link4/panda_joint5"), "angular") self.joint_6 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link5/panda_joint6"), "angular") self.joint_7 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link6/panda_joint7"), "angular") self.finger_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_hand/panda_finger_joint1"), "linear") self.finger_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_hand/panda_finger_joint2"), "linear") # Set the drive mode, target, stiffness, damping and max force for each joint set_drive_parameters(self.joint_1, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_2, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_3, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_4, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_5, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_6, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.joint_7, "position", math.degrees(0), math.radians(1e8), math.radians(1e7)) set_drive_parameters(self.finger_1, "position", 0, 1e7, 1e6) set_drive_parameters(self.finger_2, "position", 0, 1e7, 1e6) def _on_config_drives(self): self._on_config_robot() # make sure drives are configured first # Set the drive mode, target, stiffness, damping and max force for each joint set_drive_parameters(self.joint_1, "position", math.degrees(0.012)) set_drive_parameters(self.joint_2, "position", math.degrees(-0.57)) set_drive_parameters(self.joint_3, "position", math.degrees(0)) set_drive_parameters(self.joint_4, "position", math.degrees(-2.81)) set_drive_parameters(self.joint_5, "position", math.degrees(0)) set_drive_parameters(self.joint_6, "position", math.degrees(3.037)) set_drive_parameters(self.joint_7, "position", math.degrees(0.741)) set_drive_parameters(self.finger_1, "position", 4) set_drive_parameters(self.finger_2, "position", 4)
9,623
Python
47.361809
119
0.601268
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/import_kaya.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import math import weakref import omni import omni.kit.commands import omni.ui as ui from omni.importer.urdf.scripts.ui import ( btn_builder, get_style, make_menu_item_description, setup_ui_headers, ) from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items from omni.kit.viewport.utility.camera_state import ViewportCameraState from pxr import Gf, PhysicsSchemaTools, Sdf, UsdLux, UsdPhysics from .common import set_drive_parameters EXTENSION_NAME = "Import Kaya" class Extension(omni.ext.IExt): def on_startup(self, ext_id: str): ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_id = ext_id self._extension_path = ext_manager.get_extension_path(ext_id) self._menu_items = [ MenuItemDescription( name="Import Robots", sub_menu=[ make_menu_item_description(ext_id, "Kaya URDF", lambda a=weakref.proxy(self): a._menu_callback()) ], ) ] add_menu_items(self._menu_items, "Isaac Examples") self._build_ui() def _build_ui(self): self._window = omni.ui.Window( EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): title = "Import a Kaya Robot via URDF" doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = "This Example shows you import an NVIDIA Kaya robot via URDF.\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): dict = { "label": "Load Robot", "type": "button", "text": "Load", "tooltip": "Load a UR10 Robot into the Scene", "on_clicked_fn": self._on_load_robot, } btn_builder(**dict) dict = { "label": "Configure Drives", "type": "button", "text": "Configure", "tooltip": "Configure Joint Drives", "on_clicked_fn": self._on_config_robot, } btn_builder(**dict) dict = { "label": "Spin Robot", "type": "button", "text": "move", "tooltip": "Spin the Robot in Place", "on_clicked_fn": self._on_config_drives, } btn_builder(**dict) def on_shutdown(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None def _menu_callback(self): self._window.visible = not self._window.visible def _on_load_robot(self): load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async()) asyncio.ensure_future(self._load_kaya(load_stage)) async def _load_kaya(self, task): done, pending = await asyncio.wait({task}) if task in done: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = True import_config.import_inertia_tensor = False # import_config.distance_scale = 1.0 import_config.fix_base = False import_config.make_default_prim = True import_config.create_physics_scene = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._extension_path + "/data/urdf/robots/kaya/urdf/kaya.urdf", import_config=import_config, ) camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(Gf.Vec3d(-1.0, 1.5, 0.5), True) camera_state.set_target_world(Gf.Vec3d(0.0, 0.0, 0.0), True) stage = omni.usd.get_context().get_stage() scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) plane_path = "/groundPlane" PhysicsSchemaTools.addGroundPlane( stage, plane_path, "Z", 1500.0, Gf.Vec3f(0, 0, -0.25), Gf.Vec3f([0.5, 0.5, 0.5]) ) # make sure the ground plane is under root prim and not robot omni.kit.commands.execute( "MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True ) distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) def _on_config_robot(self): stage = omni.usd.get_context().get_stage() # Make all rollers spin freely by removing extra drive API for axle in range(0, 2 + 1): for ring in range(0, 1 + 1): for roller in range(0, 4 + 1): prim_path = ( "/kaya/axle_" + str(axle) + "/roller_" + str(axle) + "_" + str(ring) + "_" + str(roller) + "_joint" ) prim = stage.GetPrimAtPath(prim_path) # omni.kit.commands.execute( # "UnapplyAPISchemaCommand", # api=UsdPhysics.DriveAPI, # prim=prim, # api_prefix="drive", # multiple_api_token="angular", # ) prim.RemoveAPI(UsdPhysics.DriveAPI, "angular") def _on_config_drives(self): self._on_config_robot() # make sure drives are configured first stage = omni.usd.get_context().get_stage() # set each axis to spin at a rate of 1 rad/s axle_0 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_0_joint"), "angular") axle_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_1_joint"), "angular") axle_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_2_joint"), "angular") set_drive_parameters(axle_0, "velocity", math.degrees(1), 0, math.radians(1e7)) set_drive_parameters(axle_1, "velocity", math.degrees(1), 0, math.radians(1e7)) set_drive_parameters(axle_2, "velocity", math.degrees(1), 0, math.radians(1e7))
8,253
Python
41.328205
148
0.545499
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/import_carter.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import math import weakref import omni import omni.kit.commands import omni.ui as ui from omni.importer.urdf.scripts.ui import ( btn_builder, get_style, make_menu_item_description, setup_ui_headers, ) from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items from omni.kit.viewport.utility.camera_state import ViewportCameraState from pxr import Gf, PhysicsSchemaTools, Sdf, UsdLux, UsdPhysics from .common import set_drive_parameters EXTENSION_NAME = "Import Carter" class Extension(omni.ext.IExt): def on_startup(self, ext_id: str): ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_id = ext_id self._extension_path = ext_manager.get_extension_path(ext_id) self._menu_items = [ MenuItemDescription( name="Import Robots", sub_menu=[ make_menu_item_description(ext_id, "Carter URDF", lambda a=weakref.proxy(self): a._menu_callback()) ], ) ] add_menu_items(self._menu_items, "Isaac Examples") self._build_ui() def _build_ui(self): self._window = omni.ui.Window( EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): title = "Import a UR10 via URDF" doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = "This Example shows how to import a URDF in Isaac Sim.\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): dict = { "label": "Load Robot", "type": "button", "text": "Load", "tooltip": "Load a NVIDIA Carter robot into the Scene", "on_clicked_fn": self._on_load_robot, } btn_builder(**dict) dict = { "label": "Configure Drives", "type": "button", "text": "Configure", "tooltip": "Configure Wheel Drives", "on_clicked_fn": self._on_config_robot, } btn_builder(**dict) dict = { "label": "Move to Pose", "type": "button", "text": "move", "tooltip": "Drive the Robot to a specific pose", "on_clicked_fn": self._on_config_drives, } btn_builder(**dict) def on_shutdown(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None def _menu_callback(self): self._window.visible = not self._window.visible def _on_load_robot(self): load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async()) asyncio.ensure_future(self._load_carter(load_stage)) async def _load_carter(self, task): done, pending = await asyncio.wait({task}) if task in done: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.fix_base = False import_config.make_default_prim = True import_config.create_physics_scene = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._extension_path + "/data/urdf/robots/carter/urdf/carter.urdf", import_config=import_config, ) camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(Gf.Vec3d(3.00, -3.50, 1.13), True) camera_state.set_target_world(Gf.Vec3d(-0.96, 1.08, -0.20), True) stage = omni.usd.get_context().get_stage() scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) plane_path = "/groundPlane" PhysicsSchemaTools.addGroundPlane( stage, plane_path, "Z", 1500.0, Gf.Vec3f(0, 0, -0.50), Gf.Vec3f([0.5, 0.5, 0.5]) ) # make sure the ground plane is under root prim and not robot omni.kit.commands.execute( "MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True ) distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) def _on_config_robot(self): stage = omni.usd.get_context().get_stage() # Remove drive from rear wheel and pivot prim = stage.GetPrimAtPath("/carter/chassis_link/rear_pivot") # omni.kit.commands.execute( # "UnapplyAPISchemaCommand", # api=UsdPhysics.DriveAPI, # prim=prim, # api_prefix="drive", # multiple_api_token="angular", # ) prim.RemoveAPI(UsdPhysics.DriveAPI, "angular") prim = stage.GetPrimAtPath("/carter/rear_pivot_link/rear_axle") # omni.kit.commands.execute( # "UnapplyAPISchemaCommand", # api=UsdPhysics.DriveAPI, # prim=prim, # api_prefix="drive", # multiple_api_token="angular", # ) prim.RemoveAPI(UsdPhysics.DriveAPI, "angular") def _on_config_drives(self): self._on_config_robot() # make sure drives are configured first stage = omni.usd.get_context().get_stage() left_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/left_wheel"), "angular") right_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/right_wheel"), "angular") # Drive forward set_drive_parameters(left_wheel_drive, "velocity", math.degrees(2.5), 0, math.radians(1e8)) set_drive_parameters(right_wheel_drive, "velocity", math.degrees(2.5), 0, math.radians(1e8))
7,770
Python
40.55615
141
0.57323
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/import_ur10.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import math import weakref import omni import omni.ui as ui from omni.importer.urdf.scripts.ui import ( btn_builder, get_style, make_menu_item_description, setup_ui_headers, ) from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items from omni.kit.viewport.utility.camera_state import ViewportCameraState from pxr import Gf, PhysxSchema, Sdf, UsdLux, UsdPhysics from .common import set_drive_parameters EXTENSION_NAME = "Import UR10" class Extension(omni.ext.IExt): def on_startup(self, ext_id: str): """Initialize extension and UI elements""" ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_id = ext_id self._extension_path = ext_manager.get_extension_path(ext_id) self._menu_items = [ MenuItemDescription( name="Import Robots", sub_menu=[ make_menu_item_description(ext_id, "UR10 URDF", lambda a=weakref.proxy(self): a._menu_callback()) ], ) ] add_menu_items(self._menu_items, "Isaac Examples") self._build_ui() def _build_ui(self): self._window = omni.ui.Window( EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): title = "Import a UR10 via URDF" doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html" overview = "This Example shows you import a UR10 robot arm via URDF.\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): dict = { "label": "Load Robot", "type": "button", "text": "Load", "tooltip": "Load a UR10 Robot into the Scene", "on_clicked_fn": self._on_load_robot, } btn_builder(**dict) dict = { "label": "Configure Drives", "type": "button", "text": "Configure", "tooltip": "Configure Joint Drives", "on_clicked_fn": self._on_config_robot, } btn_builder(**dict) dict = { "label": "Move to Pose", "type": "button", "text": "move", "tooltip": "Drive the Robot to a specific pose", "on_clicked_fn": self._on_config_drives, } btn_builder(**dict) def on_shutdown(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None def _menu_callback(self): self._window.visible = not self._window.visible def _on_load_robot(self): load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async()) asyncio.ensure_future(self._load_robot(load_stage)) async def _load_robot(self, task): done, pending = await asyncio.wait({task}) if task in done: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.fix_base = True import_config.make_default_prim = True import_config.create_physics_scene = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._extension_path + "/data/urdf/robots/ur10/urdf/ur10.urdf", import_config=import_config, ) camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(Gf.Vec3d(2.0, -2.0, 0.5), True) camera_state.set_target_world(Gf.Vec3d(0.0, 0.0, 0.0), True) stage = omni.usd.get_context().get_stage() scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) def _on_config_robot(self): stage = omni.usd.get_context().get_stage() PhysxSchema.PhysxArticulationAPI.Get(stage, "/ur10").CreateSolverPositionIterationCountAttr(64) PhysxSchema.PhysxArticulationAPI.Get(stage, "/ur10").CreateSolverVelocityIterationCountAttr(64) self.joint_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/base_link/shoulder_pan_joint"), "angular") self.joint_2 = UsdPhysics.DriveAPI.Get( stage.GetPrimAtPath("/ur10/shoulder_link/shoulder_lift_joint"), "angular" ) self.joint_3 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/upper_arm_link/elbow_joint"), "angular") self.joint_4 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/forearm_link/wrist_1_joint"), "angular") self.joint_5 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/wrist_1_link/wrist_2_joint"), "angular") self.joint_6 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/ur10/wrist_2_link/wrist_3_joint"), "angular") # Set the drive mode, target, stiffness, damping and max force for each joint set_drive_parameters(self.joint_1, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_2, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_3, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_4, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_5, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) set_drive_parameters(self.joint_6, "position", math.degrees(0), math.radians(1e8), math.radians(5e7)) def _on_config_drives(self): self._on_config_robot() # make sure drives are configured first set_drive_parameters(self.joint_1, "position", 45) set_drive_parameters(self.joint_2, "position", 45) set_drive_parameters(self.joint_3, "position", 45) set_drive_parameters(self.joint_4, "position", 45) set_drive_parameters(self.joint_5, "position", 45) set_drive_parameters(self.joint_6, "position", 45)
8,082
Python
44.666666
144
0.597253
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/tests/test_urdf.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import os import numpy as np import omni.kit.commands # NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test import pxr from pxr import Gf, PhysicsSchemaTools, Sdf, UsdGeom, UsdPhysics, UsdShade # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class TestUrdf(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._timeline = omni.timeline.get_timeline_interface() ext_manager = omni.kit.app.get_app().get_extension_manager() ext_id = ext_manager.get_enabled_extension_id("omni.importer.urdf") self._extension_path = ext_manager.get_extension_path(ext_id) self.dest_path = os.path.abspath(self._extension_path + "/tests_out") await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() pass # After running each test async def tearDown(self): # _urdf.release_urdf_interface(self._urdf_interface) await omni.kit.app.get_app().next_update_async() pass # Tests to make sure visual mesh names are incremented async def test_urdf_mesh_naming(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_names.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) prim = stage.GetPrimAtPath("/test_names/cube/visuals") prim_range = prim.GetChildren() # There should be a total of 6 visual meshes after import self.assertEqual(len(prim_range), 6) # basic urdf test: joints and links are imported correctly async def test_urdf_basic(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() prim = stage.GetPrimAtPath("/test_basic") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # make sure the joints exist root_joint = stage.GetPrimAtPath("/test_basic/root_joint") self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath) wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint") self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint") fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint") self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint") self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08) fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2") self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0) self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0) pass async def test_urdf_save_to_file(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") dest_path = os.path.abspath(self.dest_path + "/test_basic.usd") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() stage = pxr.Usd.Stage.Open(dest_path) prim = stage.GetPrimAtPath("/test_basic") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # make sure the joints exist root_joint = stage.GetPrimAtPath("/test_basic/root_joint") self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath) wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint") self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint") fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint") self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint") self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08) fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2") self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0) self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3) self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0) stage = None pass async def test_urdf_textured_obj(self): base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf" basename = "cube_obj" dest_path = "{}/{}/{}.usd".format(self.dest_path, basename, basename) mats_path = "{}/{}/materials".format(self.dest_path, basename) omni.client.create_folder("{}/{}".format(self.dest_path, basename)) omni.client.create_folder(mats_path) urdf_path = "{}/{}.urdf".format(base_path, basename) status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() result = omni.client.list(mats_path) self.assertEqual(result[0], omni.client._omniclient.Result.OK) self.assertEqual(len(result[1]), 4) # Metallic texture is unsuported by assimp on OBJ pass async def test_urdf_textured_in_memory(self): base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf" basename = "cube_obj" urdf_path = "{}/{}.urdf".format(base_path, basename) status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() pass async def test_urdf_textured_dae(self): base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf" basename = "cube_dae" dest_path = "{}/{}/{}.usd".format(self.dest_path, basename, basename) mats_path = "{}/{}/materials".format(self.dest_path, basename) omni.client.create_folder("{}/{}".format(self.dest_path, basename)) omni.client.create_folder(mats_path) urdf_path = "{}/{}.urdf".format(base_path, basename) status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() result = omni.client.list(mats_path) self.assertEqual(result[0], omni.client._omniclient.Result.OK) self.assertEqual(len(result[1]), 1) # only albedo is supported for Collada pass async def test_urdf_overwrite_file(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") dest_path = os.path.abspath(self._extension_path + "/data/urdf/tests/tests_out/test_basic.usd") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path ) await omni.kit.app.get_app().next_update_async() stage = pxr.Usd.Stage.Open(dest_path) prim = stage.GetPrimAtPath("/test_basic") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # make sure the joints exist root_joint = stage.GetPrimAtPath("/test_basic/root_joint") self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath) wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint") self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint") fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint") self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint") self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08) fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2") self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0) self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0) stage = None pass # advanced urdf test: test for all the categories of inputs that an urdf can hold async def test_urdf_advanced(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_advanced.urdf") stage = omni.usd.get_context().get_stage() # enable merging fixed joints status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = True import_config.default_position_drive_damping = -1 # ignore this setting by making it -1 omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() # check if object is there prim = stage.GetPrimAtPath("/test_advanced") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # check color are imported mesh = stage.GetPrimAtPath("/test_advanced/link_1/visuals") self.assertNotEqual(mesh.GetPath(), Sdf.Path.emptyPath) mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial() shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader")) self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0, 0.8, 0), 1e-5)) # check joint properties elbowPrim = stage.GetPrimAtPath("/test_advanced/link_1/elbow_joint") self.assertNotEqual(elbowPrim.GetPath(), Sdf.Path.emptyPath) self.assertAlmostEqual(elbowPrim.GetAttribute("physxJoint:jointFriction").Get(), 0.1) self.assertAlmostEqual(elbowPrim.GetAttribute("drive:angular:physics:damping").Get(), 0.1) # check position of a link joint_pos = elbowPrim.GetAttribute("physics:localPos0").Get() self.assertTrue(Gf.IsClose(joint_pos, Gf.Vec3f(0, 0, 0.40), 1e-5)) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass # test for importing urdf where fixed joints are merged async def test_urdf_merge_joints(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_merge_joints.urdf") stage = omni.usd.get_context().get_stage() # enable merging fixed joints status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # the merged link shouldn't be there prim = stage.GetPrimAtPath("/test_merge_joints/link_2") self.assertEqual(prim.GetPath(), Sdf.Path.emptyPath) pass async def test_urdf_mtl(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_mtl.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) mesh = stage.GetPrimAtPath("/test_mtl/cube/visuals") self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None) mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial() shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader")) print(shader) self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0.8, 0.0, 0), 1e-5)) async def test_urdf_material(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_material.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) mesh = stage.GetPrimAtPath("/test_material/base/visuals") self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None) mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial() shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader")) print(shader) self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(1.0, 0.0, 0.0), 1e-5)) async def test_urdf_mtl_stl(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_mtl_stl.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) mesh = stage.GetPrimAtPath("/test_mtl_stl/cube/visuals") self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None) mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial() shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader")) print(shader) self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0.8, 0.0, 0), 1e-5)) async def test_urdf_carter(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/carter/urdf/carter.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False status, path = omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config ) self.assertTrue(path, "/carter") # TODO add checks here async def test_urdf_franka(self): urdf_path = os.path.abspath( self._extension_path + "/data/urdf/robots/franka_description/robots/panda_arm_hand.urdf" ) status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # TODO add checks here' async def test_urdf_ur10(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/ur10/urdf/ur10.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # TODO add checks here' async def test_urdf_kaya(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/kaya/urdf/kaya.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # TODO add checks here async def test_missing(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_missing.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) # This sample corresponds to the example in the docs, keep this and the version in the docs in sync async def test_doc_sample(self): import omni.kit.commands from pxr import Gf, Sdf, UsdLux, UsdPhysics # setting up import configuration: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.convex_decomp = False import_config.import_inertia_tensor = True import_config.fix_base = False # Get path to extension data: ext_manager = omni.kit.app.get_app().get_extension_manager() ext_id = ext_manager.get_enabled_extension_id("omni.importer.urdf") extension_path = ext_manager.get_extension_path(ext_id) # import URDF omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=extension_path + "/data/urdf/robots/carter/urdf/carter.urdf", import_config=import_config, ) # get stage handle stage = omni.usd.get_context().get_stage() # enable physics scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) # set gravity scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) # add ground plane PhysicsSchemaTools.addGroundPlane(stage, "/World/groundPlane", "Z", 1500, Gf.Vec3f(0, 0, -50), Gf.Vec3f(0.5)) # add lighting distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) #### #### Next Docs section #### # get handle to the Drive API for both wheels left_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/left_wheel"), "angular") right_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/right_wheel"), "angular") # Set the velocity drive target in degrees/second left_wheel_drive.GetTargetVelocityAttr().Set(150) right_wheel_drive.GetTargetVelocityAttr().Set(150) # Set the drive damping, which controls the strength of the velocity drive left_wheel_drive.GetDampingAttr().Set(15000) right_wheel_drive.GetDampingAttr().Set(15000) # Set the drive stiffness, which controls the strength of the position drive # In this case because we want to do velocity control this should be set to zero left_wheel_drive.GetStiffnessAttr().Set(0) right_wheel_drive.GetStiffnessAttr().Set(0) # Make sure that a urdf with more than 63 links imports async def test_64(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_large.urdf") status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath("/test_large") self.assertTrue(prim) # basic urdf test: joints and links are imported correctly async def test_urdf_floating(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_floating.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() prim = stage.GetPrimAtPath("/test_floating") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # make sure the joints exist root_joint = stage.GetPrimAtPath("/test_floating/root_joint") self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath) link_1 = stage.GetPrimAtPath("/test_floating/link_1") self.assertNotEqual(link_1.GetPath(), Sdf.Path.emptyPath) link_1_trans = np.array(omni.usd.get_world_transform_matrix(link_1).ExtractTranslation()) self.assertAlmostEqual(np.linalg.norm(link_1_trans - np.array([0, 0, 0.45])), 0, delta=0.03) floating_link = stage.GetPrimAtPath("/test_floating/floating_link") self.assertNotEqual(floating_link.GetPath(), Sdf.Path.emptyPath) floating_link_trans = np.array(omni.usd.get_world_transform_matrix(floating_link).ExtractTranslation()) self.assertAlmostEqual(np.linalg.norm(floating_link_trans - np.array([0, 0, 1.450])), 0, delta=0.03) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass async def test_urdf_scale(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.distance_scale = 1.0 omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0) pass async def test_urdf_drive_none(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") from omni.importer.urdf._urdf import UrdfJointTargetType import_config.default_drive_type = UrdfJointTargetType.JOINT_DRIVE_NONE omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() self.assertFalse(stage.GetPrimAtPath("/test_basic/root_joint").HasAPI(UsdPhysics.DriveAPI)) self.assertTrue(stage.GetPrimAtPath("/test_basic/link_1/elbow_joint").HasAPI(UsdPhysics.DriveAPI)) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass async def test_urdf_usd(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_usd.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") from omni.importer.urdf._urdf import UrdfJointTargetType import_config.default_drive_type = UrdfJointTargetType.JOINT_DRIVE_NONE omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() self.assertNotEqual(stage.GetPrimAtPath("/test_usd/cube/visuals/mesh_0/Cylinder"), Sdf.Path.emptyPath) self.assertNotEqual(stage.GetPrimAtPath("/test_usd/cube/visuals/mesh_1/Torus"), Sdf.Path.emptyPath) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass # test negative joint limits async def test_urdf_limits(self): urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_limits.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.import_inertia_tensor = True omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() # ensure the import completed. prim = stage.GetPrimAtPath("/test_limits") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # ensure the joint limits are set on the elbow elbowJoint = stage.GetPrimAtPath("/test_limits/link_1/elbow_joint") self.assertNotEqual(elbowJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(elbowJoint.GetTypeName(), "PhysicsRevoluteJoint") self.assertTrue(elbowJoint.HasAPI(UsdPhysics.DriveAPI)) # ensure the joint limits are set on the wrist wristJoint = stage.GetPrimAtPath("/test_limits/link_2/wrist_joint") self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint") self.assertTrue(wristJoint.HasAPI(UsdPhysics.DriveAPI)) # ensure the joint limits are set on the finger1 finger1Joint = stage.GetPrimAtPath("/test_limits/palm_link/finger_1_joint") self.assertNotEqual(finger1Joint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(finger1Joint.GetTypeName(), "PhysicsPrismaticJoint") self.assertTrue(finger1Joint.HasAPI(UsdPhysics.DriveAPI)) # ensure the joint limits are set on the finger2 finger2Joint = stage.GetPrimAtPath("/test_limits/palm_link/finger_2_joint") self.assertNotEqual(finger2Joint.GetPath(), Sdf.Path.emptyPath) self.assertEqual(finger2Joint.GetTypeName(), "PhysicsPrismaticJoint") self.assertTrue(finger2Joint.HasAPI(UsdPhysics.DriveAPI)) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(1.0) # nothing crashes self._timeline.stop() pass # test collision from visuals async def test_collision_from_visuals(self): # import a urdf file without collision urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_collision_from_visuals.urdf") stage = omni.usd.get_context().get_stage() status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.set_collision_from_visuals(True) omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config) await omni.kit.app.get_app().next_update_async() # ensure the import completed. prim = stage.GetPrimAtPath("/test_collision_from_visuals") self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath) # ensure the base_link collision prim exists and has the collision API applied. base_link = stage.GetPrimAtPath("/test_collision_from_visuals/base_link/collisions") self.assertNotEqual(base_link.GetPath(), Sdf.Path.emptyPath) self.assertTrue(base_link.GetAttribute("physics:collisionEnabled").Get()) # ensure the link_1 collision prim exists and has the collision API applied. link_1 = stage.GetPrimAtPath("/test_collision_from_visuals/link_1/collisions") self.assertNotEqual(link_1.GetPath(), Sdf.Path.emptyPath) self.assertTrue(link_1.GetAttribute("physics:collisionEnabled").Get()) # ensure the link_2 collision prim exists and has the collision API applied. link_2 = stage.GetPrimAtPath("/test_collision_from_visuals/link_2/collisions") self.assertNotEqual(link_2.GetPath(), Sdf.Path.emptyPath) self.assertTrue(link_2.GetAttribute("physics:collisionEnabled").Get()) # ensure the palm_link collision prim exists and has the collision API applied. palm_link = stage.GetPrimAtPath("/test_collision_from_visuals/palm_link/collisions") self.assertNotEqual(palm_link.GetPath(), Sdf.Path.emptyPath) self.assertTrue(palm_link.GetAttribute("physics:collisionEnabled").Get()) # ensure the finger_link_1 collision prim exists and has the collision API applied. finger_link_1 = stage.GetPrimAtPath("/test_collision_from_visuals/finger_link_1/collisions") self.assertNotEqual(finger_link_1.GetPath(), Sdf.Path.emptyPath) self.assertTrue(finger_link_1.GetAttribute("physics:collisionEnabled").Get()) # ensure the finger_link_2 collision prim exists and has the collision API applied. finger_link_2 = stage.GetPrimAtPath("/test_collision_from_visuals/finger_link_2/collisions") self.assertNotEqual(finger_link_2.GetPath(), Sdf.Path.emptyPath) self.assertTrue(finger_link_2.GetAttribute("physics:collisionEnabled").Get()) # Start Simulation and wait self._timeline.play() await omni.kit.app.get_app().next_update_async() await asyncio.sleep(2.0) # nothing crashes self._timeline.stop() pass
31,541
Python
46.646526
142
0.682287
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/tests/__init__.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .test_urdf import *
705
Python
40.529409
98
0.768794
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/bindings/BindingsUrdfPython.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <carb/BindingsPythonUtils.h> #include "../plugins/math/core/maths.h" #include "../plugins/Urdf.h" #include <pybind11/stl.h> #include <pybind11/stl_bind.h> CARB_BINDINGS("omni.importer.urdf.python") PYBIND11_MAKE_OPAQUE(std::map<std::string, omni::importer::urdf::UrdfMaterial>); namespace omni { namespace importer { namespace urdf { } } } namespace { // Helper function that creates a python type for a std::map with a string key and a custom value type template <class T> void declare_map(py::module& m, const std::string typestr) { py::class_<std::map<std::string, T>>(m, typestr.c_str()) .def(py::init<>()) .def("__getitem__", [](const std::map<std::string, T>& map, std::string key) { try { return map.at(key); } catch (const std::out_of_range&) { throw py::key_error("key '" + key + "' does not exist"); } }) .def("__iter__", [](std::map<std::string, T>& items) { return py::make_key_iterator(items.begin(), items.end()); }, py::keep_alive<0, 1>()) .def("items", [](std::map<std::string, T>& items) { return py::make_iterator(items.begin(), items.end()); }, py::keep_alive<0, 1>()) .def("__len__", [](std::map<std::string, T>& items) { return items.size(); }); } PYBIND11_MODULE(_urdf, m) { using namespace carb; using namespace omni::importer::urdf; m.doc() = R"pbdoc( This extension provides an interface to the URDF importer. Example: Setup the configuration parameters before importing. Files must be parsed before imported. :: from omni.importer.urdf import _urdf urdf_interface = _urdf.acquire_urdf_interface() # setup config params import_config = _urdf.ImportConfig() import_config.set_merge_fixed_joints(False) import_config.set_fix_base(True) # parse and import file imported_robot = urdf_interface.parse_urdf(robot_path, filename, import_config) urdf_interface.import_robot(robot_path, filename, imported_robot, import_config, "") Refer to the sample documentation for more examples and usage )pbdoc"; py::class_<ImportConfig>(m, "ImportConfig") .def(py::init<>()) .def_readwrite("merge_fixed_joints", &ImportConfig::mergeFixedJoints, "Consolidating links that are connected by fixed joints") .def_readwrite("convex_decomp", &ImportConfig::convexDecomp, "Decompose a convex mesh into smaller pieces for a closer fit") .def_readwrite("import_inertia_tensor", &ImportConfig::importInertiaTensor, "Import inertia tensor from urdf, if not specified in urdf it will import as identity") .def_readwrite("fix_base", &ImportConfig::fixBase, "Create fix joint for base link") // .def_readwrite("flip_visuals", &ImportConfig::flipVisuals, "Flip visuals from Y up to Z up") .def_readwrite("self_collision", &ImportConfig::selfCollision, "Self collisions between links in the articulation") .def_readwrite("density", &ImportConfig::density, "default density used for links, use 0 to autocompute") .def_readwrite("default_drive_type", &ImportConfig::defaultDriveType, "default drive type used for joints") .def_readwrite( "subdivision_scheme", &ImportConfig::subdivisionScheme, "Subdivision scheme to be used for mesh normals") .def_readwrite( "default_drive_strength", &ImportConfig::defaultDriveStrength, "default drive stiffness used for joints") .def_readwrite("default_position_drive_damping", &ImportConfig::defaultPositionDriveDamping, "default drive damping used if drive type is set to position") .def_readwrite("distance_scale", &ImportConfig::distanceScale, "Set the unit scaling factor, 1.0 means meters, 100.0 means cm") .def_readwrite("up_vector", &ImportConfig::upVector, "Up vector used for import") .def_readwrite("create_physics_scene", &ImportConfig::createPhysicsScene, "add a physics scene to the stage on import if none exists") .def_readwrite("make_default_prim", &ImportConfig::makeDefaultPrim, "set imported robot as default prim") .def_readwrite("make_instanceable", &ImportConfig::makeInstanceable, "Creates an instanceable version of the asset. All meshes will be placed in a separate USD file") .def_readwrite( "instanceable_usd_path", &ImportConfig::instanceableMeshUsdPath, "USD file to store instanceable mehses in") .def_readwrite("collision_from_visuals", &ImportConfig::collisionFromVisuals, "Generate convex collision from the visual meshes.") .def_readwrite("replace_cylinders_with_capsules", &ImportConfig::replaceCylindersWithCapsules, "Replace all cylinder bodies in the URDF with capsules.") // setters for each property .def("set_merge_fixed_joints", [](ImportConfig& config, const bool value) { config.mergeFixedJoints = value; }) .def("set_replace_cylinders_with_capsules", [](ImportConfig& config, const bool value) { config.replaceCylindersWithCapsules = value; }) .def("set_convex_decomp", [](ImportConfig& config, const bool value) { config.convexDecomp = value; }) .def("set_import_inertia_tensor", [](ImportConfig& config, const bool value) { config.importInertiaTensor = value; }) .def("set_fix_base", [](ImportConfig& config, const bool value) { config.fixBase = value; }) // .def("set_flip_visuals", [](ImportConfig& config, const bool value) { config.flipVisuals = value; }) .def("set_self_collision", [](ImportConfig& config, const bool value) { config.selfCollision = value; }) .def("set_density", [](ImportConfig& config, const float value) { config.density = value; }) .def("set_default_drive_type", [](ImportConfig& config, const int value) { config.defaultDriveType = static_cast<UrdfJointTargetType>(value); }) .def("set_subdivision_scheme", [](ImportConfig& config, const int value) { config.subdivisionScheme = static_cast<UrdfNormalSubdivisionScheme>(value); }) .def("set_default_drive_strength", [](ImportConfig& config, const float value) { config.defaultDriveStrength = value; }) .def("set_default_position_drive_damping", [](ImportConfig& config, const float value) { config.defaultPositionDriveDamping = value; }) .def("set_distance_scale", [](ImportConfig& config, const float value) { config.distanceScale = value; }) .def("set_up_vector", [](ImportConfig& config, const float x, const float y, const float z) { config.upVector = { x, y, z }; }) .def("set_create_physics_scene", [](ImportConfig& config, const bool value) { config.createPhysicsScene = value; }) .def("set_make_default_prim", [](ImportConfig& config, const bool value) { config.makeDefaultPrim = value; }) .def("set_make_instanceable", [](ImportConfig& config, const bool value) { config.makeInstanceable = value; }) .def("set_instanceable_usd_path", [](ImportConfig& config, const std::string value) { config.instanceableMeshUsdPath = value; }) .def("set_collision_from_visuals", [](ImportConfig& config, const bool value) { config.collisionFromVisuals = value; }); py::class_<Vec3>(m, "Position", "") .def_readwrite("x", &Vec3::x, "") .def_readwrite("y", &Vec3::y, "") .def_readwrite("z", &Vec3::z, "") .def(py::init<>()); py::class_<Quat>(m, "Orientation", "") .def_readwrite("w", &Quat::w, "") .def_readwrite("x", &Quat::x, "") .def_readwrite("y", &Quat::y, "") .def_readwrite("z", &Quat::z, "") .def(py::init<>()); py::class_<Transform>(m, "UrdfOrigin", "") .def_readwrite("p", &Transform::p, "") .def_readwrite("q", &Transform::q, "") .def(py::init<>()); py::class_<UrdfInertia>(m, "UrdfInertia", "") .def_readwrite("ixx", &UrdfInertia::ixx, "") .def_readwrite("ixy", &UrdfInertia::ixy, "") .def_readwrite("ixz", &UrdfInertia::ixz, "") .def_readwrite("iyy", &UrdfInertia::iyy, "") .def_readwrite("iyz", &UrdfInertia::iyz, "") .def_readwrite("izz", &UrdfInertia::izz, "") .def(py::init<>()); py::class_<UrdfInertial>(m, "UrdfInertial", "") .def_readwrite("origin", &UrdfInertial::origin, "") .def_readwrite("mass", &UrdfInertial::mass, "") .def_readwrite("inertia", &UrdfInertial::inertia, "") .def_readwrite("has_origin", &UrdfInertial::hasOrigin, "") .def_readwrite("has_mass", &UrdfInertial::hasMass, "") .def_readwrite("has_inertia", &UrdfInertial::hasInertia, "") .def(py::init<>()); py::class_<UrdfAxis>(m, "UrdfAxis", "") .def_readwrite("x", &UrdfAxis::x, "") .def_readwrite("y", &UrdfAxis::y, "") .def_readwrite("z", &UrdfAxis::z, "") .def(py::init<>()); py::class_<UrdfColor>(m, "UrdfColor", "") .def_readwrite("r", &UrdfColor::r, "") .def_readwrite("g", &UrdfColor::g, "") .def_readwrite("b", &UrdfColor::b, "") .def_readwrite("a", &UrdfColor::a, "") .def(py::init<>()); py::enum_<UrdfJointType>(m, "UrdfJointType", py::arithmetic(), "") .value("JOINT_REVOLUTE", UrdfJointType::REVOLUTE) .value("JOINT_CONTINUOUS", UrdfJointType::CONTINUOUS) .value("JOINT_PRISMATIC", UrdfJointType::PRISMATIC) .value("JOINT_FIXED", UrdfJointType::FIXED) .value("JOINT_FLOATING", UrdfJointType::FLOATING) .value("JOINT_PLANAR", UrdfJointType::PLANAR) .export_values(); py::enum_<UrdfJointTargetType>(m, "UrdfJointTargetType", py::arithmetic(), "") .value("JOINT_DRIVE_NONE", UrdfJointTargetType::NONE) .value("JOINT_DRIVE_POSITION", UrdfJointTargetType::POSITION) .value("JOINT_DRIVE_VELOCITY", UrdfJointTargetType::VELOCITY) .export_values(); py::enum_<UrdfJointDriveType>(m, "UrdfJointDriveType", py::arithmetic(), "") .value("JOINT_DRIVE_ACCELERATION", UrdfJointDriveType::ACCELERATION) .value("JOINT_DRIVE_FORCE", UrdfJointDriveType::FORCE) .export_values(); py::class_<UrdfDynamics>(m, "UrdfDynamics", "") .def_readwrite("damping", &UrdfDynamics::damping, "") .def_readwrite("friction", &UrdfDynamics::friction, "") .def_readwrite("stiffness", &UrdfDynamics::stiffness, "") .def("set_damping", [](UrdfDynamics& drive, const float value) { drive.damping = value; }) .def("set_friction", [](UrdfDynamics& drive, const float value) { drive.friction = value; }) .def("set_stiffness", [](UrdfDynamics& drive, const float value) { drive.stiffness = value; }) .def(py::init<>()); py::class_<UrdfJointDrive>(m, "UrdfJointDrive", "") .def_readwrite("target", &UrdfJointDrive::target, "") .def_readwrite("target_type", &UrdfJointDrive::targetType, "") .def_readwrite("drive_type", &UrdfJointDrive::driveType, "") .def("set_target", [](UrdfJointDrive& drive, const float value) { drive.target = value; }) .def("set_target_type", [](UrdfJointDrive& drive, const int value) { drive.targetType = static_cast<UrdfJointTargetType>(value); }) .def("set_drive_type", [](UrdfJointDrive& drive, const int value) { drive.driveType = static_cast<UrdfJointDriveType>(value); }) .def(py::init<>()); py::class_<UrdfLimit>(m, "UrdfLimit", "") .def_readwrite("lower", &UrdfLimit::lower, "") .def_readwrite("upper", &UrdfLimit::upper, "") .def_readwrite("effort", &UrdfLimit::effort, "") .def_readwrite("velocity", &UrdfLimit::velocity, "") .def("set_lower", [](UrdfLimit& limit, const float value) { limit.lower = value; }) .def("set_upper", [](UrdfLimit& limit, const float value) { limit.upper = value; }) .def("set_effort", [](UrdfLimit& limit, const float value) { limit.effort = value; }) .def("set_velocity", [](UrdfLimit& limit, const float value) { limit.velocity = value; }) .def(py::init<>()); py::enum_<UrdfGeometryType>(m, "UrdfGeometryType", py::arithmetic(), "") .value("GEOMETRY_BOX", UrdfGeometryType::BOX) .value("GEOMETRY_CYLINDER", UrdfGeometryType::CYLINDER) .value("GEOMETRY_CAPSULE", UrdfGeometryType::CAPSULE) .value("GEOMETRY_SPHERE", UrdfGeometryType::SPHERE) .value("GEOMETRY_MESH", UrdfGeometryType::MESH) .export_values(); py::class_<UrdfGeometry>(m, "UrdfGeometry", "") .def_readwrite("type", &UrdfGeometry::type, "") .def_readwrite("size_x", &UrdfGeometry::size_x, "") .def_readwrite("size_y", &UrdfGeometry::size_y, "") .def_readwrite("size_z", &UrdfGeometry::size_z, "") .def_readwrite("radius", &UrdfGeometry::radius, "") .def_readwrite("length", &UrdfGeometry::length, "") .def_readwrite("scale_x", &UrdfGeometry::scale_x, "") .def_readwrite("scale_y", &UrdfGeometry::scale_y, "") .def_readwrite("scale_z", &UrdfGeometry::scale_z, "") .def_readwrite("mesh_file_path", &UrdfGeometry::meshFilePath, "") .def(py::init<>()); py::class_<UrdfMaterial>(m, "UrdfMaterial", "") .def_readwrite("name", &UrdfMaterial::name, "") .def_readwrite("color", &UrdfMaterial::color, "") .def_readwrite("texture_file_path", &UrdfMaterial::textureFilePath, "") .def(py::init<>()); py::class_<UrdfVisual>(m, "UrdfVisual", "") .def_readwrite("name", &UrdfVisual::name, "") .def_readwrite("origin", &UrdfVisual::origin, "") .def_readwrite("geometry", &UrdfVisual::geometry, "") .def_readwrite("material", &UrdfVisual::material, "") .def(py::init<>()); py::class_<UrdfCollision>(m, "UrdfCollision", "") .def_readwrite("name", &UrdfCollision::name, "") .def_readwrite("origin", &UrdfCollision::origin, "") .def_readwrite("geometry", &UrdfCollision::geometry, "") .def(py::init<>()); py::class_<UrdfLink>(m, "UrdfLink", "") .def_readwrite("name", &UrdfLink::name, "") .def_readwrite("inertial", &UrdfLink::inertial, "") .def_readwrite("visuals", &UrdfLink::visuals, "") .def_readwrite("collisions", &UrdfLink::collisions, "") .def(py::init<>()); py::class_<UrdfJoint>(m, "UrdfJoint", "") .def_readwrite("name", &UrdfJoint::name, "") .def_readwrite("type", &UrdfJoint::type, "") .def_readwrite("origin", &UrdfJoint::origin, "") .def_readwrite("parent_link_name", &UrdfJoint::parentLinkName, "") .def_readwrite("child_link_name", &UrdfJoint::childLinkName, "") .def_readwrite("axis", &UrdfJoint::axis, "") .def_readwrite("dynamics", &UrdfJoint::dynamics, "") .def_readwrite("limit", &UrdfJoint::limit, "") .def_readwrite("drive", &UrdfJoint::drive, "") .def(py::init<>()); py::class_<UrdfRobot>(m, "UrdfRobot", "") .def_readwrite("name", &UrdfRobot::name, "") .def_readwrite("links", &UrdfRobot::links, "") .def_readwrite("joints", &UrdfRobot::joints, "") .def_readwrite("materials", &UrdfRobot::materials, "") .def(py::init<>()); declare_map<UrdfLink>(m, std::string("UrdfLinkMap")); declare_map<UrdfJoint>(m, std::string("UrdfJointMap")); declare_map<UrdfMaterial>(m, std::string("UrdfMaterialMap")); defineInterfaceClass<Urdf>(m, "Urdf", "acquire_urdf_interface", "release_urdf_interface") .def("parse_urdf", wrapInterfaceFunction(&Urdf::parseUrdf), R"pbdoc( Parse URDF file into the internal data structure, which is displayed in the importer window for inspection. Args: arg0 (:obj:`str`): The absolute path to where the urdf file is arg1 (:obj:`str`): The name of the urdf file arg2 (:obj:`omni.importer.urdf._urdf.ImportConfig`): Import configuration parameters Returns: :obj:`omni.importer.urdf._urdf.UrdfRobot`: Parsed URDF stored in an internal structure. )pbdoc") .def("import_robot", wrapInterfaceFunction(&Urdf::importRobot), py::arg("assetRoot"), py::arg("assetName"), py::arg("robot"), py::arg("importConfig"), py::arg("stage") = std::string(""), R"pbdoc( Importing the robot, from the already parsed URDF file. Args: arg0 (:obj:`str`): The absolute path to where the urdf file is arg1 (:obj:`str`): The name of the urdf file arg2 (:obj:`omni.importer.urdf._urdf.UrdfRobot`): The parsed URDF file, the output from :obj:`parse_urdf` arg3 (:obj:`omni.importer.urdf._urdf.ImportConfig`): Import configuration parameters arg4 (:obj:`str`): optional: path to stage to use for importing. leaving it empty will import on open stage. If the open stage is a new stage, textures will not load. Returns: :obj:`str`: Path to the robot on the USD stage. )pbdoc") .def("get_kinematic_chain", wrapInterfaceFunction(&Urdf::getKinematicChain), R"pbdoc( Get the kinematic chain of the robot. Mostly used for graphic display of the kinematic tree. Args: arg0 (:obj:`omni.importer.urdf._urdf.UrdfRobot`): The parsed URDF, the output from :obj:`parse_urdf` Returns: :obj:`dict`: A dictionary with information regarding the parent-child relationship between all the links and joints )pbdoc"); } }
19,097
C++
48.348837
186
0.605331
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/config/extension.toml
[core] reloadable = true order = 0 [package] version = "1.1.4" category = "Simulation" title = "Omniverse URDF Importer" description = "URDF Importer" repository = "https://github.com/NVIDIA-Omniverse/urdf-importer-extension" authors = ["Isaac Sim Team"] keywords = ["urdf", "importer", "isaac"] changelog = "docs/CHANGELOG.md" readme = "docs/Overview.md" icon = "data/icon.png" writeTarget.kit = true preview_image = "data/preview.png" [dependencies] "omni.kit.commands" = {} "omni.kit.uiapp" = {} "omni.kit.window.filepicker" = {} "omni.kit.window.content_browser" = {} "omni.kit.viewport.utility" = {} "omni.kit.pip_archive" = {} # pulls in pillow "omni.physx" = {} "omni.kit.window.extensions" = {} "omni.kit.window.property" = {} [[python.module]] name = "omni.importer.urdf" [[python.module]] name = "omni.importer.urdf.tests" [[python.module]] name = "omni.importer.urdf.scripts.ui" [[python.module]] name = "omni.importer.urdf.scripts.samples.import_carter" [[python.module]] name = "omni.importer.urdf.scripts.samples.import_franka" [[python.module]] name = "omni.importer.urdf.scripts.samples.import_kaya" [[python.module]] name = "omni.importer.urdf.scripts.samples.import_ur10" [[native.plugin]] path = "bin/*.plugin" recursive = false [[test]] # this is to catch issues where our assimp is out of sync with the one that comes with # asset importer as this can cause segfaults due to binary incompatibility. dependencies = ["omni.kit.tool.asset_importer"] stdoutFailPatterns.exclude = [ "*extension object is still alive, something holds a reference on it*", # exclude warning as failure ] args = ["--/app/file/ignoreUnsavedOnExit=1"] [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
1,741
TOML
23.885714
104
0.709937
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/Urdf.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "UrdfTypes.h" #include <carb/Defines.h> #include <pybind11/pybind11.h> #include <stdint.h> namespace omni { namespace importer { namespace urdf { struct ImportConfig { bool mergeFixedJoints = false; bool replaceCylindersWithCapsules = false; bool convexDecomp = false; bool importInertiaTensor = false; bool fixBase = true; bool selfCollision = false; float density = 0.0f; // default density used for objects without mass/inertia, 0 to autocompute UrdfJointTargetType defaultDriveType = UrdfJointTargetType::POSITION; float defaultDriveStrength = 1e7f; float defaultPositionDriveDamping = 1e5f; float distanceScale = 1.0f; UrdfAxis upVector = { 0.0f, 0.0f, 1.0f }; bool createPhysicsScene = false; bool makeDefaultPrim = false; UrdfNormalSubdivisionScheme subdivisionScheme = UrdfNormalSubdivisionScheme::BILINEAR; // bool flipVisuals = false; bool makeInstanceable = false; std::string instanceableMeshUsdPath = "./instanceable_meshes.usd"; bool collisionFromVisuals = false; // Create collision geometry from visual geometry when missing collision. }; struct Urdf { CARB_PLUGIN_INTERFACE("omni::importer::urdf::Urdf", 0, 1); // Parses a urdf file into a UrdfRobot data structure UrdfRobot(CARB_ABI* parseUrdf)(const std::string& assetRoot, const std::string& assetName, ImportConfig& importConfig); // Imports a UrdfRobot into the stage std::string(CARB_ABI* importRobot)(const std::string& assetRoot, const std::string& assetName, const UrdfRobot& robot, ImportConfig& importConfig, const std::string& stage); pybind11::dict(CARB_ABI* getKinematicChain)(const UrdfRobot& robot); }; } } }
2,576
C
32.467532
123
0.694876
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/UsdPCH.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once // !!! DO NOT INCLUDE THIS FILE IN A HEADER !!! // When you include this file in a cpp file, add the file name to premake5.lua's pchFiles list! // The usd headers drag in heavy dependencies and are very slow to build. // Make it PCH to speed up building time. #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4244) // = Conversion from double to float / int to float # pragma warning(disable : 4267) // conversion from size_t to int # pragma warning(disable : 4305) // argument truncation from double to float # pragma warning(disable : 4800) // int to bool # pragma warning(disable : 4996) // call to std::copy with parameters that may be unsafe # define NOMINMAX // Make sure nobody #defines min or max # include <Windows.h> // Include this here so we can curate # undef small // defined in rpcndr.h #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" # pragma GCC diagnostic ignored "-Wunused-local-typedefs" # pragma GCC diagnostic ignored "-Wunused-function" // This suppresses deprecated header warnings, which is impossible with pragmas. // Alternative is to specify -Wno-deprecated build option, but that disables other useful warnings too. # ifdef __DEPRECATED # define OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS # undef __DEPRECATED # endif #endif #define BOOST_PYTHON_STATIC_LIB // Include cstdio here so that vsnprintf is properly declared. This is necessary because pyerrors.h has // #define vsnprintf _vsnprintf which later causes <cstdio> to declare std::_vsnprintf instead of the correct and proper // std::vsnprintf. By doing it here before everything else, we avoid this nonsense. #include <cstdio> // Python must be included first because it monkeys with macros that cause // TBB to fail to compile in debug mode if TBB is included before Python #include <boost/python/object.hpp> #include <pxr/base/arch/stackTrace.h> #include <pxr/base/arch/threads.h> #include <pxr/base/gf/api.h> #include <pxr/base/gf/camera.h> #include <pxr/base/gf/frustum.h> #include <pxr/base/gf/matrix3f.h> #include <pxr/base/gf/matrix4d.h> #include <pxr/base/gf/matrix4f.h> #include <pxr/base/gf/quaternion.h> #include <pxr/base/gf/rotation.h> #include <pxr/base/gf/transform.h> #include <pxr/base/gf/vec2f.h> #include <pxr/base/plug/notice.h> #include <pxr/base/plug/plugin.h> #include <pxr/base/tf/hashmap.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/base/tf/token.h> #include <pxr/base/trace/reporter.h> #include <pxr/base/trace/trace.h> #include <pxr/base/vt/value.h> #include <pxr/base/work/loops.h> #include <pxr/base/work/threadLimits.h> #include <pxr/imaging/hd/basisCurves.h> #include <pxr/imaging/hd/camera.h> #include <pxr/imaging/hd/engine.h> #include <pxr/imaging/hd/extComputation.h> #include <pxr/imaging/hd/flatNormals.h> #include <pxr/imaging/hd/instancer.h> #include <pxr/imaging/hd/light.h> #include <pxr/imaging/hd/material.h> #include <pxr/imaging/hd/mesh.h> #include <pxr/imaging/hd/meshUtil.h> #include <pxr/imaging/hd/points.h> #include <pxr/imaging/hd/renderBuffer.h> #include <pxr/imaging/hd/renderIndex.h> #include <pxr/imaging/hd/renderPass.h> #include <pxr/imaging/hd/renderPassState.h> #include <pxr/imaging/hd/rendererPluginRegistry.h> #include <pxr/imaging/hd/resourceRegistry.h> #include <pxr/imaging/hd/rprim.h> #include <pxr/imaging/hd/smoothNormals.h> #include <pxr/imaging/hd/sprim.h> #include <pxr/imaging/hd/vertexAdjacency.h> #include <pxr/imaging/hdx/tokens.h> #include <pxr/imaging/pxOsd/tokens.h> #include <pxr/usd/ar/resolver.h> #include <pxr/usd/ar/resolverContext.h> #include <pxr/usd/ar/resolverContextBinder.h> #include <pxr/usd/ar/resolverScopedCache.h> #include <pxr/usd/kind/registry.h> #include <pxr/usd/pcp/layerStack.h> #include <pxr/usd/pcp/site.h> #include <pxr/usd/sdf/attributeSpec.h> #include <pxr/usd/sdf/changeList.h> #include <pxr/usd/sdf/copyUtils.h> #include <pxr/usd/sdf/fileFormat.h> #include <pxr/usd/sdf/layerStateDelegate.h> #include <pxr/usd/sdf/layerUtils.h> #include <pxr/usd/sdf/relationshipSpec.h> #include <pxr/usd/usd/attribute.h> #include <pxr/usd/usd/editContext.h> #include <pxr/usd/usd/modelAPI.h> #include <pxr/usd/usd/notice.h> #include <pxr/usd/usd/primRange.h> #include <pxr/usd/usd/relationship.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/stageCache.h> #include <pxr/usd/usd/usdFileFormat.h> #include <pxr/usd/usdGeom/basisCurves.h> #include <pxr/usd/usdGeom/camera.h> #include <pxr/usd/usdGeom/capsule.h> #include <pxr/usd/usdGeom/cone.h> #include <pxr/usd/usdGeom/cube.h> #include <pxr/usd/usdGeom/cylinder.h> #include <pxr/usd/usdGeom/mesh.h> #include <pxr/usd/usdGeom/metrics.h> #include <pxr/usd/usdGeom/points.h> #include <pxr/usd/usdGeom/primvarsAPI.h> #include <pxr/usd/usdGeom/scope.h> #include <pxr/usd/usdGeom/sphere.h> #include <pxr/usd/usdGeom/subset.h> #include <pxr/usd/usdGeom/xform.h> #include <pxr/usd/usdGeom/xformCommonAPI.h> #include <pxr/usd/usdLux/cylinderLight.h> #include <pxr/usd/usdLux/diskLight.h> #include <pxr/usd/usdLux/distantLight.h> #include <pxr/usd/usdLux/domeLight.h> #include <pxr/usd/usdLux/rectLight.h> #include <pxr/usd/usdLux/sphereLight.h> #include <pxr/usd/usdLux/tokens.h> #include <pxr/usd/usdShade/tokens.h> #include <pxr/usd/usdSkel/animation.h> #include <pxr/usd/usdSkel/root.h> #include <pxr/usd/usdSkel/skeleton.h> #include <pxr/usd/usdSkel/tokens.h> #include <pxr/usd/usdUtils/stageCache.h> #include <pxr/usdImaging/usdImaging/delegate.h> // -- Hydra #include <pxr/imaging/hd/renderDelegate.h> #include <pxr/imaging/hd/renderIndex.h> #include <pxr/imaging/hd/rendererPlugin.h> #include <pxr/imaging/hd/sceneDelegate.h> #include <pxr/imaging/hd/tokens.h> #include <pxr/imaging/hdx/taskController.h> #include <pxr/usdImaging/usdImaging/gprimAdapter.h> #include <pxr/usdImaging/usdImaging/indexProxy.h> #include <pxr/usdImaging/usdImaging/tokens.h> // -- nv extensions //#include <audioSchema/sound.h> // -- omni.usd #include <omni/usd/UsdContextIncludes.h> #include <omni/usd/UtilsIncludes.h> #ifdef _MSC_VER # pragma warning(pop) #elif defined(__GNUC__) # pragma GCC diagnostic pop # ifdef OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS # define __DEPRECATED # undef OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS # endif #endif
7,044
C
37.288043
120
0.747871
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/Urdf.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #define CARB_EXPORTS // clang-format off #include "UsdPCH.h" // clang-format on #include "import/ImportHelpers.h" #include "import/UrdfImporter.h" #include "Urdf.h" #include <carb/PluginUtils.h> #include <carb/logging/Log.h> #include <omni/ext/IExt.h> #include <omni/kit/IApp.h> #include <omni/kit/IStageUpdate.h> #include <pybind11/pybind11.h> #include <fstream> #include <memory> using namespace carb; const struct carb::PluginImplDesc kPluginImpl = { "omni.importer.urdf", "URDF Utilities", "NVIDIA", carb::PluginHotReload::eEnabled, "dev" }; CARB_PLUGIN_IMPL(kPluginImpl, omni::importer::urdf::Urdf) CARB_PLUGIN_IMPL_DEPS(omni::kit::IApp, carb::logging::ILogging) namespace { omni::importer::urdf::UrdfRobot parseUrdf(const std::string& assetRoot, const std::string& assetName, omni::importer::urdf::ImportConfig& importConfig) { omni::importer::urdf::UrdfRobot robot; std::string filename = assetRoot + "/" + assetName; { CARB_LOG_INFO("Trying to import %s", filename.c_str()); if (parseUrdf(assetRoot, assetName, robot)) { } else { CARB_LOG_ERROR("Failed to parse URDF file '%s'", assetName.c_str()); return robot; } if (importConfig.mergeFixedJoints) { collapseFixedJoints(robot); } if (importConfig.collisionFromVisuals) { addVisualMeshToCollision(robot); } for (auto& joint : robot.joints) { joint.second.drive.targetType = importConfig.defaultDriveType; if (joint.second.drive.targetType == omni::importer::urdf::UrdfJointTargetType::POSITION) { // set position gain if (importConfig.defaultDriveStrength > 0) { joint.second.dynamics.stiffness = importConfig.defaultDriveStrength; } // set velocity gain if (importConfig.defaultPositionDriveDamping > 0) { joint.second.dynamics.damping = importConfig.defaultPositionDriveDamping; } } else if (joint.second.drive.targetType == omni::importer::urdf::UrdfJointTargetType::VELOCITY) { // set position gain joint.second.dynamics.stiffness = 0.0f; // set velocity gain if (importConfig.defaultDriveStrength > 0) { joint.second.dynamics.damping = importConfig.defaultDriveStrength; } } else if (joint.second.drive.targetType == omni::importer::urdf::UrdfJointTargetType::NONE) { // set both gains to 0 joint.second.dynamics.stiffness = 0.0f; joint.second.dynamics.damping = 0.0f; } else { CARB_LOG_ERROR("Unknown drive target type %d", (int)joint.second.drive.targetType); } } } return robot; } std::string importRobot(const std::string& assetRoot, const std::string& assetName, const omni::importer::urdf::UrdfRobot& robot, omni::importer::urdf::ImportConfig& importConfig, const std::string& stage_identifier = "") { omni::importer::urdf::UrdfImporter urdfImporter(assetRoot, assetName, importConfig); bool save_stage = true; pxr::UsdStageRefPtr _stage; if (stage_identifier != "" && pxr::UsdStage::IsSupportedFile(stage_identifier)) { _stage = pxr::UsdStage::Open(stage_identifier); if (!_stage) { CARB_LOG_INFO("Creating Stage: %s", stage_identifier.c_str()); _stage = pxr::UsdStage::CreateNew(stage_identifier); } else { for (const auto& p : _stage->GetPrimAtPath(pxr::SdfPath("/")).GetChildren()) { _stage->RemovePrim(p.GetPath()); } } importConfig.makeDefaultPrim = true; pxr::UsdGeomSetStageUpAxis(_stage, pxr::UsdGeomTokens->z); } if (!_stage) // If all else fails, import on current stage { CARB_LOG_INFO("Importing URDF to Current Stage"); // Get the 'active' USD stage from the USD stage cache. const std::vector<pxr::UsdStageRefPtr> allStages = pxr::UsdUtilsStageCache::Get().GetAllStages(); if (allStages.size() != 1) { CARB_LOG_ERROR("Cannot determine the 'active' USD stage (%zu stages present in the USD stage cache).", allStages.size()); return ""; } _stage = allStages[0]; save_stage = false; } std::string result = ""; if (_stage) { pxr::UsdGeomSetStageMetersPerUnit(_stage, 1.0 / importConfig.distanceScale); result = urdfImporter.addToStage(_stage, robot); // CARB_LOG_WARN("Import Done, saving"); if (save_stage) { // CARB_LOG_WARN("Saving Stage %s", _stage->GetRootLayer()->GetIdentifier().c_str()); _stage->Save(); } } else { CARB_LOG_ERROR("Stage pointer not valid, could not import urdf to stage"); } return result; } } pybind11::list addLinksAndJoints(omni::importer::urdf::KinematicChain::Node* parentNode) { if (parentNode->parentJointName_ == "") { } pybind11::list temp_list; if (!parentNode->childNodes_.empty()) { for (const auto& childNode : parentNode->childNodes_) { pybind11::dict temp; temp["A_joint"] = childNode->parentJointName_; temp["A_link"] = parentNode->linkName_; temp["B_link"] = childNode->linkName_; temp["B_node"] = addLinksAndJoints(childNode.get()); temp_list.append(temp); } } return temp_list; } pybind11::dict getKinematicChain(const omni::importer::urdf::UrdfRobot& robot) { pybind11::dict robotDict; omni::importer::urdf::KinematicChain chain; if (chain.computeKinematicChain(robot)) { robotDict["A_joint"] = ""; robotDict["B_link"] = chain.baseNode->linkName_; robotDict["B_node"] = addLinksAndJoints(chain.baseNode.get()); } return robotDict; } CARB_EXPORT void carbOnPluginStartup() { CARB_LOG_INFO("Startup URDF Extension"); } CARB_EXPORT void carbOnPluginShutdown() { } void fillInterface(omni::importer::urdf::Urdf& iface) { using namespace omni::importer::urdf; memset(&iface, 0, sizeof(iface)); iface.parseUrdf = parseUrdf; iface.importRobot = importRobot; iface.getKinematicChain = getKinematicChain; }
7,554
C++
31.012712
133
0.59121
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/UrdfTypes.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "math/core/maths.h" #include <float.h> #include <iostream> #include <map> #include <string> #include <vector> namespace omni { namespace importer { namespace urdf { // The default values and data structures are mostly the same as defined in the official URDF documentation // http://wiki.ros.org/urdf/XML struct UrdfInertia { float ixx = 0.0f; float ixy = 0.0f; float ixz = 0.0f; float iyy = 0.0f; float iyz = 0.0f; float izz = 0.0f; }; struct UrdfInertial { Transform origin; // This is the pose of the inertial reference frame, relative to the link reference frame. The // origin of the inertial reference frame needs to be at the center of gravity float mass = 0.0f; UrdfInertia inertia; bool hasOrigin = false; bool hasMass = false; // Whether the inertial field defined a mass bool hasInertia = false; // Whether the inertial field defined an inertia }; struct UrdfAxis { float x = 1.0f; float y = 0.0f; float z = 0.0f; }; // By Default a UrdfColor struct will have an invalid color unless it was found in the xml struct UrdfColor { float r = -1.0f; float g = -1.0f; float b = -1.0f; float a = 1.0f; }; enum class UrdfJointType { REVOLUTE = 0, // A hinge joint that rotates along the axis and has a limited range specified by the upper and lower // limits CONTINUOUS = 1, // A continuous hinge joint that rotates around the axis and has no upper and lower limits PRISMATIC = 2, // A sliding joint that slides along the axis, and has a limited range specified by the upper and // lower limits FIXED = 3, // this is not really a joint because it cannot move. All degrees of freedom are locked. This type of // joint does not require the axis, calibration, dynamics, limits or safety_controller FLOATING = 4, // This joint allows motion for all 6 degrees of freedom PLANAR = 5 // This joint allows motion in a plane perpendicular to the axis }; enum class UrdfJointTargetType { NONE = 0, POSITION = 1, VELOCITY = 2 }; enum class UrdfNormalSubdivisionScheme { CATMULLCLARK = 0, LOOP = 1, BILINEAR = 2, NONE = 3 }; enum class UrdfJointDriveType { ACCELERATION = 0, FORCE = 2 }; struct UrdfDynamics { float damping = 0.0f; float friction = 0.0f; float stiffness = 0.0f; }; struct UrdfJointDrive { float target = 0.0; UrdfJointTargetType targetType = UrdfJointTargetType::POSITION; UrdfJointDriveType driveType = UrdfJointDriveType::FORCE; }; struct UrdfJointMimic { std::string joint = ""; float multiplier; float offset; }; struct UrdfLimit { float lower = -FLT_MAX; // An attribute specifying the lower joint limit (radians for revolute joints, meters for // prismatic joints) float upper = FLT_MAX; // An attribute specifying the upper joint limit (radians for revolute joints, meters for // prismatic joints) float effort = FLT_MAX; // An attribute for enforcing the maximum joint effort float velocity = FLT_MAX; // An attribute for enforcing the maximum joint velocity }; enum class UrdfGeometryType { BOX = 0, CYLINDER = 1, CAPSULE = 2, SPHERE = 3, MESH = 4 }; struct UrdfGeometry { UrdfGeometryType type; // Box float size_x = 0.0f; float size_y = 0.0f; float size_z = 0.0f; // Cylinder and Sphere float radius = 0.0f; float length = 0.0f; // Mesh float scale_x = 1.0f; float scale_y = 1.0f; float scale_z = 1.0f; std::string meshFilePath; }; struct UrdfMaterial { std::string name; UrdfColor color; std::string textureFilePath; }; struct UrdfVisual { std::string name; Transform origin; // The reference frame of the visual element with respect to the reference frame of the link UrdfGeometry geometry; UrdfMaterial material; }; struct UrdfCollision { std::string name; Transform origin; // The reference frame of the collision element, relative to the reference frame of the link UrdfGeometry geometry; }; struct UrdfLink { std::string name; UrdfInertial inertial; std::vector<UrdfVisual> visuals; std::vector<UrdfCollision> collisions; std::map<std::string, Transform> mergedChildren; }; struct UrdfJoint { std::string name; UrdfJointType type; Transform origin; // This is the transform from the parent link to the child link. The joint is located at the // origin of the child link std::string parentLinkName; std::string childLinkName; UrdfAxis axis; UrdfDynamics dynamics; UrdfLimit limit; UrdfJointDrive drive; UrdfJointMimic mimic; std::map<std::string, float> mimicChildren; bool dontCollapse = false; // This is a custom attribute that is used to prevent the child link from being // collapsed into the parent link when a fixed joint is used. It is used when user // enables "merging of fixed joints" but does not want to merge this particular joint. // For example: for sensor or end-effector frames. // Note: The tag is not part of the URDF specification. Rather it is a custom tag // that was first introduced in Isaac Gym for the purpose of merging fixed joints. }; struct UrdfRobot { std::string name; std::map<std::string, UrdfLink> links; std::map<std::string, UrdfJoint> joints; std::map<std::string, UrdfMaterial> materials; }; } // namespace urdf } }
6,415
C
26.774892
119
0.66516
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/mat33.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "common_math.h" #include "quat.h" #include "vec3.h" struct Matrix33 { CUDA_CALLABLE Matrix33() { } CUDA_CALLABLE Matrix33(const float* ptr) { cols[0].x = ptr[0]; cols[0].y = ptr[1]; cols[0].z = ptr[2]; cols[1].x = ptr[3]; cols[1].y = ptr[4]; cols[1].z = ptr[5]; cols[2].x = ptr[6]; cols[2].y = ptr[7]; cols[2].z = ptr[8]; } CUDA_CALLABLE Matrix33(const Vec3& c1, const Vec3& c2, const Vec3& c3) { cols[0] = c1; cols[1] = c2; cols[2] = c3; } CUDA_CALLABLE Matrix33(const Quat& q) { cols[0] = Rotate(q, Vec3(1.0f, 0.0f, 0.0f)); cols[1] = Rotate(q, Vec3(0.0f, 1.0f, 0.0f)); cols[2] = Rotate(q, Vec3(0.0f, 0.0f, 1.0f)); } CUDA_CALLABLE float operator()(int i, int j) const { return static_cast<const float*>(cols[j])[i]; } CUDA_CALLABLE float& operator()(int i, int j) { return static_cast<float*>(cols[j])[i]; } Vec3 cols[3]; CUDA_CALLABLE static inline Matrix33 Identity() { const Matrix33 sIdentity(Vec3(1.0f, 0.0f, 0.0f), Vec3(0.0f, 1.0f, 0.0f), Vec3(0.0f, 0.0f, 1.0f)); return sIdentity; } }; CUDA_CALLABLE inline Matrix33 Multiply(float s, const Matrix33& m) { Matrix33 r = m; r.cols[0] *= s; r.cols[1] *= s; r.cols[2] *= s; return r; } CUDA_CALLABLE inline Vec3 Multiply(const Matrix33& a, const Vec3& x) { return a.cols[0] * x.x + a.cols[1] * x.y + a.cols[2] * x.z; } CUDA_CALLABLE inline Vec3 operator*(const Matrix33& a, const Vec3& x) { return Multiply(a, x); } CUDA_CALLABLE inline Matrix33 Multiply(const Matrix33& a, const Matrix33& b) { Matrix33 r; r.cols[0] = a * b.cols[0]; r.cols[1] = a * b.cols[1]; r.cols[2] = a * b.cols[2]; return r; } CUDA_CALLABLE inline Matrix33 Add(const Matrix33& a, const Matrix33& b) { return Matrix33(a.cols[0] + b.cols[0], a.cols[1] + b.cols[1], a.cols[2] + b.cols[2]); } CUDA_CALLABLE inline float Determinant(const Matrix33& m) { return Dot(m.cols[0], Cross(m.cols[1], m.cols[2])); } CUDA_CALLABLE inline Matrix33 Transpose(const Matrix33& a) { Matrix33 r; for (uint32_t i = 0; i < 3; ++i) for (uint32_t j = 0; j < 3; ++j) r(i, j) = a(j, i); return r; } CUDA_CALLABLE inline float Trace(const Matrix33& a) { return a(0, 0) + a(1, 1) + a(2, 2); } CUDA_CALLABLE inline Matrix33 Outer(const Vec3& a, const Vec3& b) { return Matrix33(a * b.x, a * b.y, a * b.z); } CUDA_CALLABLE inline Matrix33 Inverse(const Matrix33& a, bool& success) { float s = Determinant(a); const float eps = 0.0f; if (fabsf(s) > eps) { Matrix33 b; b(0, 0) = a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1); b(0, 1) = a(0, 2) * a(2, 1) - a(0, 1) * a(2, 2); b(0, 2) = a(0, 1) * a(1, 2) - a(0, 2) * a(1, 1); b(1, 0) = a(1, 2) * a(2, 0) - a(1, 0) * a(2, 2); b(1, 1) = a(0, 0) * a(2, 2) - a(0, 2) * a(2, 0); b(1, 2) = a(0, 2) * a(1, 0) - a(0, 0) * a(1, 2); b(2, 0) = a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0); b(2, 1) = a(0, 1) * a(2, 0) - a(0, 0) * a(2, 1); b(2, 2) = a(0, 0) * a(1, 1) - a(0, 1) * a(1, 0); success = true; return Multiply(1.0f / s, b); } else { success = false; return Matrix33(); } } CUDA_CALLABLE inline Matrix33 InverseDouble(const Matrix33& a, bool& success) { double m[3][3]; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) m[i][j] = a(i, j); double det = m[0][0] * (m[2][2] * m[1][1] - m[2][1] * m[1][2]) - m[1][0] * (m[2][2] * m[0][1] - m[2][1] * m[0][2]) + m[2][0] * (m[1][2] * m[0][1] - m[1][1] * m[0][2]); const double eps = 0.0f; if (fabs(det) > eps) { double b[3][3]; b[0][0] = m[1][1] * m[2][2] - m[1][2] * m[2][1]; b[0][1] = m[0][2] * m[2][1] - m[0][1] * m[2][2]; b[0][2] = m[0][1] * m[1][2] - m[0][2] * m[1][1]; b[1][0] = m[1][2] * m[2][0] - m[1][0] * m[2][2]; b[1][1] = m[0][0] * m[2][2] - m[0][2] * m[2][0]; b[1][2] = m[0][2] * m[1][0] - m[0][0] * m[1][2]; b[2][0] = m[1][0] * m[2][1] - m[1][1] * m[2][0]; b[2][1] = m[0][1] * m[2][0] - m[0][0] * m[2][1]; b[2][2] = m[0][0] * m[1][1] - m[0][1] * m[1][0]; success = true; double invDet = 1.0 / det; Matrix33 out; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) out(i, j) = (float)(b[i][j] * invDet); return out; } else { success = false; Matrix33 out; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) out(i, j) = 0.0f; return out; } } CUDA_CALLABLE inline Matrix33 operator*(float s, const Matrix33& a) { return Multiply(s, a); } CUDA_CALLABLE inline Matrix33 operator*(const Matrix33& a, float s) { return Multiply(s, a); } CUDA_CALLABLE inline Matrix33 operator*(const Matrix33& a, const Matrix33& b) { return Multiply(a, b); } CUDA_CALLABLE inline Matrix33 operator+(const Matrix33& a, const Matrix33& b) { return Add(a, b); } CUDA_CALLABLE inline Matrix33 operator-(const Matrix33& a, const Matrix33& b) { return Add(a, -1.0f * b); } CUDA_CALLABLE inline Matrix33& operator+=(Matrix33& a, const Matrix33& b) { a = a + b; return a; } CUDA_CALLABLE inline Matrix33& operator-=(Matrix33& a, const Matrix33& b) { a = a - b; return a; } CUDA_CALLABLE inline Matrix33& operator*=(Matrix33& a, float s) { a.cols[0] *= s; a.cols[1] *= s; a.cols[2] *= s; return a; } CUDA_CALLABLE inline Matrix33 Skew(const Vec3& v) { return Matrix33(Vec3(0.0f, v.z, -v.y), Vec3(-v.z, 0.0f, v.x), Vec3(v.y, -v.x, 0.0f)); } template <typename T> CUDA_CALLABLE inline XQuat<T>::XQuat(const Matrix33& m) { float tr = m(0, 0) + m(1, 1) + m(2, 2), h; if (tr >= 0) { h = sqrtf(tr + 1); w = 0.5f * h; h = 0.5f / h; x = (m(2, 1) - m(1, 2)) * h; y = (m(0, 2) - m(2, 0)) * h; z = (m(1, 0) - m(0, 1)) * h; } else { unsigned int i = 0; if (m(1, 1) > m(0, 0)) i = 1; if (m(2, 2) > m(i, i)) i = 2; switch (i) { case 0: h = sqrtf((m(0, 0) - (m(1, 1) + m(2, 2))) + 1); x = 0.5f * h; h = 0.5f / h; y = (m(0, 1) + m(1, 0)) * h; z = (m(2, 0) + m(0, 2)) * h; w = (m(2, 1) - m(1, 2)) * h; break; case 1: h = sqrtf((m(1, 1) - (m(2, 2) + m(0, 0))) + 1); y = 0.5f * h; h = 0.5f / h; z = (m(1, 2) + m(2, 1)) * h; x = (m(0, 1) + m(1, 0)) * h; w = (m(0, 2) - m(2, 0)) * h; break; case 2: h = sqrtf((m(2, 2) - (m(0, 0) + m(1, 1))) + 1); z = 0.5f * h; h = 0.5f / h; x = (m(2, 0) + m(0, 2)) * h; y = (m(1, 2) + m(2, 1)) * h; w = (m(1, 0) - m(0, 1)) * h; break; default: // Make compiler happy x = y = z = w = 0; break; } } *this = Normalize(*this); } CUDA_CALLABLE inline void quat2Mat(const XQuat<float>& q, Matrix33& m) { float sqx = q.x * q.x; float sqy = q.y * q.y; float sqz = q.z * q.z; float squ = q.w * q.w; float s = 1.f / (sqx + sqy + sqz + squ); m(0, 0) = 1.f - 2.f * s * (sqy + sqz); m(0, 1) = 2.f * s * (q.x * q.y - q.z * q.w); m(0, 2) = 2.f * s * (q.x * q.z + q.y * q.w); m(1, 0) = 2.f * s * (q.x * q.y + q.z * q.w); m(1, 1) = 1.f - 2.f * s * (sqx + sqz); m(1, 2) = 2.f * s * (q.y * q.z - q.x * q.w); m(2, 0) = 2.f * s * (q.x * q.z - q.y * q.w); m(2, 1) = 2.f * s * (q.y * q.z + q.x * q.w); m(2, 2) = 1.f - 2.f * s * (sqx + sqy); } // rotation is using new rotation axis // rotation: Rx(X)*Ry(Y)*Rz(Z) CUDA_CALLABLE inline void getEulerXYZ(const XQuat<float>& q, float& X, float& Y, float& Z) { Matrix33 rot; quat2Mat(q, rot); float cy = sqrtf(rot(2, 2) * rot(2, 2) + rot(1, 2) * rot(1, 2)); if (cy > 1e-6f) { Z = -atan2(rot(0, 1), rot(0, 0)); Y = -atan2(-rot(0, 2), cy); X = -atan2(rot(1, 2), rot(2, 2)); } else { Z = -atan2(-rot(1, 0), rot(1, 1)); Y = -atan2(-rot(0, 2), cy); X = 0.0f; } }
9,245
C
24.826816
120
0.466414
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/mat22.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "common_math.h" #include "vec2.h" struct Matrix22 { CUDA_CALLABLE Matrix22() { } CUDA_CALLABLE Matrix22(float a, float b, float c, float d) { cols[0] = Vec2(a, c); cols[1] = Vec2(b, d); } CUDA_CALLABLE Matrix22(const Vec2& c1, const Vec2& c2) { cols[0] = c1; cols[1] = c2; } CUDA_CALLABLE float operator()(int i, int j) const { return static_cast<const float*>(cols[j])[i]; } CUDA_CALLABLE float& operator()(int i, int j) { return static_cast<float*>(cols[j])[i]; } Vec2 cols[2]; static inline Matrix22 Identity() { static const Matrix22 sIdentity(Vec2(1.0f, 0.0f), Vec2(0.0f, 1.0f)); return sIdentity; } }; CUDA_CALLABLE inline Matrix22 Multiply(float s, const Matrix22& m) { Matrix22 r = m; r.cols[0] *= s; r.cols[1] *= s; return r; } CUDA_CALLABLE inline Matrix22 Multiply(const Matrix22& a, const Matrix22& b) { Matrix22 r; r.cols[0] = a.cols[0] * b.cols[0].x + a.cols[1] * b.cols[0].y; r.cols[1] = a.cols[0] * b.cols[1].x + a.cols[1] * b.cols[1].y; return r; } CUDA_CALLABLE inline Matrix22 Add(const Matrix22& a, const Matrix22& b) { return Matrix22(a.cols[0] + b.cols[0], a.cols[1] + b.cols[1]); } CUDA_CALLABLE inline Vec2 Multiply(const Matrix22& a, const Vec2& x) { return a.cols[0] * x.x + a.cols[1] * x.y; } CUDA_CALLABLE inline Matrix22 operator*(float s, const Matrix22& a) { return Multiply(s, a); } CUDA_CALLABLE inline Matrix22 operator*(const Matrix22& a, float s) { return Multiply(s, a); } CUDA_CALLABLE inline Matrix22 operator*(const Matrix22& a, const Matrix22& b) { return Multiply(a, b); } CUDA_CALLABLE inline Matrix22 operator+(const Matrix22& a, const Matrix22& b) { return Add(a, b); } CUDA_CALLABLE inline Matrix22 operator-(const Matrix22& a, const Matrix22& b) { return Add(a, -1.0f * b); } CUDA_CALLABLE inline Matrix22& operator+=(Matrix22& a, const Matrix22& b) { a = a + b; return a; } CUDA_CALLABLE inline Matrix22& operator-=(Matrix22& a, const Matrix22& b) { a = a - b; return a; } CUDA_CALLABLE inline Matrix22& operator*=(Matrix22& a, float s) { a = a * s; return a; } CUDA_CALLABLE inline Vec2 operator*(const Matrix22& a, const Vec2& x) { return Multiply(a, x); } CUDA_CALLABLE inline float Determinant(const Matrix22& m) { return m(0, 0) * m(1, 1) - m(1, 0) * m(0, 1); } CUDA_CALLABLE inline Matrix22 Inverse(const Matrix22& m, float& det) { det = Determinant(m); if (fabsf(det) > FLT_EPSILON) { Matrix22 inv; inv(0, 0) = m(1, 1); inv(1, 1) = m(0, 0); inv(0, 1) = -m(0, 1); inv(1, 0) = -m(1, 0); return Multiply(1.0f / det, inv); } else { det = 0.0f; return m; } } CUDA_CALLABLE inline Matrix22 Transpose(const Matrix22& a) { Matrix22 r; r(0, 0) = a(0, 0); r(0, 1) = a(1, 0); r(1, 0) = a(0, 1); r(1, 1) = a(1, 1); return r; } CUDA_CALLABLE inline float Trace(const Matrix22& a) { return a(0, 0) + a(1, 1); } CUDA_CALLABLE inline Matrix22 RotationMatrix(float theta) { return Matrix22(Vec2(cosf(theta), sinf(theta)), Vec2(-sinf(theta), cosf(theta))); } // outer product of a and b, b is considered a row vector CUDA_CALLABLE inline Matrix22 Outer(const Vec2& a, const Vec2& b) { return Matrix22(a * b.x, a * b.y); } CUDA_CALLABLE inline Matrix22 QRDecomposition(const Matrix22& m) { Vec2 a = Normalize(m.cols[0]); Matrix22 q(a, PerpCCW(a)); return q; } CUDA_CALLABLE inline Matrix22 PolarDecomposition(const Matrix22& m) { /* //iterative method float det; Matrix22 q = m; for (int i=0; i < 4; ++i) { q = 0.5f*(q + Inverse(Transpose(q), det)); } */ Matrix22 q = m + Matrix22(m(1, 1), -m(1, 0), -m(0, 1), m(0, 0)); float s = Length(q.cols[0]); q.cols[0] /= s; q.cols[1] /= s; return q; }
4,704
C
22.063725
99
0.611607
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/vec2.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "common_math.h" #if defined(_WIN32) && !defined(__CUDACC__) # if defined(_DEBUG) # define VEC2_VALIDATE() \ { \ assert(_finite(x)); \ assert(!_isnan(x)); \ \ assert(_finite(y)); \ assert(!_isnan(y)); \ } # else # define VEC2_VALIDATE() \ { \ assert(isfinite(x)); \ assert(isfinite(y)); \ } # endif // _WIN32 #else # define VEC2_VALIDATE() #endif #ifdef _DEBUG # define FLOAT_VALIDATE(f) \ { \ assert(_finite(f)); \ assert(!_isnan(f)); \ } #else # define FLOAT_VALIDATE(f) #endif // vec2 template <typename T> class XVector2 { public: typedef T value_type; CUDA_CALLABLE XVector2() : x(0.0f), y(0.0f) { VEC2_VALIDATE(); } CUDA_CALLABLE XVector2(T _x) : x(_x), y(_x) { VEC2_VALIDATE(); } CUDA_CALLABLE XVector2(T _x, T _y) : x(_x), y(_y) { VEC2_VALIDATE(); } CUDA_CALLABLE XVector2(const T* p) : x(p[0]), y(p[1]) { } template <typename U> CUDA_CALLABLE explicit XVector2(const XVector2<U>& v) : x(v.x), y(v.y) { } CUDA_CALLABLE operator T*() { return &x; } CUDA_CALLABLE operator const T*() const { return &x; }; CUDA_CALLABLE void Set(T x_, T y_) { VEC2_VALIDATE(); x = x_; y = y_; } CUDA_CALLABLE XVector2<T> operator*(T scale) const { XVector2<T> r(*this); r *= scale; VEC2_VALIDATE(); return r; } CUDA_CALLABLE XVector2<T> operator/(T scale) const { XVector2<T> r(*this); r /= scale; VEC2_VALIDATE(); return r; } CUDA_CALLABLE XVector2<T> operator+(const XVector2<T>& v) const { XVector2<T> r(*this); r += v; VEC2_VALIDATE(); return r; } CUDA_CALLABLE XVector2<T> operator-(const XVector2<T>& v) const { XVector2<T> r(*this); r -= v; VEC2_VALIDATE(); return r; } CUDA_CALLABLE XVector2<T>& operator*=(T scale) { x *= scale; y *= scale; VEC2_VALIDATE(); return *this; } CUDA_CALLABLE XVector2<T>& operator/=(T scale) { T s(1.0f / scale); x *= s; y *= s; VEC2_VALIDATE(); return *this; } CUDA_CALLABLE XVector2<T>& operator+=(const XVector2<T>& v) { x += v.x; y += v.y; VEC2_VALIDATE(); return *this; } CUDA_CALLABLE XVector2<T>& operator-=(const XVector2<T>& v) { x -= v.x; y -= v.y; VEC2_VALIDATE(); return *this; } CUDA_CALLABLE XVector2<T>& operator*=(const XVector2<T>& scale) { x *= scale.x; y *= scale.y; VEC2_VALIDATE(); return *this; } // negate CUDA_CALLABLE XVector2<T> operator-() const { VEC2_VALIDATE(); return XVector2<T>(-x, -y); } T x; T y; }; typedef XVector2<float> Vec2; typedef XVector2<float> Vector2; // lhs scalar scale template <typename T> CUDA_CALLABLE XVector2<T> operator*(T lhs, const XVector2<T>& rhs) { XVector2<T> r(rhs); r *= lhs; return r; } template <typename T> CUDA_CALLABLE XVector2<T> operator*(const XVector2<T>& lhs, const XVector2<T>& rhs) { XVector2<T> r(lhs); r *= rhs; return r; } template <typename T> CUDA_CALLABLE bool operator==(const XVector2<T>& lhs, const XVector2<T>& rhs) { return (lhs.x == rhs.x && lhs.y == rhs.y); } template <typename T> CUDA_CALLABLE T Dot(const XVector2<T>& v1, const XVector2<T>& v2) { return v1.x * v2.x + v1.y * v2.y; } // returns the ccw perpendicular vector template <typename T> CUDA_CALLABLE XVector2<T> PerpCCW(const XVector2<T>& v) { return XVector2<T>(-v.y, v.x); } template <typename T> CUDA_CALLABLE XVector2<T> PerpCW(const XVector2<T>& v) { return XVector2<T>(v.y, -v.x); } // component wise min max functions template <typename T> CUDA_CALLABLE XVector2<T> Max(const XVector2<T>& a, const XVector2<T>& b) { return XVector2<T>(Max(a.x, b.x), Max(a.y, b.y)); } template <typename T> CUDA_CALLABLE XVector2<T> Min(const XVector2<T>& a, const XVector2<T>& b) { return XVector2<T>(Min(a.x, b.x), Min(a.y, b.y)); } // 2d cross product, treat as if a and b are in the xy plane and return magnitude of z template <typename T> CUDA_CALLABLE T Cross(const XVector2<T>& a, const XVector2<T>& b) { return (a.x * b.y - a.y * b.x); }
6,708
C
26.609053
120
0.444246
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/point3.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "vec4.h" #include <ostream> class Point3 { public: CUDA_CALLABLE Point3() : x(0), y(0), z(0) { } CUDA_CALLABLE Point3(float a) : x(a), y(a), z(a) { } CUDA_CALLABLE Point3(const float* p) : x(p[0]), y(p[1]), z(p[2]) { } CUDA_CALLABLE Point3(float x_, float y_, float z_) : x(x_), y(y_), z(z_) { Validate(); } CUDA_CALLABLE explicit Point3(const Vec3& v) : x(v.x), y(v.y), z(v.z) { } CUDA_CALLABLE operator float*() { return &x; } CUDA_CALLABLE operator const float*() const { return &x; }; CUDA_CALLABLE operator Vec4() const { return Vec4(x, y, z, 1.0f); } CUDA_CALLABLE void Set(float x_, float y_, float z_) { Validate(); x = x_; y = y_; z = z_; } CUDA_CALLABLE Point3 operator*(float scale) const { Point3 r(*this); r *= scale; Validate(); return r; } CUDA_CALLABLE Point3 operator/(float scale) const { Point3 r(*this); r /= scale; Validate(); return r; } CUDA_CALLABLE Point3 operator+(const Vec3& v) const { Point3 r(*this); r += v; Validate(); return r; } CUDA_CALLABLE Point3 operator-(const Vec3& v) const { Point3 r(*this); r -= v; Validate(); return r; } CUDA_CALLABLE Point3& operator*=(float scale) { x *= scale; y *= scale; z *= scale; Validate(); return *this; } CUDA_CALLABLE Point3& operator/=(float scale) { float s(1.0f / scale); x *= s; y *= s; z *= s; Validate(); return *this; } CUDA_CALLABLE Point3& operator+=(const Vec3& v) { x += v.x; y += v.y; z += v.z; Validate(); return *this; } CUDA_CALLABLE Point3& operator-=(const Vec3& v) { x -= v.x; y -= v.y; z -= v.z; Validate(); return *this; } CUDA_CALLABLE Point3& operator=(const Vec3& v) { x = v.x; y = v.y; z = v.z; return *this; } CUDA_CALLABLE bool operator!=(const Point3& v) const { return (x != v.x || y != v.y || z != v.z); } // negate CUDA_CALLABLE Point3 operator-() const { Validate(); return Point3(-x, -y, -z); } float x, y, z; CUDA_CALLABLE void Validate() const { } }; // lhs scalar scale CUDA_CALLABLE inline Point3 operator*(float lhs, const Point3& rhs) { Point3 r(rhs); r *= lhs; return r; } CUDA_CALLABLE inline Vec3 operator-(const Point3& lhs, const Point3& rhs) { return Vec3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z); } CUDA_CALLABLE inline Point3 operator+(const Point3& lhs, const Point3& rhs) { return Point3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z); } CUDA_CALLABLE inline bool operator==(const Point3& lhs, const Point3& rhs) { return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z); } // component wise min max functions CUDA_CALLABLE inline Point3 Max(const Point3& a, const Point3& b) { return Point3(Max(a.x, b.x), Max(a.y, b.y), Max(a.z, b.z)); } CUDA_CALLABLE inline Point3 Min(const Point3& a, const Point3& b) { return Point3(Min(a.x, b.x), Min(a.y, b.y), Min(a.z, b.z)); }
4,141
C
21.149733
99
0.54552
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/quat.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "vec3.h" #include <cassert> struct Matrix33; template <typename T> class XQuat { public: typedef T value_type; CUDA_CALLABLE XQuat() : x(0), y(0), z(0), w(1.0) { } CUDA_CALLABLE XQuat(const T* p) : x(p[0]), y(p[1]), z(p[2]), w(p[3]) { } CUDA_CALLABLE XQuat(T x_, T y_, T z_, T w_) : x(x_), y(y_), z(z_), w(w_) { } CUDA_CALLABLE XQuat(const Vec3& v, float w) : x(v.x), y(v.y), z(v.z), w(w) { } CUDA_CALLABLE explicit XQuat(const Matrix33& m); CUDA_CALLABLE operator T*() { return &x; } CUDA_CALLABLE operator const T*() const { return &x; }; CUDA_CALLABLE void Set(T x_, T y_, T z_, T w_) { x = x_; y = y_; z = z_; w = w_; } CUDA_CALLABLE XQuat<T> operator*(T scale) const { XQuat<T> r(*this); r *= scale; return r; } CUDA_CALLABLE XQuat<T> operator/(T scale) const { XQuat<T> r(*this); r /= scale; return r; } CUDA_CALLABLE XQuat<T> operator+(const XQuat<T>& v) const { XQuat<T> r(*this); r += v; return r; } CUDA_CALLABLE XQuat<T> operator-(const XQuat<T>& v) const { XQuat<T> r(*this); r -= v; return r; } CUDA_CALLABLE XQuat<T> operator*(XQuat<T> q) const { // quaternion multiplication return XQuat<T>(w * q.x + q.w * x + y * q.z - q.y * z, w * q.y + q.w * y + z * q.x - q.z * x, w * q.z + q.w * z + x * q.y - q.x * y, w * q.w - x * q.x - y * q.y - z * q.z); } CUDA_CALLABLE XQuat<T>& operator*=(T scale) { x *= scale; y *= scale; z *= scale; w *= scale; return *this; } CUDA_CALLABLE XQuat<T>& operator/=(T scale) { T s(1.0f / scale); x *= s; y *= s; z *= s; w *= s; return *this; } CUDA_CALLABLE XQuat<T>& operator+=(const XQuat<T>& v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } CUDA_CALLABLE XQuat<T>& operator-=(const XQuat<T>& v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } CUDA_CALLABLE bool operator!=(const XQuat<T>& v) const { return (x != v.x || y != v.y || z != v.z || w != v.w); } // negate CUDA_CALLABLE XQuat<T> operator-() const { return XQuat<T>(-x, -y, -z, -w); } CUDA_CALLABLE XVector3<T> GetAxis() const { return XVector3<T>(x, y, z); } T x, y, z, w; }; typedef XQuat<float> Quat; // lhs scalar scale template <typename T> CUDA_CALLABLE XQuat<T> operator*(T lhs, const XQuat<T>& rhs) { XQuat<T> r(rhs); r *= lhs; return r; } template <typename T> CUDA_CALLABLE bool operator==(const XQuat<T>& lhs, const XQuat<T>& rhs) { return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w); } template <typename T> CUDA_CALLABLE inline XQuat<T> QuatFromAxisAngle(const Vec3& axis, float angle) { Vec3 v = Normalize(axis); float half = angle * 0.5f; float w = cosf(half); const float sin_theta_over_two = sinf(half); v *= sin_theta_over_two; return XQuat<T>(v.x, v.y, v.z, w); } CUDA_CALLABLE inline float Dot(const Quat& a, const Quat& b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } CUDA_CALLABLE inline float Length(const Quat& a) { return sqrtf(Dot(a, a)); } CUDA_CALLABLE inline Quat QuatFromEulerZYX(float rotx, float roty, float rotz) { Quat q; // Abbreviations for the various angular functions float cy = cos(rotz * 0.5f); float sy = sin(rotz * 0.5f); float cr = cos(rotx * 0.5f); float sr = sin(rotx * 0.5f); float cp = cos(roty * 0.5f); float sp = sin(roty * 0.5f); q.w = (float)(cy * cr * cp + sy * sr * sp); q.x = (float)(cy * sr * cp - sy * cr * sp); q.y = (float)(cy * cr * sp + sy * sr * cp); q.z = (float)(sy * cr * cp - cy * sr * sp); return q; } CUDA_CALLABLE inline void EulerFromQuatZYX(const Quat& q, float& rotx, float& roty, float& rotz) { float x = q.x, y = q.y, z = q.z, w = q.w; float t0 = x * x - z * z; float t1 = w * w - y * y; float xx = 0.5f * (t0 + t1); // 1/2 x of x' float xy = x * y + w * z; // 1/2 y of x' float xz = w * y - x * z; // 1/2 z of x' float t = xx * xx + xy * xy; // cos(theta)^2 float yz = 2.0f * (y * z + w * x); // z of y' rotz = atan2(xy, xx); // yaw (psi) roty = atan(xz / sqrt(t)); // pitch (theta) // todo: doublecheck! if (fabsf(t) > 1e-6f) { rotx = (float)atan2(yz, t1 - t0); } else { rotx = (float)(2.0f * atan2(x, w) - copysignf(1.0f, xz) * rotz); } } // converts Euler angles to quaternion performing an intrinsic rotation in yaw then pitch then roll order // i.e. first rotate by yaw around z, then rotate by pitch around the rotated y axis, then rotate around // roll around the twice (by yaw and pitch) rotated x axis CUDA_CALLABLE inline Quat rpy2quat(const float roll, const float pitch, const float yaw) { Quat q; // Abbreviations for the various angular functions float cy = cos(yaw * 0.5f); float sy = sin(yaw * 0.5f); float cr = cos(roll * 0.5f); float sr = sin(roll * 0.5f); float cp = cos(pitch * 0.5f); float sp = sin(pitch * 0.5f); q.w = (float)(cy * cr * cp + sy * sr * sp); q.x = (float)(cy * sr * cp - sy * cr * sp); q.y = (float)(cy * cr * sp + sy * sr * cp); q.z = (float)(sy * cr * cp - cy * sr * sp); return q; } // converts Euler angles to quaternion performing an intrinsic rotation in x then y then z order // i.e. first rotate by x_rot around x, then rotate by y_rot around the rotated y axis, then rotate by // z_rot around the twice (by roll and pitch) rotated z axis CUDA_CALLABLE inline Quat euler_xyz2quat(const float x_rot, const float y_rot, const float z_rot) { Quat q; // Abbreviations for the various angular functions float cy = std::cos(z_rot * 0.5f); float sy = std::sin(z_rot * 0.5f); float cr = std::cos(x_rot * 0.5f); float sr = std::sin(x_rot * 0.5f); float cp = std::cos(y_rot * 0.5f); float sp = std::sin(y_rot * 0.5f); q.w = (float)(cy * cr * cp - sy * sr * sp); q.x = (float)(cy * sr * cp + sy * cr * sp); q.y = (float)(cy * cr * sp - sy * sr * cp); q.z = (float)(sy * cr * cp + cy * sr * sp); return q; } // !!! preist@ This function produces euler angles according to this convention: // https://www.euclideanspace.com/maths/standards/index.htm Heading = rotation about y axis Attitude = rotation about z // axis Bank = rotation about x axis Order: Heading (y) -> Attitude (z) -> Bank (x), and applied intrinsically CUDA_CALLABLE inline void quat2rpy(const Quat& q1, float& bank, float& attitude, float& heading) { float sqw = q1.w * q1.w; float sqx = q1.x * q1.x; float sqy = q1.y * q1.y; float sqz = q1.z * q1.z; float unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor float test = q1.x * q1.y + q1.z * q1.w; if (test > 0.499f * unit) { // singularity at north pole heading = 2.f * atan2(q1.x, q1.w); attitude = kPi / 2.f; bank = 0.f; return; } if (test < -0.499f * unit) { // singularity at south pole heading = -2.f * atan2(q1.x, q1.w); attitude = -kPi / 2.f; bank = 0.f; return; } heading = atan2(2.f * q1.x * q1.y + 2.f * q1.w * q1.z, sqx - sqy - sqz + sqw); attitude = asin(-2.f * q1.x * q1.z + 2.f * q1.y * q1.w); bank = atan2(2.f * q1.y * q1.z + 2.f * q1.x * q1.w, -sqx - sqy + sqz + sqw); } // preist@: // The Euler angles correspond to an extrinsic x-y-z i.e. intrinsic z-y-x rotation // and this function does not guard against gimbal lock CUDA_CALLABLE inline void zUpQuat2rpy(const Quat& q1, float& roll, float& pitch, float& yaw) { // roll (x-axis rotation) float sinr_cosp = 2.0f * (q1.w * q1.x + q1.y * q1.z); float cosr_cosp = 1.0f - 2.0f * (q1.x * q1.x + q1.y * q1.y); roll = atan2(sinr_cosp, cosr_cosp); // pitch (y-axis rotation) float sinp = 2.0f * (q1.w * q1.y - q1.z * q1.x); if (fabs(sinp) > 0.999f) pitch = (float)copysign(kPi / 2.0f, sinp); else pitch = asin(sinp); // yaw (z-axis rotation) float siny_cosp = 2.0f * (q1.w * q1.z + q1.x * q1.y); float cosy_cosp = 1.0f - 2.0f * (q1.y * q1.y + q1.z * q1.z); yaw = atan2(siny_cosp, cosy_cosp); } CUDA_CALLABLE inline void getEulerZYX(const Quat& q, float& yawZ, float& pitchY, float& rollX) { float squ; float sqx; float sqy; float sqz; float sarg; sqx = q.x * q.x; sqy = q.y * q.y; sqz = q.z * q.z; squ = q.w * q.w; rollX = atan2(2 * (q.y * q.z + q.w * q.x), squ - sqx - sqy + sqz); sarg = (-2.0f) * (q.x * q.z - q.w * q.y); pitchY = sarg <= (-1.0f) ? (-0.5f) * kPi : (sarg >= (1.0f) ? (0.5f) * kPi : asinf(sarg)); yawZ = atan2(2 * (q.x * q.y + q.w * q.z), squ + sqx - sqy - sqz); } // rotate vector by quaternion (q, w) CUDA_CALLABLE inline Vec3 Rotate(const Quat& q, const Vec3& x) { return x * (2.0f * q.w * q.w - 1.0f) + Cross(Vec3(q), x) * q.w * 2.0f + Vec3(q) * Dot(Vec3(q), x) * 2.0f; } CUDA_CALLABLE inline Vec3 operator*(const Quat& q, const Vec3& v) { return Rotate(q, v); } CUDA_CALLABLE inline Vec3 GetBasisVector0(const Quat& q) { return Rotate(q, Vec3(1.0f, 0.0f, 0.0f)); } CUDA_CALLABLE inline Vec3 GetBasisVector1(const Quat& q) { return Rotate(q, Vec3(0.0f, 1.0f, 0.0f)); } CUDA_CALLABLE inline Vec3 GetBasisVector2(const Quat& q) { return Rotate(q, Vec3(0.0f, 0.0f, 1.0f)); } // rotate vector by inverse transform in (q, w) CUDA_CALLABLE inline Vec3 RotateInv(const Quat& q, const Vec3& x) { return x * (2.0f * q.w * q.w - 1.0f) - Cross(Vec3(q), x) * q.w * 2.0f + Vec3(q) * Dot(Vec3(q), x) * 2.0f; } CUDA_CALLABLE inline Quat Inverse(const Quat& q) { return Quat(-q.x, -q.y, -q.z, q.w); } CUDA_CALLABLE inline Quat Normalize(const Quat& q) { float lSq = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w; if (lSq > 0.0f) { float invL = 1.0f / sqrtf(lSq); return q * invL; } else return Quat(); } // // given two quaternions and a time-step returns the corresponding angular velocity vector // CUDA_CALLABLE inline Vec3 DifferentiateQuat(const Quat& q1, const Quat& q0, float invdt) { Quat dq = q1 * Inverse(q0); float sinHalfTheta = Length(dq.GetAxis()); float theta = asinf(sinHalfTheta) * 2.0f; if (fabsf(theta) < 0.001f) { // use linear approximation approx for small angles Quat dqdt = (q1 - q0) * invdt; Quat omega = dqdt * Inverse(q0); return Vec3(omega.x, omega.y, omega.z) * 2.0f; } else { // use inverse exponential map Vec3 axis = Normalize(dq.GetAxis()); return axis * theta * invdt; } } CUDA_CALLABLE inline Quat IntegrateQuat(const Vec3& omega, const Quat& q0, float dt) { Vec3 axis; float w = Length(omega); if (w * dt < 0.001f) { // sinc approx for small angles axis = omega * (0.5f * dt - (dt * dt * dt) / 48.0f * w * w); } else { axis = omega * (sinf(0.5f * w * dt) / w); } Quat dq; dq.x = axis.x; dq.y = axis.y; dq.z = axis.z; dq.w = cosf(w * dt * 0.5f); Quat q1 = dq * q0; // explicit re-normalization here otherwise we do some see energy drift return Normalize(q1); }
12,375
C
26.380531
119
0.550949
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/vec3.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "common_math.h" #if 0 //_DEBUG # define VEC3_VALIDATE() \ { \ assert(_finite(x)); \ assert(!_isnan(x)); \ \ assert(_finite(y)); \ assert(!_isnan(y)); \ \ assert(_finite(z)); \ assert(!_isnan(z)); \ } #else # define VEC3_VALIDATE() #endif template <typename T = float> class XVector3 { public: typedef T value_type; CUDA_CALLABLE inline XVector3() : x(0.0f), y(0.0f), z(0.0f) { } CUDA_CALLABLE inline XVector3(T a) : x(a), y(a), z(a) { } CUDA_CALLABLE inline XVector3(const T* p) : x(p[0]), y(p[1]), z(p[2]) { } CUDA_CALLABLE inline XVector3(T x_, T y_, T z_) : x(x_), y(y_), z(z_) { VEC3_VALIDATE(); } CUDA_CALLABLE inline operator T*() { return &x; } CUDA_CALLABLE inline operator const T*() const { return &x; }; CUDA_CALLABLE inline void Set(T x_, T y_, T z_) { VEC3_VALIDATE(); x = x_; y = y_; z = z_; } CUDA_CALLABLE inline XVector3<T> operator*(T scale) const { XVector3<T> r(*this); r *= scale; return r; VEC3_VALIDATE(); } CUDA_CALLABLE inline XVector3<T> operator/(T scale) const { XVector3<T> r(*this); r /= scale; return r; VEC3_VALIDATE(); } CUDA_CALLABLE inline XVector3<T> operator+(const XVector3<T>& v) const { XVector3<T> r(*this); r += v; return r; VEC3_VALIDATE(); } CUDA_CALLABLE inline XVector3<T> operator-(const XVector3<T>& v) const { XVector3<T> r(*this); r -= v; return r; VEC3_VALIDATE(); } CUDA_CALLABLE inline XVector3<T> operator/(const XVector3<T>& v) const { XVector3<T> r(*this); r /= v; return r; VEC3_VALIDATE(); } CUDA_CALLABLE inline XVector3<T> operator*(const XVector3<T>& v) const { XVector3<T> r(*this); r *= v; return r; VEC3_VALIDATE(); } CUDA_CALLABLE inline XVector3<T>& operator*=(T scale) { x *= scale; y *= scale; z *= scale; VEC3_VALIDATE(); return *this; } CUDA_CALLABLE inline XVector3<T>& operator/=(T scale) { T s(1.0f / scale); x *= s; y *= s; z *= s; VEC3_VALIDATE(); return *this; } CUDA_CALLABLE inline XVector3<T>& operator+=(const XVector3<T>& v) { x += v.x; y += v.y; z += v.z; VEC3_VALIDATE(); return *this; } CUDA_CALLABLE inline XVector3<T>& operator-=(const XVector3<T>& v) { x -= v.x; y -= v.y; z -= v.z; VEC3_VALIDATE(); return *this; } CUDA_CALLABLE inline XVector3<T>& operator/=(const XVector3<T>& v) { x /= v.x; y /= v.y; z /= v.z; VEC3_VALIDATE(); return *this; } CUDA_CALLABLE inline XVector3<T>& operator*=(const XVector3<T>& v) { x *= v.x; y *= v.y; z *= v.z; VEC3_VALIDATE(); return *this; } CUDA_CALLABLE inline bool operator!=(const XVector3<T>& v) const { return (x != v.x || y != v.y || z != v.z); } // negate CUDA_CALLABLE inline XVector3<T> operator-() const { VEC3_VALIDATE(); return XVector3<T>(-x, -y, -z); } CUDA_CALLABLE void Validate() { VEC3_VALIDATE(); } T x, y, z; }; typedef XVector3<float> Vec3; typedef XVector3<float> Vector3; // lhs scalar scale template <typename T> CUDA_CALLABLE XVector3<T> operator*(T lhs, const XVector3<T>& rhs) { XVector3<T> r(rhs); r *= lhs; return r; } template <typename T> CUDA_CALLABLE bool operator==(const XVector3<T>& lhs, const XVector3<T>& rhs) { return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z); } template <typename T> CUDA_CALLABLE typename T::value_type Dot3(const T& v1, const T& v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } CUDA_CALLABLE inline float Dot3(const float* v1, const float* v2) { return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; } template <typename T> CUDA_CALLABLE inline T Dot(const XVector3<T>& v1, const XVector3<T>& v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } CUDA_CALLABLE inline Vec3 Cross(const Vec3& b, const Vec3& c) { return Vec3(b.y * c.z - b.z * c.y, b.z * c.x - b.x * c.z, b.x * c.y - b.y * c.x); } // component wise min max functions template <typename T> CUDA_CALLABLE inline XVector3<T> Max(const XVector3<T>& a, const XVector3<T>& b) { return XVector3<T>(Max(a.x, b.x), Max(a.y, b.y), Max(a.z, b.z)); } template <typename T> CUDA_CALLABLE inline XVector3<T> Min(const XVector3<T>& a, const XVector3<T>& b) { return XVector3<T>(Min(a.x, b.x), Min(a.y, b.y), Min(a.z, b.z)); }
6,616
C
26.686192
120
0.465689
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/matnn.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once template <int m, int n, typename T = double> class XMatrix { public: XMatrix() { memset(data, 0, sizeof(*this)); } XMatrix(const XMatrix<m, n>& a) { memcpy(data, a.data, sizeof(*this)); } template <typename OtherT> XMatrix(const OtherT* ptr) { for (int j = 0; j < n; ++j) for (int i = 0; i < m; ++i) data[j][i] = *(ptr++); } const XMatrix<m, n>& operator=(const XMatrix<m, n>& a) { memcpy(data, a.data, sizeof(*this)); return *this; } template <typename OtherT> void SetCol(int j, const XMatrix<m, 1, OtherT>& c) { for (int i = 0; i < m; ++i) data[j][i] = c(i, 0); } template <typename OtherT> void SetRow(int i, const XMatrix<1, n, OtherT>& r) { for (int j = 0; j < m; ++j) data[j][i] = r(0, j); } T& operator()(int row, int col) { return data[col][row]; } const T& operator()(int row, int col) const { return data[col][row]; } void SetIdentity() { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i == j) data[i][j] = 1.0; else data[i][j] = 0.0; } } } // column major storage T data[n][m]; }; template <int m, int n, typename T> XMatrix<m, n, T> operator-(const XMatrix<m, n, T>& lhs, const XMatrix<m, n, T>& rhs) { XMatrix<m, n> d; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) d(i, j) = lhs(i, j) - rhs(i, j); return d; } template <int m, int n, typename T> XMatrix<m, n, T> operator+(const XMatrix<m, n, T>& lhs, const XMatrix<m, n, T>& rhs) { XMatrix<m, n> d; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) d(i, j) = lhs(i, j) + rhs(i, j); return d; } template <int m, int n, int o, typename T> XMatrix<m, o> Multiply(const XMatrix<m, n, T>& lhs, const XMatrix<n, o, T>& rhs) { XMatrix<m, o> ret; for (int i = 0; i < m; ++i) { for (int j = 0; j < o; ++j) { T sum = 0.0f; for (int k = 0; k < n; ++k) { sum += lhs(i, k) * rhs(k, j); } ret(i, j) = sum; } } return ret; } template <int m, int n> XMatrix<n, m> Transpose(const XMatrix<m, n>& a) { XMatrix<n, m> ret; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { ret(j, i) = a(i, j); } } return ret; } // matrix to swap row i and j when multiplied on the right template <int n> XMatrix<n, n> Permutation(int i, int j) { XMatrix<n, n> m; m.SetIdentity(); m(i, i) = 0.0; m(i, j) = 1.0; m(j, j) = 0.0; m(j, i) = 1.0; return m; } template <int m, int n> void PrintMatrix(const char* name, XMatrix<m, n> a) { printf("%s = [\n", name); for (int i = 0; i < m; ++i) { printf("[ "); for (int j = 0; j < n; ++j) { printf("% .4f", float(a(i, j))); if (j < n - 1) printf(" "); } printf(" ]\n"); } printf("]\n"); } template <int n, typename T> XMatrix<n, n, T> LU(const XMatrix<n, n, T>& m, XMatrix<n, n, T>& L) { XMatrix<n, n> U = m; L.SetIdentity(); // for each row for (int j = 0; j < n; ++j) { XMatrix<n, n> Li, LiInv; Li.SetIdentity(); LiInv.SetIdentity(); T pivot = U(j, j); if (pivot == 0.0) return U; assert(pivot != 0.0); // zero our all entries below pivot for (int i = j + 1; i < n; ++i) { T l = -U(i, j) / pivot; Li(i, j) = l; // create inverse of L1..Ln as we go (this is L) L(i, j) = -l; } U = Multiply(Li, U); } return U; } template <int m, typename T> XMatrix<m, 1, T> Solve(const XMatrix<m, m, T>& L, const XMatrix<m, m, T>& U, const XMatrix<m, 1, T>& b) { XMatrix<m, 1> y; XMatrix<m, 1> x; // Ly = b (forward substitution) for (int i = 0; i < m; ++i) { T sum = 0.0; for (int j = 0; j < i; ++j) { sum += y(j, 0) * L(i, j); } assert(L(i, i) != 0.0); y(i, 0) = (b(i, 0) - sum) / L(i, i); } // Ux = y (back substitution) for (int i = m - 1; i >= 0; --i) { T sum = 0.0; for (int j = i + 1; j < m; ++j) { sum += x(j, 0) * U(i, j); } assert(U(i, i) != 0.0); x(i, 0) = (y(i, 0) - sum) / U(i, i); } return x; } template <int n, typename T> T Determinant(const XMatrix<n, n, T>& A, XMatrix<n, n, T>& L, XMatrix<n, n, T>& U) { U = LU(A, L); // determinant is the product of diagonal entries of U (assume L has 1s on diagonal) T det = 1.0; for (int i = 0; i < n; ++i) det *= U(i, i); return det; } template <int n, typename T> XMatrix<n, n, T> Inverse(const XMatrix<n, n, T>& A, T& det) { XMatrix<n, n> L, U; det = Determinant(A, L, U); XMatrix<n, n> Inv; if (det != 0.0f) { for (int i = 0; i < n; ++i) { // solve for each column of the identity matrix XMatrix<n, 1> I; I(i, 0) = 1.0; XMatrix<n, 1> x = Solve(L, U, I); Inv.SetCol(i, x); } } return Inv; } template <int m, int n, typename T> T FrobeniusNorm(const XMatrix<m, n, T>& A) { T sum = 0.0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) sum += A(i, j) * A(i, j); return sqrt(sum); }
6,483
C
19.326019
103
0.459201
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/vec4.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "common_math.h" #include "vec3.h" #include <cassert> #if 0 // defined(_DEBUG) && defined(_WIN32) # define VEC4_VALIDATE() \ { \ assert(_finite(x)); \ assert(!_isnan(x)); \ \ assert(_finite(y)); \ assert(!_isnan(y)); \ \ assert(_finite(z)); \ assert(!_isnan(z)); \ \ assert(_finite(w)); \ assert(!_isnan(w)); \ } #else # define VEC4_VALIDATE() #endif template <typename T> class XVector4 { public: typedef T value_type; CUDA_CALLABLE XVector4() : x(0), y(0), z(0), w(0) { } CUDA_CALLABLE XVector4(T a) : x(a), y(a), z(a), w(a) { } CUDA_CALLABLE XVector4(const T* p) : x(p[0]), y(p[1]), z(p[2]), w(p[3]) { } CUDA_CALLABLE XVector4(T x_, T y_, T z_, T w_ = 1.0f) : x(x_), y(y_), z(z_), w(w_) { VEC4_VALIDATE(); } CUDA_CALLABLE XVector4(const Vec3& v, float w) : x(v.x), y(v.y), z(v.z), w(w) { } CUDA_CALLABLE operator T*() { return &x; } CUDA_CALLABLE operator const T*() const { return &x; }; CUDA_CALLABLE void Set(T x_, T y_, T z_, T w_) { VEC4_VALIDATE(); x = x_; y = y_; z = z_; w = w_; } CUDA_CALLABLE XVector4<T> operator*(T scale) const { XVector4<T> r(*this); r *= scale; VEC4_VALIDATE(); return r; } CUDA_CALLABLE XVector4<T> operator/(T scale) const { XVector4<T> r(*this); r /= scale; VEC4_VALIDATE(); return r; } CUDA_CALLABLE XVector4<T> operator+(const XVector4<T>& v) const { XVector4<T> r(*this); r += v; VEC4_VALIDATE(); return r; } CUDA_CALLABLE XVector4<T> operator-(const XVector4<T>& v) const { XVector4<T> r(*this); r -= v; VEC4_VALIDATE(); return r; } CUDA_CALLABLE XVector4<T> operator*(XVector4<T> scale) const { XVector4<T> r(*this); r *= scale; VEC4_VALIDATE(); return r; } CUDA_CALLABLE XVector4<T>& operator*=(T scale) { x *= scale; y *= scale; z *= scale; w *= scale; VEC4_VALIDATE(); return *this; } CUDA_CALLABLE XVector4<T>& operator/=(T scale) { T s(1.0f / scale); x *= s; y *= s; z *= s; w *= s; VEC4_VALIDATE(); return *this; } CUDA_CALLABLE XVector4<T>& operator+=(const XVector4<T>& v) { x += v.x; y += v.y; z += v.z; w += v.w; VEC4_VALIDATE(); return *this; } CUDA_CALLABLE XVector4<T>& operator-=(const XVector4<T>& v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; VEC4_VALIDATE(); return *this; } CUDA_CALLABLE XVector4<T>& operator*=(const XVector4<T>& v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; VEC4_VALIDATE(); return *this; } CUDA_CALLABLE bool operator!=(const XVector4<T>& v) const { return (x != v.x || y != v.y || z != v.z || w != v.w); } // negate CUDA_CALLABLE XVector4<T> operator-() const { VEC4_VALIDATE(); return XVector4<T>(-x, -y, -z, -w); } T x, y, z, w; }; typedef XVector4<float> Vector4; typedef XVector4<float> Vec4; // lhs scalar scale template <typename T> CUDA_CALLABLE XVector4<T> operator*(T lhs, const XVector4<T>& rhs) { XVector4<T> r(rhs); r *= lhs; return r; } template <typename T> CUDA_CALLABLE bool operator==(const XVector4<T>& lhs, const XVector4<T>& rhs) { return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w); }
5,778
C
28.040201
120
0.401696
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/mat44.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "common_math.h" #include "point3.h" #include "vec4.h" // stores column vectors in column major order template <typename T> class XMatrix44 { public: CUDA_CALLABLE XMatrix44() { memset(columns, 0, sizeof(columns)); } CUDA_CALLABLE XMatrix44(const T* d) { assert(d); memcpy(columns, d, sizeof(*this)); } CUDA_CALLABLE XMatrix44( T c11, T c21, T c31, T c41, T c12, T c22, T c32, T c42, T c13, T c23, T c33, T c43, T c14, T c24, T c34, T c44) { columns[0][0] = c11; columns[0][1] = c21; columns[0][2] = c31; columns[0][3] = c41; columns[1][0] = c12; columns[1][1] = c22; columns[1][2] = c32; columns[1][3] = c42; columns[2][0] = c13; columns[2][1] = c23; columns[2][2] = c33; columns[2][3] = c43; columns[3][0] = c14; columns[3][1] = c24; columns[3][2] = c34; columns[3][3] = c44; } CUDA_CALLABLE XMatrix44(const Vec4& c1, const Vec4& c2, const Vec4& c3, const Vec4& c4) { columns[0][0] = c1.x; columns[0][1] = c1.y; columns[0][2] = c1.z; columns[0][3] = c1.w; columns[1][0] = c2.x; columns[1][1] = c2.y; columns[1][2] = c2.z; columns[1][3] = c2.w; columns[2][0] = c3.x; columns[2][1] = c3.y; columns[2][2] = c3.z; columns[2][3] = c3.w; columns[3][0] = c4.x; columns[3][1] = c4.y; columns[3][2] = c4.z; columns[3][3] = c4.w; } CUDA_CALLABLE operator T*() { return &columns[0][0]; } CUDA_CALLABLE operator const T*() const { return &columns[0][0]; } // right multiply CUDA_CALLABLE XMatrix44<T> operator*(const XMatrix44<T>& rhs) const { XMatrix44<T> r; MatrixMultiply(*this, rhs, r); return r; } // right multiply CUDA_CALLABLE XMatrix44<T>& operator*=(const XMatrix44<T>& rhs) { XMatrix44<T> r; MatrixMultiply(*this, rhs, r); *this = r; return *this; } CUDA_CALLABLE float operator()(int row, int col) const { return columns[col][row]; } CUDA_CALLABLE float& operator()(int row, int col) { return columns[col][row]; } // scalar multiplication CUDA_CALLABLE XMatrix44<T>& operator*=(const T& s) { for (int c = 0; c < 4; ++c) { for (int r = 0; r < 4; ++r) { columns[c][r] *= s; } } return *this; } CUDA_CALLABLE void MatrixMultiply(const T* __restrict lhs, const T* __restrict rhs, T* __restrict result) const { assert(lhs != rhs); assert(lhs != result); assert(rhs != result); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { result[j * 4 + i] = rhs[j * 4 + 0] * lhs[i + 0]; result[j * 4 + i] += rhs[j * 4 + 1] * lhs[i + 4]; result[j * 4 + i] += rhs[j * 4 + 2] * lhs[i + 8]; result[j * 4 + i] += rhs[j * 4 + 3] * lhs[i + 12]; } } } CUDA_CALLABLE void SetCol(int index, const Vec4& c) { columns[index][0] = c.x; columns[index][1] = c.y; columns[index][2] = c.z; columns[index][3] = c.w; } // convenience overloads CUDA_CALLABLE void SetAxis(uint32_t index, const XVector3<T>& a) { columns[index][0] = a.x; columns[index][1] = a.y; columns[index][2] = a.z; columns[index][3] = 0.0f; } CUDA_CALLABLE void SetTranslation(const Point3& p) { columns[3][0] = p.x; columns[3][1] = p.y; columns[3][2] = p.z; columns[3][3] = 1.0f; } CUDA_CALLABLE const Vec3& GetAxis(int i) const { return *reinterpret_cast<const Vec3*>(&columns[i]); } CUDA_CALLABLE const Vec4& GetCol(int i) const { return *reinterpret_cast<const Vec4*>(&columns[i]); } CUDA_CALLABLE const Point3& GetTranslation() const { return *reinterpret_cast<const Point3*>(&columns[3]); } CUDA_CALLABLE Vec4 GetRow(int i) const { return Vec4(columns[0][i], columns[1][i], columns[2][i], columns[3][i]); } CUDA_CALLABLE static inline XMatrix44 Identity() { const XMatrix44 sIdentity(Vec4(1.0f, 0.0f, 0.0f, 0.0f), Vec4(0.0f, 1.0f, 0.0f, 0.0f), Vec4(0.0f, 0.0f, 1.0f, 0.0f), Vec4(0.0f, 0.0f, 0.0f, 1.0f)); return sIdentity; } float columns[4][4]; }; // right multiply a point assumes w of 1 template <typename T> CUDA_CALLABLE Point3 Multiply(const XMatrix44<T>& mat, const Point3& v) { Point3 r; r.x = v.x * mat[0] + v.y * mat[4] + v.z * mat[8] + mat[12]; r.y = v.x * mat[1] + v.y * mat[5] + v.z * mat[9] + mat[13]; r.z = v.x * mat[2] + v.y * mat[6] + v.z * mat[10] + mat[14]; return r; } // right multiply a vector3 assumes a w of 0 template <typename T> CUDA_CALLABLE XVector3<T> Multiply(const XMatrix44<T>& mat, const XVector3<T>& v) { XVector3<T> r; r.x = v.x * mat[0] + v.y * mat[4] + v.z * mat[8]; r.y = v.x * mat[1] + v.y * mat[5] + v.z * mat[9]; r.z = v.x * mat[2] + v.y * mat[6] + v.z * mat[10]; return r; } // right multiply a vector4 template <typename T> CUDA_CALLABLE XVector4<T> Multiply(const XMatrix44<T>& mat, const XVector4<T>& v) { XVector4<T> r; r.x = v.x * mat[0] + v.y * mat[4] + v.z * mat[8] + v.w * mat[12]; r.y = v.x * mat[1] + v.y * mat[5] + v.z * mat[9] + v.w * mat[13]; r.z = v.x * mat[2] + v.y * mat[6] + v.z * mat[10] + v.w * mat[14]; r.w = v.x * mat[3] + v.y * mat[7] + v.z * mat[11] + v.w * mat[15]; return r; } template <typename T> CUDA_CALLABLE Point3 operator*(const XMatrix44<T>& mat, const Point3& v) { return Multiply(mat, v); } template <typename T> CUDA_CALLABLE XVector4<T> operator*(const XMatrix44<T>& mat, const XVector4<T>& v) { return Multiply(mat, v); } template <typename T> CUDA_CALLABLE XVector3<T> operator*(const XMatrix44<T>& mat, const XVector3<T>& v) { return Multiply(mat, v); } template <typename T> CUDA_CALLABLE inline XMatrix44<T> Transpose(const XMatrix44<T>& m) { XMatrix44<float> inv; // transpose for (uint32_t c = 0; c < 4; ++c) { for (uint32_t r = 0; r < 4; ++r) { inv.columns[c][r] = m.columns[r][c]; } } return inv; } template <typename T> CUDA_CALLABLE XMatrix44<T> AffineInverse(const XMatrix44<T>& m) { XMatrix44<T> inv; // transpose upper 3x3 for (int c = 0; c < 3; ++c) { for (int r = 0; r < 3; ++r) { inv.columns[c][r] = m.columns[r][c]; } } // multiply -translation by upper 3x3 transpose inv.columns[3][0] = -Dot3(m.columns[3], m.columns[0]); inv.columns[3][1] = -Dot3(m.columns[3], m.columns[1]); inv.columns[3][2] = -Dot3(m.columns[3], m.columns[2]); inv.columns[3][3] = 1.0f; return inv; } CUDA_CALLABLE inline XMatrix44<float> Outer(const Vec4& a, const Vec4& b) { return XMatrix44<float>(a * b.x, a * b.y, a * b.z, a * b.w); } // convenience typedef XMatrix44<float> Mat44; typedef XMatrix44<float> Matrix44;
8,070
C
25.289902
119
0.536679
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/maths.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "common_math.h" #include "core.h" #include "mat22.h" #include "mat33.h" #include "mat44.h" #include "matnn.h" #include "point3.h" #include "quat.h" #include "types.h" #include "vec2.h" #include "vec3.h" #include "vec4.h" #include <cassert> #include <cmath> #include <cstdlib> #include <float.h> #include <string.h> struct Transform { // transform CUDA_CALLABLE Transform() : p(0.0) { } CUDA_CALLABLE Transform(const Vec3& v, const Quat& q = Quat()) : p(v), q(q) { } CUDA_CALLABLE Transform operator*(const Transform& rhs) const { return Transform(Rotate(q, rhs.p) + p, q * rhs.q); } Vec3 p; Quat q; }; CUDA_CALLABLE inline Transform Inverse(const Transform& transform) { Transform t; t.q = Inverse(transform.q); t.p = -Rotate(t.q, transform.p); return t; } CUDA_CALLABLE inline Vec3 TransformVector(const Transform& t, const Vec3& v) { return t.q * v; } CUDA_CALLABLE inline Vec3 TransformPoint(const Transform& t, const Vec3& v) { return t.q * v + t.p; } CUDA_CALLABLE inline Vec3 InverseTransformVector(const Transform& t, const Vec3& v) { return Inverse(t.q) * v; } CUDA_CALLABLE inline Vec3 InverseTransformPoint(const Transform& t, const Vec3& v) { return Inverse(t.q) * (v - t.p); } // represents a plane in the form ax + by + cz - d = 0 class Plane : public Vec4 { public: CUDA_CALLABLE inline Plane() { } CUDA_CALLABLE inline Plane(float x, float y, float z, float w) : Vec4(x, y, z, w) { } CUDA_CALLABLE inline Plane(const Vec3& p, const Vector3& n) { x = n.x; y = n.y; z = n.z; w = -Dot3(p, n); } CUDA_CALLABLE inline Vec3 GetNormal() const { return Vec3(x, y, z); } CUDA_CALLABLE inline Vec3 GetPoint() const { return Vec3(x * -w, y * -w, z * -w); } CUDA_CALLABLE inline Plane(const Vec3& v) : Vec4(v.x, v.y, v.z, 1.0f) { } CUDA_CALLABLE inline Plane(const Vec4& v) : Vec4(v) { } }; template <typename T> CUDA_CALLABLE inline T Dot(const XVector4<T>& v1, const XVector4<T>& v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + v1.w * v2.w; } // helper function that assumes a w of 0 CUDA_CALLABLE inline float Dot(const Plane& p, const Vector3& v) { return p.x * v.x + p.y * v.y + p.z * v.z; } CUDA_CALLABLE inline float Dot(const Vector3& v, const Plane& p) { return Dot(p, v); } // helper function that assumes a w of 1 CUDA_CALLABLE inline float Dot(const Plane& p, const Point3& v) { return p.x * v.x + p.y * v.y + p.z * v.z + p.w; } // ensures that the normal component of the plane is unit magnitude CUDA_CALLABLE inline Vec4 NormalizePlane(const Vec4& p) { float l = Length(Vec3(p)); return (1.0f / l) * p; } //---------------------------------------------------------------------------- inline float RandomUnit() { float r = (float)rand(); r /= RAND_MAX; return r; } // Random number in range [-1,1] inline float RandomSignedUnit() { float r = (float)rand(); r /= RAND_MAX; r = 2.0f * r - 1.0f; return r; } inline float Random(float lo, float hi) { float r = (float)rand(); r /= RAND_MAX; r = (hi - lo) * r + lo; return r; } inline void RandInit(uint32_t seed = 315645664) { std::srand(static_cast<unsigned>(seed)); } // random number generator inline uint32_t Rand() { return static_cast<uint32_t>(std::rand()); } // returns a random number in the range [min, max) inline uint32_t Rand(uint32_t min, uint32_t max) { return min + Rand() % (max - min); } // returns random number between 0-1 inline float Randf() { uint32_t value = Rand(); uint32_t limit = 0xffffffff; return (float)value * (1.0f / (float)limit); } // returns random number between min and max inline float Randf(float min, float max) { // return Lerp(min, max, ParticleRandf()); float t = Randf(); return (1.0f - t) * min + t * (max); } // returns random number between 0-max inline float Randf(float max) { return Randf() * max; } // returns a random unit vector (also can add an offset to generate around an off axis vector) inline Vec3 RandomUnitVector() { float phi = Randf(kPi * 2.0f); float theta = Randf(kPi * 2.0f); float cosTheta = Cos(theta); float sinTheta = Sin(theta); float cosPhi = Cos(phi); float sinPhi = Sin(phi); return Vec3(cosTheta * sinPhi, cosPhi, sinTheta * sinPhi); } inline Vec3 RandVec3() { return Vec3(Randf(-1.0f, 1.0f), Randf(-1.0f, 1.0f), Randf(-1.0f, 1.0f)); } // uniformly sample volume of a sphere using dart throwing inline Vec3 UniformSampleSphereVolume() { for (;;) { Vec3 v = RandVec3(); if (Dot(v, v) < 1.0f) return v; } } inline Vec3 UniformSampleSphere() { float u1 = Randf(0.0f, 1.0f); float u2 = Randf(0.0f, 1.0f); float z = 1.f - 2.f * u1; float r = sqrtf(Max(0.f, 1.f - z * z)); float phi = 2.f * kPi * u2; float x = r * cosf(phi); float y = r * sinf(phi); return Vector3(x, y, z); } inline Vec3 UniformSampleHemisphere() { // generate a random z value float z = Randf(0.0f, 1.0f); float w = Sqrt(1.0f - z * z); float phi = k2Pi * Randf(0.0f, 1.0f); float x = Cos(phi) * w; float y = Sin(phi) * w; return Vec3(x, y, z); } inline Vec2 UniformSampleDisc() { float r = Sqrt(Randf(0.0f, 1.0f)); float theta = k2Pi * Randf(0.0f, 1.0f); return Vec2(r * Cos(theta), r * Sin(theta)); } inline void UniformSampleTriangle(float& u, float& v) { float r = Sqrt(Randf()); u = 1.0f - r; v = Randf() * r; } inline Vec3 CosineSampleHemisphere() { Vec2 s = UniformSampleDisc(); float z = Sqrt(Max(0.0f, 1.0f - s.x * s.x - s.y * s.y)); return Vec3(s.x, s.y, z); } inline Vec3 SphericalToXYZ(float theta, float phi) { float cosTheta = cos(theta); float sinTheta = sin(theta); return Vec3(sin(phi) * sinTheta, cosTheta, cos(phi) * sinTheta); } // returns random vector between -range and range inline Vec4 Randf(const Vec4& range) { return Vec4(Randf(-range.x, range.x), Randf(-range.y, range.y), Randf(-range.z, range.z), Randf(-range.w, range.w)); } // generates a transform matrix with v as the z axis, taken from PBRT CUDA_CALLABLE inline void BasisFromVector(const Vec3& w, Vec3* u, Vec3* v) { if (fabsf(w.x) > fabsf(w.y)) { float invLen = 1.0f / sqrtf(w.x * w.x + w.z * w.z); *u = Vec3(-w.z * invLen, 0.0f, w.x * invLen); } else { float invLen = 1.0f / sqrtf(w.y * w.y + w.z * w.z); *u = Vec3(0.0f, w.z * invLen, -w.y * invLen); } *v = Cross(w, *u); // assert(fabsf(Length(*u)-1.0f) < 0.01f); // assert(fabsf(Length(*v)-1.0f) < 0.01f); } // same as above but returns a matrix inline Mat44 TransformFromVector(const Vec3& w, const Point3& t = Point3(0.0f, 0.0f, 0.0f)) { Mat44 m = Mat44::Identity(); m.SetCol(2, Vec4(w.x, w.y, w.z, 0.0)); m.SetCol(3, Vec4(t.x, t.y, t.z, 1.0f)); BasisFromVector(w, (Vec3*)m.columns[0], (Vec3*)m.columns[1]); return m; } // todo: sort out rotations inline Mat44 ViewMatrix(const Point3& pos) { float view[4][4] = { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f }, { -pos.x, -pos.y, -pos.z, 1.0f } }; return Mat44(&view[0][0]); } inline Mat44 LookAtMatrix(const Point3& viewer, const Point3& target) { // create a basis from viewer to target (OpenGL convention looking down -z) Vec3 forward = -Normalize(target - viewer); Vec3 up(0.0f, 1.0f, 0.0f); Vec3 left = Normalize(Cross(up, forward)); up = Cross(forward, left); float xform[4][4] = { { left.x, left.y, left.z, 0.0f }, { up.x, up.y, up.z, 0.0f }, { forward.x, forward.y, forward.z, 0.0f }, { viewer.x, viewer.y, viewer.z, 1.0f } }; return AffineInverse(Mat44(&xform[0][0])); } // generate a rotation matrix around an axis, from PBRT p74 inline Mat44 RotationMatrix(float angle, const Vec3& axis) { Vec3 a = Normalize(axis); float s = sinf(angle); float c = cosf(angle); float m[4][4]; m[0][0] = a.x * a.x + (1.0f - a.x * a.x) * c; m[0][1] = a.x * a.y * (1.0f - c) + a.z * s; m[0][2] = a.x * a.z * (1.0f - c) - a.y * s; m[0][3] = 0.0f; m[1][0] = a.x * a.y * (1.0f - c) - a.z * s; m[1][1] = a.y * a.y + (1.0f - a.y * a.y) * c; m[1][2] = a.y * a.z * (1.0f - c) + a.x * s; m[1][3] = 0.0f; m[2][0] = a.x * a.z * (1.0f - c) + a.y * s; m[2][1] = a.y * a.z * (1.0f - c) - a.x * s; m[2][2] = a.z * a.z + (1.0f - a.z * a.z) * c; m[2][3] = 0.0f; m[3][0] = 0.0f; m[3][1] = 0.0f; m[3][2] = 0.0f; m[3][3] = 1.0f; return Mat44(&m[0][0]); } inline Mat44 RotationMatrix(const Quat& q) { Matrix33 rotation(q); Matrix44 m; m.SetAxis(0, rotation.cols[0]); m.SetAxis(1, rotation.cols[1]); m.SetAxis(2, rotation.cols[2]); m.SetTranslation(Point3(0.0f)); return m; } inline Mat44 TranslationMatrix(const Point3& t) { Mat44 m(Mat44::Identity()); m.SetTranslation(t); return m; } inline Mat44 TransformMatrix(const Transform& t) { return TranslationMatrix(Point3(t.p)) * RotationMatrix(t.q); } inline Mat44 OrthographicMatrix(float left, float right, float bottom, float top, float n, float f) { float m[4][4] = { { 2.0f / (right - left), 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f / (top - bottom), 0.0f, 0.0f }, { 0.0f, 0.0f, -2.0f / (f - n), 0.0f }, { -(right + left) / (right - left), -(top + bottom) / (top - bottom), -(f + n) / (f - n), 1.0f } }; return Mat44(&m[0][0]); } // this is designed as a drop in replacement for gluPerspective inline Mat44 ProjectionMatrix(float fov, float aspect, float znear, float zfar) { float f = 1.0f / tanf(DegToRad(fov * 0.5f)); float zd = znear - zfar; float view[4][4] = { { f / aspect, 0.0f, 0.0f, 0.0f }, { 0.0f, f, 0.0f, 0.0f }, { 0.0f, 0.0f, (zfar + znear) / zd, -1.0f }, { 0.0f, 0.0f, (2.0f * znear * zfar) / zd, 0.0f } }; return Mat44(&view[0][0]); } // encapsulates an orientation encoded in Euler angles, not the sexiest // representation but it is convenient when manipulating objects from script class Rotation { public: Rotation() : yaw(0), pitch(0), roll(0) { } Rotation(float inYaw, float inPitch, float inRoll) : yaw(inYaw), pitch(inPitch), roll(inRoll) { } Rotation& operator+=(const Rotation& rhs) { yaw += rhs.yaw; pitch += rhs.pitch; roll += rhs.roll; return *this; } Rotation& operator-=(const Rotation& rhs) { yaw -= rhs.yaw; pitch -= rhs.pitch; roll -= rhs.roll; return *this; } Rotation operator+(const Rotation& rhs) const { Rotation lhs(*this); lhs += rhs; return lhs; } Rotation operator-(const Rotation& rhs) const { Rotation lhs(*this); lhs -= rhs; return lhs; } // all members are in degrees (easy editing) float yaw; float pitch; float roll; }; inline Mat44 ScaleMatrix(const Vector3& s) { float m[4][4] = { { s.x, 0.0f, 0.0f, 0.0f }, { 0.0f, s.y, 0.0f, 0.0f }, { 0.0f, 0.0f, s.z, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; return Mat44(&m[0][0]); } // assumes yaw on y, then pitch on z, then roll on x inline Mat44 TransformMatrix(const Rotation& r, const Point3& p) { const float yaw = DegToRad(r.yaw); const float pitch = DegToRad(r.pitch); const float roll = DegToRad(r.roll); const float s1 = Sin(roll); const float c1 = Cos(roll); const float s2 = Sin(pitch); const float c2 = Cos(pitch); const float s3 = Sin(yaw); const float c3 = Cos(yaw); // interprets the angles as yaw around world-y, pitch around new z, roll around new x float mr[4][4] = { { c2 * c3, s2, -c2 * s3, 0.0f }, { s1 * s3 - c1 * c3 * s2, c1 * c2, c3 * s1 + c1 * s2 * s3, 0.0f }, { c3 * s1 * s2 + c1 * s3, -c2 * s1, c1 * c3 - s1 * s2 * s3, 0.0f }, { p.x, p.y, p.z, 1.0f } }; Mat44 m1(&mr[0][0]); return m1; // m2 * m1; } // aligns the z axis along the vector inline Rotation AlignToVector(const Vec3& vector) { // todo: fix, see spherical->cartesian coordinates wikipedia return Rotation(0.0f, RadToDeg(atan2(vector.y, vector.x)), 0.0f); } // creates a vector given an angle measured clockwise from horizontal (1,0) inline Vec2 AngleToVector(float a) { return Vec2(Cos(a), Sin(a)); } inline float VectorToAngle(const Vec2& v) { return atan2f(v.y, v.x); } CUDA_CALLABLE inline float SmoothStep(float a, float b, float t) { t = Clamp(t - a / (b - a), 0.0f, 1.0f); return t * t * (3.0f - 2.0f * t); } // hermite spline interpolation template <typename T> T HermiteInterpolate(const T& a, const T& b, const T& t1, const T& t2, float t) { // blending weights const float w1 = 1.0f - 3 * t * t + 2 * t * t * t; const float w2 = t * t * (3.0f - 2.0f * t); const float w3 = t * t * t - 2 * t * t + t; const float w4 = t * t * (t - 1.0f); // return weighted combination return a * w1 + b * w2 + t1 * w3 + t2 * w4; } template <typename T> T HermiteTangent(const T& a, const T& b, const T& t1, const T& t2, float t) { // first derivative blend weights const float w1 = 6.0f * t * t - 6 * t; const float w2 = -6.0f * t * t + 6 * t; const float w3 = 3 * t * t - 4 * t + 1; const float w4 = 3 * t * t - 2 * t; // weighted combination return a * w1 + b * w2 + t1 * w3 + t2 * w4; } template <typename T> T HermiteSecondDerivative(const T& a, const T& b, const T& t1, const T& t2, float t) { // first derivative blend weights const float w1 = 12 * t - 6.0f; const float w2 = -12.0f * t + 6; const float w3 = 6 * t - 4.0f; const float w4 = 6 * t - 2.0f; // weighted combination return a * w1 + b * w2 + t1 * w3 + t2 * w4; } inline float Log(float base, float x) { // calculate the log of a value for an arbitary base, only use if you can't use the standard bases (10, e) return logf(x) / logf(base); } inline int Log2(int x) { int n = 0; while (x >= 2) { ++n; x /= 2; } return n; } // function which maps a value to a range template <typename T> T RangeMap(T value, T lower, T upper) { assert(upper >= lower); return (value - lower) / (upper - lower); } // simple colour class class Colour { public: enum Preset { kRed, kGreen, kBlue, kWhite, kBlack }; Colour(float r_ = 0.0f, float g_ = 0.0f, float b_ = 0.0f, float a_ = 1.0f) : r(r_), g(g_), b(b_), a(a_) { } Colour(float* p) : r(p[0]), g(p[1]), b(p[2]), a(p[3]) { } Colour(uint32_t rgba) { a = ((rgba)&0xff) / 255.0f; r = ((rgba >> 24) & 0xff) / 255.0f; g = ((rgba >> 16) & 0xff) / 255.0f; b = ((rgba >> 8) & 0xff) / 255.0f; } Colour(Preset p) { switch (p) { case kRed: *this = Colour(1.0f, 0.0f, 0.0f); break; case kGreen: *this = Colour(0.0f, 1.0f, 0.0f); break; case kBlue: *this = Colour(0.0f, 0.0f, 1.0f); break; case kWhite: *this = Colour(1.0f, 1.0f, 1.0f); break; case kBlack: *this = Colour(0.0f, 0.0f, 0.0f); break; }; } // cast operator operator const float*() const { return &r; } operator float*() { return &r; } Colour operator*(float scale) const { Colour r(*this); r *= scale; return r; } Colour operator/(float scale) const { Colour r(*this); r /= scale; return r; } Colour operator+(const Colour& v) const { Colour r(*this); r += v; return r; } Colour operator-(const Colour& v) const { Colour r(*this); r -= v; return r; } Colour operator*(const Colour& scale) const { Colour r(*this); r *= scale; return r; } Colour& operator*=(float scale) { r *= scale; g *= scale; b *= scale; a *= scale; return *this; } Colour& operator/=(float scale) { float s(1.0f / scale); r *= s; g *= s; b *= s; a *= s; return *this; } Colour& operator+=(const Colour& v) { r += v.r; g += v.g; b += v.b; a += v.a; return *this; } Colour& operator-=(const Colour& v) { r -= v.r; g -= v.g; b -= v.b; a -= v.a; return *this; } Colour& operator*=(const Colour& v) { r *= v.r; g *= v.g; b *= v.b; a *= v.a; return *this; } float r, g, b, a; }; inline bool operator==(const Colour& lhs, const Colour& rhs) { return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b && lhs.a == rhs.a; } inline bool operator!=(const Colour& lhs, const Colour& rhs) { return !(lhs == rhs); } inline Colour ToneMap(const Colour& s) { // return Colour(s.r / (s.r+1.0f), s.g / (s.g+1.0f), s.b / (s.b+1.0f), 1.0f); float Y = 0.3333f * (s.r + s.g + s.b); return s / (1.0f + Y); } // lhs scalar scale inline Colour operator*(float lhs, const Colour& rhs) { Colour r(rhs); r *= lhs; return r; } inline Colour YxyToXYZ(float Y, float x, float y) { float X = x * (Y / y); float Z = (1.0f - x - y) * Y / y; return Colour(X, Y, Z, 1.0f); } inline Colour HSVToRGB(float h, float s, float v) { float r, g, b; int i; float f, p, q, t; if (s == 0) { // achromatic (grey) r = g = b = v; } else { h *= 6.0f; // sector 0 to 5 i = int(floor(h)); f = h - i; // factorial part of h p = v * (1 - s); q = v * (1 - s * f); t = v * (1 - s * (1 - f)); switch (i) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; default: // case 5: r = v; g = p; b = q; break; }; } return Colour(r, g, b); } inline Colour XYZToLinear(float x, float y, float z) { float c[4]; c[0] = 3.240479f * x + -1.537150f * y + -0.498535f * z; c[1] = -0.969256f * x + 1.875991f * y + 0.041556f * z; c[2] = 0.055648f * x + -0.204043f * y + 1.057311f * z; c[3] = 1.0f; return Colour(c); } inline uint32_t ColourToRGBA8(const Colour& c) { union SmallColor { uint8_t u8[4]; uint32_t u32; }; SmallColor s; s.u8[0] = (uint8_t)(Clamp(c.r, 0.0f, 1.0f) * 255); s.u8[1] = (uint8_t)(Clamp(c.g, 0.0f, 1.0f) * 255); s.u8[2] = (uint8_t)(Clamp(c.b, 0.0f, 1.0f) * 255); s.u8[3] = (uint8_t)(Clamp(c.a, 0.0f, 1.0f) * 255); return s.u32; } inline Colour LinearToSrgb(const Colour& c) { const float kInvGamma = 1.0f / 2.2f; return Colour(powf(c.r, kInvGamma), powf(c.g, kInvGamma), powf(c.b, kInvGamma), c.a); } inline Colour SrgbToLinear(const Colour& c) { const float kInvGamma = 2.2f; return Colour(powf(c.r, kInvGamma), powf(c.g, kInvGamma), powf(c.b, kInvGamma), c.a); } inline float SpecularRoughnessToExponent(float roughness, float maxExponent = 2048.0f) { return powf(maxExponent, 1.0f - roughness); } inline float SpecularExponentToRoughness(float exponent, float maxExponent = 2048.0f) { if (exponent <= 1.0f) return 1.0f; else return 1.0f - logf(exponent) / logf(maxExponent); } inline Colour JetColorMap(float low, float high, float x) { float t = (x - low) / (high - low); return HSVToRGB(t, 1.0f, 1.0f); } inline Colour BourkeColorMap(float low, float high, float v) { Colour c(1.0f, 1.0f, 1.0f); // white float dv; if (v < low) v = low; if (v > high) v = high; dv = high - low; if (v < (low + 0.25f * dv)) { c.r = 0.f; c.g = 4.f * (v - low) / dv; } else if (v < (low + 0.5f * dv)) { c.r = 0.f; c.b = 1.f + 4.f * (low + 0.25f * dv - v) / dv; } else if (v < (low + 0.75f * dv)) { c.r = 4.f * (v - low - 0.5f * dv) / dv; c.b = 0.f; } else { c.g = 1.f + 4.f * (low + 0.75f * dv - v) / dv; c.b = 0.f; } return (c); } // intersection routines inline bool IntersectRaySphere(const Point3& sphereOrigin, float sphereRadius, const Point3& rayOrigin, const Vec3& rayDir, float& t, Vec3* hitNormal = nullptr) { Vec3 d(sphereOrigin - rayOrigin); float deltaSq = LengthSq(d); float radiusSq = sphereRadius * sphereRadius; // if the origin is inside the sphere return no intersection if (deltaSq > radiusSq) { float dprojr = Dot(d, rayDir); // if ray pointing away from sphere no intersection if (dprojr < 0.0f) return false; // bit of Pythagoras to get closest point on ray float dSq = deltaSq - dprojr * dprojr; if (dSq > radiusSq) return false; else { // length of the half cord float thc = sqrt(radiusSq - dSq); // closest intersection t = dprojr - thc; // calculate normal if requested if (hitNormal) *hitNormal = Normalize((rayOrigin + rayDir * t) - sphereOrigin); return true; } } else { return false; } } template <typename T> CUDA_CALLABLE inline bool SolveQuadratic(T a, T b, T c, T& minT, T& maxT) { if (a == 0.0f && b == 0.0f) { minT = maxT = 0.0f; return true; } T discriminant = b * b - T(4.0) * a * c; if (discriminant < 0.0f) { return false; } // numerical receipes 5.6 (this method ensures numerical accuracy is preserved) T t = T(-0.5) * (b + Sign(b) * Sqrt(discriminant)); minT = t / a; maxT = c / t; if (minT > maxT) { Swap(minT, maxT); } return true; } // alternative ray sphere intersect, returns closest and furthest t values inline bool IntersectRaySphere(const Point3& sphereOrigin, float sphereRadius, const Point3& rayOrigin, const Vector3& rayDir, float& minT, float& maxT, Vec3* hitNormal = nullptr) { Vector3 q = rayOrigin - sphereOrigin; float a = 1.0f; float b = 2.0f * Dot(q, rayDir); float c = Dot(q, q) - (sphereRadius * sphereRadius); bool r = SolveQuadratic(a, b, c, minT, maxT); if (minT < 0.0) minT = 0.0f; // calculate the normal of the closest hit if (hitNormal && r) { *hitNormal = Normalize((rayOrigin + rayDir * minT) - sphereOrigin); } return r; } CUDA_CALLABLE inline bool IntersectRayPlane(const Point3& p, const Vector3& dir, const Plane& plane, float& t) { float d = Dot(plane, dir); if (d == 0.0f) { return false; } else { t = -Dot(plane, p) / d; } return (t > 0.0f); } CUDA_CALLABLE inline bool IntersectLineSegmentPlane(const Vec3& start, const Vec3& end, const Plane& plane, Vec3& out) { Vec3 u(end - start); float dist = -Dot(plane, start) / Dot(plane, u); if (dist > 0.0f && dist < 1.0f) { out = (start + u * dist); return true; } else return false; } // Moller and Trumbore's method CUDA_CALLABLE inline bool IntersectRayTriTwoSided(const Vec3& p, const Vec3& dir, const Vec3& a, const Vec3& b, const Vec3& c, float& t, float& u, float& v, float& w, float& sign, Vec3* normal) { Vector3 ab = b - a; Vector3 ac = c - a; Vector3 n = Cross(ab, ac); float d = Dot(-dir, n); float ood = 1.0f / d; // No need to check for division by zero here as infinity aritmetic will save us... Vector3 ap = p - a; t = Dot(ap, n) * ood; if (t < 0.0f) return false; Vector3 e = Cross(-dir, ap); v = Dot(ac, e) * ood; if (v < 0.0f || v > 1.0f) // ...here... return false; w = -Dot(ab, e) * ood; if (w < 0.0f || v + w > 1.0f) // ...and here return false; u = 1.0f - v - w; if (normal) *normal = n; sign = d; return true; } // mostly taken from Real Time Collision Detection - p192 inline bool IntersectRayTri(const Point3& p, const Vec3& dir, const Point3& a, const Point3& b, const Point3& c, float& t, float& u, float& v, float& w, Vec3* normal) { const Vec3 ab = b - a; const Vec3 ac = c - a; // calculate normal Vec3 n = Cross(ab, ac); // need to solve a system of three equations to give t, u, v float d = Dot(-dir, n); // if dir is parallel to triangle plane or points away from triangle if (d <= 0.0f) return false; Vec3 ap = p - a; t = Dot(ap, n); // ignores tris behind if (t < 0.0f) return false; // compute barycentric coordinates Vec3 e = Cross(-dir, ap); v = Dot(ac, e); if (v < 0.0f || v > d) return false; w = -Dot(ab, e); if (w < 0.0f || v + w > d) return false; float ood = 1.0f / d; t *= ood; v *= ood; w *= ood; u = 1.0f - v - w; // optionally write out normal (todo: this branch is a performance concern, should probably remove) if (normal) *normal = n; return true; } // mostly taken from Real Time Collision Detection - p192 CUDA_CALLABLE inline bool IntersectSegmentTri(const Vec3& p, const Vec3& q, const Vec3& a, const Vec3& b, const Vec3& c, float& t, float& u, float& v, float& w, Vec3* normal) { const Vec3 ab = b - a; const Vec3 ac = c - a; const Vec3 qp = p - q; // calculate normal Vec3 n = Cross(ab, ac); // need to solve a system of three equations to give t, u, v float d = Dot(qp, n); // if dir is parallel to triangle plane or points away from triangle // if (d <= 0.0f) // return false; Vec3 ap = p - a; t = Dot(ap, n); // ignores tris behind if (t < 0.0f) return false; // ignores tris beyond segment if (t > d) return false; // compute barycentric coordinates Vec3 e = Cross(qp, ap); v = Dot(ac, e); if (v < 0.0f || v > d) return false; w = -Dot(ab, e); if (w < 0.0f || v + w > d) return false; float ood = 1.0f / d; t *= ood; v *= ood; w *= ood; u = 1.0f - v - w; // optionally write out normal (todo: this branch is a performance concern, should probably remove) if (normal) *normal = n; return true; } CUDA_CALLABLE inline float ScalarTriple(const Vec3& a, const Vec3& b, const Vec3& c) { return Dot(Cross(a, b), c); } // intersects a line (through points p and q, against a triangle a, b, c - mostly taken from Real Time Collision // Detection - p186 CUDA_CALLABLE inline bool IntersectLineTri( const Vec3& p, const Vec3& q, const Vec3& a, const Vec3& b, const Vec3& c) //, float& t, float& u, float& v, float& // w, Vec3* normal, float expand) { const Vec3 pq = q - p; const Vec3 pa = a - p; const Vec3 pb = b - p; const Vec3 pc = c - p; Vec3 m = Cross(pq, pc); float u = Dot(pb, m); if (u < 0.0f) return false; float v = -Dot(pa, m); if (v < 0.0f) return false; float w = ScalarTriple(pq, pb, pa); if (w < 0.0f) return false; return true; } CUDA_CALLABLE inline Vec3 ClosestPointToAABB(const Vec3& p, const Vec3& lower, const Vec3& upper) { Vec3 c; for (int i = 0; i < 3; ++i) { float v = p[i]; if (v < lower[i]) v = lower[i]; if (v > upper[i]) v = upper[i]; c[i] = v; } return c; } // RTCD 5.1.5, page 142 CUDA_CALLABLE inline Vec3 ClosestPointOnTriangle( const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& p, float& v, float& w) { Vec3 ab = b - a; Vec3 ac = c - a; Vec3 ap = p - a; float d1 = Dot(ab, ap); float d2 = Dot(ac, ap); if (d1 <= 0.0f && d2 <= 0.0f) { v = 0.0f; w = 0.0f; return a; } Vec3 bp = p - b; float d3 = Dot(ab, bp); float d4 = Dot(ac, bp); if (d3 >= 0.0f && d4 <= d3) { v = 1.0f; w = 0.0f; return b; } float vc = d1 * d4 - d3 * d2; if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f) { v = d1 / (d1 - d3); w = 0.0f; return a + v * ab; } Vec3 cp = p - c; float d5 = Dot(ab, cp); float d6 = Dot(ac, cp); if (d6 >= 0.0f && d5 <= d6) { v = 0.0f; w = 1.0f; return c; } float vb = d5 * d2 - d1 * d6; if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f) { v = 0.0f; w = d2 / (d2 - d6); return a + w * ac; } float va = d3 * d6 - d5 * d4; if (va <= 0.0f && (d4 - d3) >= 0.0f && (d5 - d6) >= 0.0f) { w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); v = 1.0f - w; return b + w * (c - b); } float denom = 1.0f / (va + vb + vc); v = vb * denom; w = vc * denom; return a + ab * v + ac * w; } CUDA_CALLABLE inline Vec3 ClosestPointOnFatTriangle( const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& p, const float thickness, float& v, float& w) { const Vec3 x = ClosestPointOnTriangle(a, b, c, p, v, w); const Vec3 d = SafeNormalize(p - x); // apply thickness along delta dir return x + d * thickness; } // computes intersection between a ray and a triangle expanded by a constant thickness, also works for ray-sphere and // ray-capsule this is an iterative method similar to sphere tracing but for convex objects, see // http://dtecta.com/papers/jgt04raycast.pdf CUDA_CALLABLE inline bool IntersectRayFatTriangle(const Vec3& p, const Vec3& dir, const Vec3& a, const Vec3& b, const Vec3& c, float thickness, float threshold, float maxT, float& t, float& u, float& v, float& w, Vec3* normal) { t = 0.0f; Vec3 x = p; Vec3 n; float distSq; const float thresholdSq = threshold * threshold; const int maxIterations = 20; for (int i = 0; i < maxIterations; ++i) { const Vec3 closestPoint = ClosestPointOnFatTriangle(a, b, c, x, thickness, v, w); n = x - closestPoint; distSq = LengthSq(n); // early out if (distSq <= thresholdSq) break; float ndir = Dot(n, dir); // we've gone past the convex if (ndir >= 0.0f) return false; // we've exceeded max ray length if (t > maxT) return false; t = t - distSq / ndir; x = p + t * dir; } // calculate normal based on unexpanded geometry to avoid precision issues Vec3 cp = ClosestPointOnTriangle(a, b, c, x, v, w); n = x - cp; // if n faces away due to numerical issues flip it to face ray dir if (Dot(n, dir) > 0.0f) n *= -1.0f; u = 1.0f - v - w; *normal = SafeNormalize(n); return true; } CUDA_CALLABLE inline float SqDistPointSegment(Vec3 a, Vec3 b, Vec3 c) { Vec3 ab = b - a, ac = c - a, bc = c - b; float e = Dot(ac, ab); if (e <= 0.0f) return Dot(ac, ac); float f = Dot(ab, ab); if (e >= f) return Dot(bc, bc); return Dot(ac, ac) - e * e / f; } CUDA_CALLABLE inline bool PointInTriangle(Vec3 a, Vec3 b, Vec3 c, Vec3 p) { a -= p; b -= p; c -= p; /* float eps = 0.0f; float ab = Dot(a, b); float ac = Dot(a, c); float bc = Dot(b, c); float cc = Dot(c, c); if (bc *ac - cc * ab <= eps) return false; float bb = Dot(b, b); if (ab * bc - ac*bb <= eps) return false; return true; */ Vec3 u = Cross(b, c); Vec3 v = Cross(c, a); if (Dot(u, v) <= 0.0f) return false; Vec3 w = Cross(a, b); if (Dot(u, w) <= 0.0f) return false; return true; } CUDA_CALLABLE inline void ClosestPointBetweenLineSegments( const Vec3& p, const Vec3& q, const Vec3& r, const Vec3& s, float& u, float& v) { Vec3 d1 = q - p; Vec3 d2 = s - r; Vec3 rp = p - r; float a = Dot(d1, d1); float c = Dot(d1, rp); float e = Dot(d2, d2); float f = Dot(d2, rp); float b = Dot(d1, d2); float denom = a * e - b * b; if (denom != 0.0f) u = Clamp((b * f - c * e) / denom, 0.0f, 1.0f); else { u = 0.0f; } v = (b * u + f) / e; if (v < 0.0f) { v = 0.0f; u = Clamp(-c / a, 0.0f, 1.0f); } else if (v > 1.0f) { v = 1.0f; u = Clamp((b - c) / a, 0.0f, 1.0f); } } CUDA_CALLABLE inline float ClosestPointBetweenLineSegmentAndTri( const Vec3& p, const Vec3& q, const Vec3& a, const Vec3& b, const Vec3& c, float& outT, float& outV, float& outW) { float minDsq = FLT_MAX; float minT, minV, minW; float t, u, v, w, dSq; Vec3 r, s; // test if line segment intersects tri if (IntersectSegmentTri(p, q, a, b, c, t, u, v, w, nullptr)) { outT = t; outV = v; outW = w; return 0.0f; } // edge ab ClosestPointBetweenLineSegments(p, q, a, b, t, v); r = p + (q - p) * t; s = a + (b - a) * v; dSq = LengthSq(r - s); if (dSq < minDsq) { minDsq = dSq; minT = u; // minU = 1.0f-v minV = v; minW = 0.0f; } // edge bc ClosestPointBetweenLineSegments(p, q, b, c, t, w); r = p + (q - p) * t; s = b + (c - b) * w; dSq = LengthSq(r - s); if (dSq < minDsq) { minDsq = dSq; minT = t; // minU = 0.0f; minV = 1.0f - w; minW = w; } // edge ca ClosestPointBetweenLineSegments(p, q, c, a, t, u); r = p + (q - p) * t; s = c + (a - c) * u; dSq = LengthSq(r - s); if (dSq < minDsq) { minDsq = dSq; minT = t; // minU = u; minV = 0.0f; minW = 1.0f - u; } // end point p ClosestPointOnTriangle(a, b, c, p, v, w); s = a * (1.0f - v - w) + b * v + c * w; dSq = LengthSq(s - p); if (dSq < minDsq) { minDsq = dSq; minT = 0.0f; minV = v; minW = w; } // end point q ClosestPointOnTriangle(a, b, c, q, v, w); s = a * (1.0f - v - w) + b * v + c * w; dSq = LengthSq(s - q); if (dSq < minDsq) { minDsq = dSq; minT = 1.0f; minV = v; minW = w; } // write mins outT = minT; outV = minV; outW = minW; return sqrtf(minDsq); } CUDA_CALLABLE inline float minf(const float a, const float b) { return a < b ? a : b; } CUDA_CALLABLE inline float maxf(const float a, const float b) { return a > b ? a : b; } CUDA_CALLABLE inline bool IntersectRayAABBFast( const Vec3& pos, const Vector3& rcp_dir, const Vector3& min, const Vector3& max, float& t) { float l1 = (min.x - pos.x) * rcp_dir.x, l2 = (max.x - pos.x) * rcp_dir.x, lmin = minf(l1, l2), lmax = maxf(l1, l2); l1 = (min.y - pos.y) * rcp_dir.y; l2 = (max.y - pos.y) * rcp_dir.y; lmin = maxf(minf(l1, l2), lmin); lmax = minf(maxf(l1, l2), lmax); l1 = (min.z - pos.z) * rcp_dir.z; l2 = (max.z - pos.z) * rcp_dir.z; lmin = maxf(minf(l1, l2), lmin); lmax = minf(maxf(l1, l2), lmax); // return ((lmax > 0.f) & (lmax >= lmin)); // return ((lmax > 0.f) & (lmax > lmin)); bool hit = ((lmax >= 0.f) & (lmax >= lmin)); if (hit) t = lmin; return hit; } CUDA_CALLABLE inline bool IntersectRayAABB( const Vec3& start, const Vector3& dir, const Vector3& min, const Vector3& max, float& t, Vector3* normal) { //! calculate candidate plane on each axis float tx = -1.0f, ty = -1.0f, tz = -1.0f; bool inside = true; //! use unrolled loops //! x if (start.x < min.x) { if (dir.x != 0.0f) tx = (min.x - start.x) / dir.x; inside = false; } else if (start.x > max.x) { if (dir.x != 0.0f) tx = (max.x - start.x) / dir.x; inside = false; } //! y if (start.y < min.y) { if (dir.y != 0.0f) ty = (min.y - start.y) / dir.y; inside = false; } else if (start.y > max.y) { if (dir.y != 0.0f) ty = (max.y - start.y) / dir.y; inside = false; } //! z if (start.z < min.z) { if (dir.z != 0.0f) tz = (min.z - start.z) / dir.z; inside = false; } else if (start.z > max.z) { if (dir.z != 0.0f) tz = (max.z - start.z) / dir.z; inside = false; } //! if point inside all planes if (inside) { t = 0.0f; return true; } //! we now have t values for each of possible intersection planes //! find the maximum to get the intersection point float tmax = tx; int taxis = 0; if (ty > tmax) { tmax = ty; taxis = 1; } if (tz > tmax) { tmax = tz; taxis = 2; } if (tmax < 0.0f) return false; //! check that the intersection point lies on the plane we picked //! we don't test the axis of closest intersection for precision reasons //! no eps for now float eps = 0.0f; Vec3 hit = start + dir * tmax; if ((hit.x < min.x - eps || hit.x > max.x + eps) && taxis != 0) return false; if ((hit.y < min.y - eps || hit.y > max.y + eps) && taxis != 1) return false; if ((hit.z < min.z - eps || hit.z > max.z + eps) && taxis != 2) return false; //! output results t = tmax; return true; } // construct a plane equation such that ax + by + cz + dw = 0 CUDA_CALLABLE inline Vec4 PlaneFromPoints(const Vec3& p, const Vec3& q, const Vec3& r) { Vec3 e0 = q - p; Vec3 e1 = r - p; Vec3 n = SafeNormalize(Cross(e0, e1)); return Vec4(n.x, n.y, n.z, -Dot(p, n)); } CUDA_CALLABLE inline bool IntersectPlaneAABB(const Vec4& plane, const Vec3& center, const Vec3& extents) { float radius = Abs(extents.x * plane.x) + Abs(extents.y * plane.y) + Abs(extents.z * plane.z); float delta = Dot(center, Vec3(plane)) + plane.w; return Abs(delta) <= radius; } // 2d rectangle class class Rect { public: Rect() : m_left(0), m_right(0), m_top(0), m_bottom(0) { } Rect(uint32_t left, uint32_t right, uint32_t top, uint32_t bottom) : m_left(left), m_right(right), m_top(top), m_bottom(bottom) { assert(left <= right); assert(top <= bottom); } uint32_t Width() const { return m_right - m_left; } uint32_t Height() const { return m_bottom - m_top; } // expand rect x units in each direction void Expand(uint32_t x) { m_left -= x; m_right += x; m_top -= x; m_bottom += x; } uint32_t Left() const { return m_left; } uint32_t Right() const { return m_right; } uint32_t Top() const { return m_top; } uint32_t Bottom() const { return m_bottom; } bool Contains(uint32_t x, uint32_t y) const { return (x >= m_left) && (x <= m_right) && (y >= m_top) && (y <= m_bottom); } uint32_t m_left; uint32_t m_right; uint32_t m_top; uint32_t m_bottom; }; // doesn't really belong here but efficient (and I believe correct) in place random shuffle based on the Fisher-Yates / // Knuth algorithm template <typename T> void RandomShuffle(T begin, T end) { assert(end > begin); uint32_t n = distance(begin, end); for (uint32_t i = 0; i < n; ++i) { // pick a random number between 0 and n-1 uint32_t r = Rand() % (n - i); // swap that location with the current randomly selected position swap(*(begin + i), *(begin + (i + r))); } } CUDA_CALLABLE inline Quat QuatFromAxisAngle(const Vec3& axis, float angle) { Vec3 v = Normalize(axis); float half = angle * 0.5f; float w = cosf(half); const float sin_theta_over_two = sinf(half); v *= sin_theta_over_two; return Quat(v.x, v.y, v.z, w); } // rotate by quaternion (q, w) CUDA_CALLABLE inline Vec3 rotate(const Vec3& q, float w, const Vec3& x) { return 2.0f * (x * (w * w - 0.5f) + Cross(q, x) * w + q * Dot(q, x)); } // rotate x by inverse transform in (q, w) CUDA_CALLABLE inline Vec3 rotateInv(const Vec3& q, float w, const Vec3& x) { return 2.0f * (x * (w * w - 0.5f) - Cross(q, x) * w + q * Dot(q, x)); } // get rotation from u to v CUDA_CALLABLE inline Quat GetRotationQuat(const Vec3& _u, const Vec3& _v) { Vec3 u = Normalize(_u); Vec3 v = Normalize(_v); // check for aligned vectors float d = Dot(u, v); if (d > 1.0f - 1e-6f) { // vectors are colinear, return identity return Quat(); } else if (d < 1e-6f - 1.0f) { // vectors are opposite, return a 180 degree rotation Vec3 axis = Cross({ 1.0f, 0.0f, 0.0f }, u); if (LengthSq(axis) < 1e-6f) { axis = Cross({ 0.0f, 1.0f, 0.0f }, u); } return QuatFromAxisAngle(Normalize(axis), kPi); } else { Vec3 c = Cross(u, v); float s = sqrtf((1.0f + d) * 2.0f); float invs = 1.0f / s; Quat q(invs * c.x, invs * c.y, invs * c.z, 0.5f * s); return Normalize(q); } } CUDA_CALLABLE inline void TransformBounds(const Quat& q, Vec3 extents, Vec3& newExtents) { Matrix33 transform(q); transform.cols[0] *= extents.x; transform.cols[1] *= extents.y; transform.cols[2] *= extents.z; float ex = fabsf(transform.cols[0].x) + fabsf(transform.cols[1].x) + fabsf(transform.cols[2].x); float ey = fabsf(transform.cols[0].y) + fabsf(transform.cols[1].y) + fabsf(transform.cols[2].y); float ez = fabsf(transform.cols[0].z) + fabsf(transform.cols[1].z) + fabsf(transform.cols[2].z); newExtents = Vec3(ex, ey, ez); } CUDA_CALLABLE inline void TransformBounds(const Vec3& localLower, const Vec3& localUpper, const Vec3& translation, const Quat& rotation, float scale, Vec3& lower, Vec3& upper) { Matrix33 transform(rotation); Vec3 extents = (localUpper - localLower) * scale; transform.cols[0] *= extents.x; transform.cols[1] *= extents.y; transform.cols[2] *= extents.z; float ex = fabsf(transform.cols[0].x) + fabsf(transform.cols[1].x) + fabsf(transform.cols[2].x); float ey = fabsf(transform.cols[0].y) + fabsf(transform.cols[1].y) + fabsf(transform.cols[2].y); float ez = fabsf(transform.cols[0].z) + fabsf(transform.cols[1].z) + fabsf(transform.cols[2].z); Vec3 center = (localUpper + localLower) * 0.5f * scale; lower = rotation * center + translation - Vec3(ex, ey, ez) * 0.5f; upper = rotation * center + translation + Vec3(ex, ey, ez) * 0.5f; } // Poisson sample the volume of a sphere with given separation inline int PoissonSample3D(float radius, float separation, Vec3* points, int maxPoints, int maxAttempts) { // naive O(n^2) dart throwing algorithm to generate a Poisson distribution int c = 0; while (c < maxPoints) { int a = 0; while (a < maxAttempts) { const Vec3 p = UniformSampleSphereVolume() * radius; // test against points already generated int i = 0; for (; i < c; ++i) { Vec3 d = p - points[i]; // reject if closer than separation if (LengthSq(d) < separation * separation) break; } // sample passed all tests, accept if (i == c) { points[c] = p; ++c; break; } ++a; } // exit if we reached the max attempts and didn't manage to add a point if (a == maxAttempts) break; } return c; } inline int PoissonSampleBox3D(Vec3 lower, Vec3 upper, float separation, Vec3* points, int maxPoints, int maxAttempts) { // naive O(n^2) dart throwing algorithm to generate a Poisson distribution int c = 0; while (c < maxPoints) { int a = 0; while (a < maxAttempts) { const Vec3 p = Vec3(Randf(lower.x, upper.x), Randf(lower.y, upper.y), Randf(lower.z, upper.z)); // test against points already generated int i = 0; for (; i < c; ++i) { Vec3 d = p - points[i]; // reject if closer than separation if (LengthSq(d) < separation * separation) break; } // sample passed all tests, accept if (i == c) { points[c] = p; ++c; break; } ++a; } // exit if we reached the max attempts and didn't manage to add a point if (a == maxAttempts) break; } return c; } // Generates an optimally dense sphere packing at the origin (implicit sphere at the origin) inline int TightPack3D(float radius, float separation, Vec3* points, int maxPoints) { int dim = int(ceilf(radius / separation)); int c = 0; for (int z = -dim; z <= dim; ++z) { for (int y = -dim; y <= dim; ++y) { for (int x = -dim; x <= dim; ++x) { float xpos = x * separation + (((y + z) & 1) ? separation * 0.5f : 0.0f); float ypos = y * sqrtf(0.75f) * separation; float zpos = z * sqrtf(0.75f) * separation; Vec3 p(xpos, ypos, zpos); // skip center if (LengthSq(p) == 0.0f) continue; if (c < maxPoints && Length(p) <= radius) { points[c] = p; ++c; } } } } return c; } struct Bounds { CUDA_CALLABLE inline Bounds() : lower(FLT_MAX), upper(-FLT_MAX) { } CUDA_CALLABLE inline Bounds(const Vec3& lower, const Vec3& upper) : lower(lower), upper(upper) { } CUDA_CALLABLE inline Vec3 GetCenter() const { return 0.5f * (lower + upper); } CUDA_CALLABLE inline Vec3 GetEdges() const { return upper - lower; } CUDA_CALLABLE inline void Expand(float r) { lower -= Vec3(r); upper += Vec3(r); } CUDA_CALLABLE inline void Expand(const Vec3& r) { lower -= r; upper += r; } CUDA_CALLABLE inline bool Empty() const { return lower.x >= upper.x || lower.y >= upper.y || lower.z >= upper.z; } CUDA_CALLABLE inline bool Overlaps(const Vec3& p) const { if (p.x < lower.x || p.y < lower.y || p.z < lower.z || p.x > upper.x || p.y > upper.y || p.z > upper.z) { return false; } else { return true; } } CUDA_CALLABLE inline bool Overlaps(const Bounds& b) const { if (lower.x > b.upper.x || lower.y > b.upper.y || lower.z > b.upper.z || upper.x < b.lower.x || upper.y < b.lower.y || upper.z < b.lower.z) { return false; } else { return true; } } Vec3 lower; Vec3 upper; }; CUDA_CALLABLE inline Bounds Union(const Bounds& a, const Vec3& b) { return Bounds(Min(a.lower, b), Max(a.upper, b)); } CUDA_CALLABLE inline Bounds Union(const Bounds& a, const Bounds& b) { return Bounds(Min(a.lower, b.lower), Max(a.upper, b.upper)); } CUDA_CALLABLE inline Bounds Intersection(const Bounds& a, const Bounds& b) { return Bounds(Max(a.lower, b.lower), Min(a.upper, b.upper)); } CUDA_CALLABLE inline float SurfaceArea(const Bounds& b) { Vec3 e = b.upper - b.lower; return 2.0f * (e.x * e.y + e.x * e.z + e.y * e.z); } inline void ExtractFrustumPlanes(const Matrix44& m, Plane* planes) { // Based on Fast Extraction of Viewing Frustum Planes from the WorldView-Projection Matrix, Gill Grib, Klaus // Hartmann // Left clipping plane planes[0].x = m(3, 0) + m(0, 0); planes[0].y = m(3, 1) + m(0, 1); planes[0].z = m(3, 2) + m(0, 2); planes[0].w = m(3, 3) + m(0, 3); // Right clipping plane planes[1].x = m(3, 0) - m(0, 0); planes[1].y = m(3, 1) - m(0, 1); planes[1].z = m(3, 2) - m(0, 2); planes[1].w = m(3, 3) - m(0, 3); // Top clipping plane planes[2].x = m(3, 0) - m(1, 0); planes[2].y = m(3, 1) - m(1, 1); planes[2].z = m(3, 2) - m(1, 2); planes[2].w = m(3, 3) - m(1, 3); // Bottom clipping plane planes[3].x = m(3, 0) + m(1, 0); planes[3].y = m(3, 1) + m(1, 1); planes[3].z = m(3, 2) + m(1, 2); planes[3].w = m(3, 3) + m(1, 3); // Near clipping plane planes[4].x = m(3, 0) + m(2, 0); planes[4].y = m(3, 1) + m(2, 1); planes[4].z = m(3, 2) + m(2, 2); planes[4].w = m(3, 3) + m(2, 3); // Far clipping plane planes[5].x = m(3, 0) - m(2, 0); planes[5].y = m(3, 1) - m(2, 1); planes[5].z = m(3, 2) - m(2, 2); planes[5].w = m(3, 3) - m(2, 3); NormalizePlane(planes[0]); NormalizePlane(planes[1]); NormalizePlane(planes[2]); NormalizePlane(planes[3]); NormalizePlane(planes[4]); NormalizePlane(planes[5]); } inline bool TestSphereAgainstFrustum(const Plane* planes, Vec3 center, float radius) { for (int i = 0; i < 6; ++i) { float d = -Dot(planes[i], Point3(center)) - radius; if (d > 0.0f) return false; } return true; }
53,776
C
23.169438
121
0.501674
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/types.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "stdint.h" #include <cstddef>
748
C
34.666665
99
0.751337
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/common_math.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "core.h" #include "types.h" #include <cassert> #include <cmath> #include <float.h> #include <string.h> #ifdef __CUDACC__ # define CUDA_CALLABLE __host__ __device__ #else # define CUDA_CALLABLE #endif #define kPi 3.141592653589f const float k2Pi = 2.0f * kPi; const float kInvPi = 1.0f / kPi; const float kInv2Pi = 0.5f / kPi; const float kDegToRad = kPi / 180.0f; const float kRadToDeg = 180.0f / kPi; CUDA_CALLABLE inline float DegToRad(float t) { return t * kDegToRad; } CUDA_CALLABLE inline float RadToDeg(float t) { return t * kRadToDeg; } CUDA_CALLABLE inline float Sin(float theta) { return sinf(theta); } CUDA_CALLABLE inline float Cos(float theta) { return cosf(theta); } CUDA_CALLABLE inline void SinCos(float theta, float& s, float& c) { // no optimizations yet s = sinf(theta); c = cosf(theta); } CUDA_CALLABLE inline float Tan(float theta) { return tanf(theta); } CUDA_CALLABLE inline float Sqrt(float x) { return sqrtf(x); } CUDA_CALLABLE inline double Sqrt(double x) { return sqrt(x); } CUDA_CALLABLE inline float ASin(float theta) { return asinf(theta); } CUDA_CALLABLE inline float ACos(float theta) { return acosf(theta); } CUDA_CALLABLE inline float ATan(float theta) { return atanf(theta); } CUDA_CALLABLE inline float ATan2(float x, float y) { return atan2f(x, y); } CUDA_CALLABLE inline float Abs(float x) { return fabsf(x); } CUDA_CALLABLE inline float Pow(float b, float e) { return powf(b, e); } CUDA_CALLABLE inline float Sgn(float x) { return (x < 0.0f ? -1.0f : 1.0f); } CUDA_CALLABLE inline float Sign(float x) { return x < 0.0f ? -1.0f : 1.0f; } CUDA_CALLABLE inline double Sign(double x) { return x < 0.0f ? -1.0f : 1.0f; } CUDA_CALLABLE inline float Mod(float x, float y) { return fmod(x, y); } template <typename T> CUDA_CALLABLE inline T Min(T a, T b) { return a < b ? a : b; } template <typename T> CUDA_CALLABLE inline T Max(T a, T b) { return a > b ? a : b; } template <typename T> CUDA_CALLABLE inline void Swap(T& a, T& b) { T tmp = a; a = b; b = tmp; } template <typename T> CUDA_CALLABLE inline T Clamp(T a, T low, T high) { if (low > high) Swap(low, high); return Max(low, Min(a, high)); } template <typename V, typename T> CUDA_CALLABLE inline V Lerp(const V& start, const V& end, const T& t) { return start + (end - start) * t; } CUDA_CALLABLE inline float InvSqrt(float x) { return 1.0f / sqrtf(x); } // round towards +infinity CUDA_CALLABLE inline int Round(float f) { return int(f + 0.5f); } template <typename T> CUDA_CALLABLE T Normalize(const T& v) { T a(v); a /= Length(v); return a; } template <typename T> CUDA_CALLABLE inline typename T::value_type LengthSq(const T v) { return Dot(v, v); } template <typename T> CUDA_CALLABLE inline typename T::value_type Length(const T& v) { typename T::value_type lSq = LengthSq(v); if (lSq) return Sqrt(LengthSq(v)); else return 0.0f; } // this is mainly a helper function used by script template <typename T> CUDA_CALLABLE inline typename T::value_type Distance(const T& v1, const T& v2) { return Length(v1 - v2); } template <typename T> CUDA_CALLABLE inline T SafeNormalize(const T& v, const T& fallback = T()) { float l = LengthSq(v); if (l > 0.0f) { return v * InvSqrt(l); } else return fallback; } template <typename T> CUDA_CALLABLE inline T Sqr(T x) { return x * x; } template <typename T> CUDA_CALLABLE inline T Cube(T x) { return x * x * x; }
4,322
C
17.714286
99
0.662656
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/math/core/core.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #define ENABLE_VERBOSE_OUTPUT 0 #define ENABLE_APIC_CAPTURE 0 #define ENABLE_PERFALYZE_CAPTURE 0 #if ENABLE_VERBOSE_OUTPUT # define VERBOSE(a) a##; #else # define VERBOSE(a) #endif //#define Super __super // basically just a collection of macros and types #ifndef UNUSED # define UNUSED(x) (void)x; #endif #define NOMINMAX #if !PLATFORM_OPENCL # include <cassert> #endif #include "types.h" #if !PLATFORM_SPU && !PLATFORM_OPENCL # include <algorithm> # include <fstream> # include <functional> # include <iostream> # include <string> #endif #include <string.h> // disable some warnings #if _WIN32 # pragma warning(disable : 4996) // secure io # pragma warning(disable : 4100) // unreferenced param # pragma warning(disable : 4324) // structure was padded due to __declspec(align()) #endif // alignment helpers #define DEFAULT_ALIGNMENT 16 #if PLATFORM_LINUX # define ALIGN_N(x) # define ENDALIGN_N(x) __attribute__((aligned(x))) #else # define ALIGN_N(x) __declspec(align(x)) # define END_ALIGN_N(x) #endif #define ALIGN ALIGN_N(DEFAULT_ALIGNMENT) #define END_ALIGN END_ALIGN_N(DEFAULT_ALIGNMENT) inline bool IsPowerOfTwo(int n) { return (n & (n - 1)) == 0; } // align a ptr to a power of tow template <typename T> inline T* AlignPtr(T* p, uint32_t alignment) { assert(IsPowerOfTwo(alignment)); // cast to safe ptr type uintptr_t up = reinterpret_cast<uintptr_t>(p); return (T*)((up + (alignment - 1)) & ~(alignment - 1)); } // align an unsigned value to a power of two inline uint32_t Align(uint32_t val, uint32_t alignment) { assert(IsPowerOfTwo(alignment)); return (val + (alignment - 1)) & ~(alignment - 1); } inline bool IsAligned(void* p, uint32_t alignment) { return (((uintptr_t)p) & (alignment - 1)) == 0; } template <typename To, typename From> To UnionCast(From in) { union { To t; From f; }; f = in; return t; } // Endian helpers template <typename T> T ByteSwap(const T& val) { T copy = val; uint8_t* p = reinterpret_cast<uint8_t*>(&copy); std::reverse(p, p + sizeof(T)); return copy; } #ifndef LITTLE_ENDIAN # define LITTLE_ENDIAN WIN32 #endif #ifndef BIG_ENDIAN # define BIG_ENDIAN PLATFORM_PS3 || PLATFORM_SPU #endif #if BIG_ENDIAN # define ToLittleEndian(x) ByteSwap(x) #else # define ToLittleEndian(x) x #endif //#include "platform.h" //#define sizeof_array(x) (sizeof(x)/sizeof(*x)) template <typename T, size_t N> size_t sizeof_array(const T (&)[N]) { return N; } // unary_function depricated in c++11 // functor designed for use in the stl // template <typename T> // class free_ptr : public std::unary_function<T*, void> //{ // public: // void operator()(const T* ptr) // { // delete ptr; // } //}; // given the path of one file it strips the filename and appends the relative path onto it inline void MakeRelativePath(const char* filePath, const char* fileRelativePath, char* fullPath) { // get base path of file const char* lastSlash = nullptr; if (!lastSlash) lastSlash = strrchr(filePath, '\\'); if (!lastSlash) lastSlash = strrchr(filePath, '/'); int baseLength = 0; if (lastSlash) { baseLength = int(lastSlash - filePath) + 1; // copy base path (including slash to relative path) memcpy(fullPath, filePath, baseLength); } // if (fileRelativePath[0] == '.') //++fileRelativePath; if (fileRelativePath[0] == '\\' || fileRelativePath[0] == '/') ++fileRelativePath; // append mesh filename strcpy(fullPath + baseLength, fileRelativePath); }
4,375
C
21.441026
99
0.662171
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/KinematicChain.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "KinematicChain.h" #include <carb/logging/Log.h> #include <algorithm> namespace omni { namespace importer { namespace urdf { KinematicChain::~KinematicChain() { baseNode.reset(); } // Computes the kinematic chain for a Urdf robot bool KinematicChain::computeKinematicChain(const UrdfRobot& urdfRobot) { bool success = true; if (urdfRobot.joints.empty()) { if (urdfRobot.links.empty()) { CARB_LOG_ERROR("*** URDF robot is empty \n"); success = false; } else if (urdfRobot.links.size() == 1) { baseNode = std::make_unique<Node>(urdfRobot.links.begin()->second.name, ""); } else { CARB_LOG_ERROR("*** URDF has multiple links that are not connected to a joint \n"); success = false; } } else { std::vector<std::string> childLinkNames; for (auto& joint : urdfRobot.joints) { childLinkNames.push_back(joint.second.childLinkName); } // Find the base link std::string baseLinkName; for (auto& link : urdfRobot.links) { if (std::find(childLinkNames.begin(), childLinkNames.end(), link.second.name) == childLinkNames.end()) { CARB_LOG_INFO("Found base link called %s \n", link.second.name.c_str()); baseLinkName = link.second.name; break; } } if (baseLinkName.empty()) { CARB_LOG_ERROR("*** Could not find base link \n"); success = false; } baseNode = std::make_unique<Node>(baseLinkName, ""); // Recursively add the rest of the kinematic chain computeChildNodes(baseNode, urdfRobot); } return success; } void KinematicChain::computeChildNodes(std::unique_ptr<Node>& parentNode, const UrdfRobot& urdfRobot) { for (auto& joint : urdfRobot.joints) { if (joint.second.parentLinkName == parentNode->linkName_) { std::unique_ptr<Node> childNode = std::make_unique<Node>(joint.second.childLinkName, joint.second.name); parentNode->childNodes_.push_back(std::move(childNode)); CARB_LOG_INFO("Link %s has child %s \n", parentNode->linkName_.c_str(), joint.second.childLinkName.c_str()); } } if (parentNode->childNodes_.empty()) { return; } else { for (auto& childLink : parentNode->childNodes_) { computeChildNodes(childLink, urdfRobot); } } } } } }
3,295
C++
27.17094
120
0.607587
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/ImportHelpers.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once // clang-format off #include "../UsdPCH.h" // clang-format on #include "../parse/UrdfParser.h" #include "KinematicChain.h" #include "../math/core/maths.h" #include "../UrdfTypes.h" namespace omni { namespace importer { namespace urdf { Quat indexedRotation(int axis, float s, float c); Vec3 Diagonalize(const Matrix33& m, Quat& massFrame); void inertiaToUrdf(const Matrix33& inertia, UrdfInertia& urdfInertia); void urdfToInertia(const UrdfInertia& urdfInertia, Matrix33& inertia); void mergeFixedChildLinks(const KinematicChain::Node& parentNode, UrdfRobot& robot); bool collapseFixedJoints(UrdfRobot& robot); Vec3 urdfAxisToVec(const UrdfAxis& axis); std::string resolveXrefPath(const std::string& assetRoot, const std::string& urdfPath, const std::string& xrefpath); bool IsUsdFile(const std::string& filename); // Make a path name that is not already used. std::string GetNewSdfPathString(pxr::UsdStageWeakPtr stage, std::string path, int nameClashNum = -1); bool addVisualMeshToCollision(UrdfRobot& robot); } } }
1,731
C
32.960784
116
0.76372
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/ImportHelpers.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ImportHelpers.h" #include "../core/PathUtils.h" #include <carb/logging/Log.h> #include <boost/algorithm/string.hpp> namespace omni { namespace importer { namespace urdf { Quat indexedRotation(int axis, float s, float c) { float v[3] = { 0, 0, 0 }; v[axis] = s; return Quat(v[0], v[1], v[2], c); } Vec3 Diagonalize(const Matrix33& m, Quat& massFrame) { const int MAX_ITERS = 24; Quat q = Quat(); Matrix33 d; for (int i = 0; i < MAX_ITERS; i++) { Matrix33 axes; quat2Mat(q, axes); d = Transpose(axes) * m * axes; float d0 = fabs(d(1, 2)), d1 = fabs(d(0, 2)), d2 = fabs(d(0, 1)); // rotation axis index, from largest off-diagonal element int a = int(d0 > d1 && d0 > d2 ? 0 : d1 > d2 ? 1 : 2); int a1 = (a + 1 + (a >> 1)) & 3, a2 = (a1 + 1 + (a1 >> 1)) & 3; if (d(a1, a2) == 0.0f || fabs(d(a1, a1) - d(a2, a2)) > 2e6f * fabs(2.0f * d(a1, a2))) break; // cot(2 * phi), where phi is the rotation angle float w = (d(a1, a1) - d(a2, a2)) / (2.0f * d(a1, a2)); float absw = fabs(w); Quat r; if (absw > 1000) { // h will be very close to 1, so use small angle approx instead r = indexedRotation(a, 1 / (4 * w), 1.f); } else { float t = 1 / (absw + Sqrt(w * w + 1)); // absolute value of tan phi float h = 1 / Sqrt(t * t + 1); // absolute value of cos phi assert(h != 1); // |w|<1000 guarantees this with typical IEEE754 machine eps (approx 6e-8) r = indexedRotation(a, Sqrt((1 - h) / 2) * Sign(w), Sqrt((1 + h) / 2)); } q = Normalize(q * r); } massFrame = q; return Vec3(d.cols[0].x, d.cols[1].y, d.cols[2].z); } void inertiaToUrdf(const Matrix33& inertia, UrdfInertia& urdfInertia) { urdfInertia.ixx = inertia.cols[0].x; urdfInertia.ixy = inertia.cols[0].y; urdfInertia.ixz = inertia.cols[0].z; urdfInertia.iyy = inertia.cols[1].y; urdfInertia.iyz = inertia.cols[1].z; urdfInertia.izz = inertia.cols[2].z; } void urdfToInertia(const UrdfInertia& urdfInertia, Matrix33& inertia) { inertia.cols[0].x = urdfInertia.ixx; inertia.cols[0].y = urdfInertia.ixy; inertia.cols[0].z = urdfInertia.ixz; inertia.cols[1].x = urdfInertia.ixy; inertia.cols[1].y = urdfInertia.iyy; inertia.cols[1].z = urdfInertia.iyz; inertia.cols[2].x = urdfInertia.ixz; inertia.cols[2].y = urdfInertia.iyz; inertia.cols[2].z = urdfInertia.izz; } void mergeFixedChildLinks(const KinematicChain::Node& parentNode, UrdfRobot& robot) { // Child contribution to inertia for (auto& childNode : parentNode.childNodes_) { // Depth first mergeFixedChildLinks(*childNode, robot); if (robot.joints.at(childNode->parentJointName_).type == UrdfJointType::FIXED && !robot.joints.at(childNode->parentJointName_).dontCollapse) { auto& urdfParentLink = robot.links.at(parentNode.linkName_); auto& urdfChildLink = robot.links.at(childNode->linkName_); // The pose of the child with respect to the parent is defined at the joint connecting them Transform poseChildToParent = robot.joints.at(childNode->parentJointName_).origin; //Add a reference to the merged link urdfParentLink.mergedChildren[childNode->linkName_] = poseChildToParent; // At least one of the link masses has to be defined if ((urdfParentLink.inertial.hasMass || urdfChildLink.inertial.hasMass) && (urdfParentLink.inertial.mass > 0.0f || urdfChildLink.inertial.mass > 0.0f)) { // Move inertial parameters to parent Transform parentInertialInParentFrame = urdfParentLink.inertial.origin; Transform childInertialInParentFrame = poseChildToParent * urdfChildLink.inertial.origin; float totMass = urdfParentLink.inertial.mass + urdfChildLink.inertial.mass; Vec3 com = (urdfParentLink.inertial.mass * parentInertialInParentFrame.p + urdfChildLink.inertial.mass * childInertialInParentFrame.p) / totMass; Vec3 deltaParent = parentInertialInParentFrame.p - com; Vec3 deltaChild = childInertialInParentFrame.p - com; Matrix33 rotParentOrigin(parentInertialInParentFrame.q); Matrix33 rotChildOrigin(childInertialInParentFrame.q); Matrix33 parentInertia; Matrix33 childInertia; urdfToInertia(urdfParentLink.inertial.inertia, parentInertia); urdfToInertia(urdfChildLink.inertial.inertia, childInertia); Matrix33 inertiaParent = rotParentOrigin * parentInertia * Transpose(rotParentOrigin) + urdfParentLink.inertial.mass * (LengthSq(deltaParent) * Matrix33::Identity() - Outer(deltaParent, deltaParent)); Matrix33 inertiaChild = rotChildOrigin * childInertia * Transpose(rotChildOrigin) + urdfChildLink.inertial.mass * (LengthSq(deltaChild) * Matrix33::Identity() - Outer(deltaChild, deltaChild)); Matrix33 inertia = Transpose(rotParentOrigin) * (inertiaParent + inertiaChild) * rotParentOrigin; urdfParentLink.inertial.origin.p.x = com.x; urdfParentLink.inertial.origin.p.y = com.y; urdfParentLink.inertial.origin.p.z = com.z; urdfParentLink.inertial.mass = totMass; inertiaToUrdf(inertia, urdfParentLink.inertial.inertia); urdfParentLink.inertial.hasMass = true; urdfParentLink.inertial.hasInertia = true; urdfParentLink.inertial.hasOrigin = true; } // Move collisions to parent for (auto& collision : urdfChildLink.collisions) { collision.origin = poseChildToParent * collision.origin; urdfParentLink.collisions.push_back(collision); } urdfChildLink.collisions.clear(); // Move visuals to parent for (auto& visual : urdfChildLink.visuals) { visual.origin = poseChildToParent * visual.origin; urdfParentLink.visuals.push_back(visual); } urdfChildLink.visuals.clear(); for (auto& joint : robot.joints) { if (joint.second.parentLinkName == childNode->linkName_) { joint.second.parentLinkName = parentNode.linkName_; joint.second.origin = poseChildToParent * joint.second.origin; } } // Remove this link and parent joint // if (!urdfChildLink.softs.size()) // { robot.links.erase(childNode->linkName_); robot.joints.erase(childNode->parentJointName_); // } } } } bool collapseFixedJoints(UrdfRobot& robot) { KinematicChain chain; if (!chain.computeKinematicChain(robot)) { return false; } auto& parentNode = chain.baseNode; if (!parentNode->childNodes_.empty()) { mergeFixedChildLinks(*parentNode, robot); } return true; } Vec3 urdfAxisToVec(const UrdfAxis& axis) { return { axis.x, axis.y, axis.z }; } std::string resolveXrefPath(const std::string& assetRoot, const std::string& urdfPath, const std::string& xrefpath) { // Remove the package prefix if it exists std::string xrefPath = xrefpath; if (xrefPath.find("omniverse://") != std::string::npos) { CARB_LOG_INFO("Path is on nucleus server, will assume that it is fully resolved already"); return xrefPath; } // removal of any prefix ending with "://" std::size_t p = xrefPath.find("://"); if (p != std::string::npos) { xrefPath = xrefPath.substr(p + 3); // +3 to remove "://" } if (isAbsolutePath(xrefPath.c_str())) { if (testPath(xrefPath.c_str()) == PathType::eFile) { return xrefPath; } else { // xref not found return std::string(); } } std::string rootPath; if (isAbsolutePath(urdfPath.c_str())) { rootPath = urdfPath; } else { rootPath = pathJoin(assetRoot, urdfPath); } auto s = rootPath.find_last_of("/\\"); while (s != std::string::npos && s > 0) { auto basePath = rootPath.substr(0, s + 1); auto path = pathJoin(basePath, xrefPath); CARB_LOG_INFO("trying '%s' (%d)\n", path.c_str(), int(testPath(path.c_str()))); if (testPath(path.c_str()) == PathType::eFile) { return path; } // if (strncmp(basePath.c_str(), assetRoot.c_str(), s) == 0) // { // // don't search upwards of assetRoot // break; // } s = rootPath.find_last_of("/\\", s - 1); } // hmmm, should we accept pure relative paths? if (testPath(xrefPath.c_str()) == PathType::eFile) { return xrefPath; } // Check if ROS_PACKAGE_PATH is defined and if so go through all searching for the package char* exists = getenv("ROS_PACKAGE_PATH"); if (exists != NULL) { std::string rosPackagePath = std::string(exists); if (rosPackagePath.size()) { std::vector<std::string> results; boost::split(results, rosPackagePath, [](char c) { return c == ':'; }); for (size_t i = 0; i < results.size(); i++) { std::string path = results[i]; if (path.size() > 0) { auto packagePath = pathJoin(path, xrefPath); CARB_LOG_INFO("Testing ROS Package path '%s' (%d)\n", packagePath.c_str(), int(testPath(packagePath.c_str()))); if (testPath(packagePath.c_str()) == PathType::eFile) { return packagePath; } } } } } else { CARB_LOG_WARN("ROS_PACKAGE_PATH not defined, will skip checking ROS packages"); } CARB_LOG_WARN("Path: %s not found", xrefpath.c_str()); // if we got here, we failed to resolve the path return std::string(); } bool IsUsdFile(const std::string& filename) { std::vector<std::string> types = { ".usd", ".usda" }; for (auto& t : types) { if (t.size() > filename.size()) continue; if (std::equal(t.rbegin(), t.rend(), filename.rbegin())) { return true; } } return false; } // Make a path name that is not already used. std::string GetNewSdfPathString(pxr::UsdStageWeakPtr stage, std::string path, int nameClashNum) { bool appendedNumber = false; int numberAppended = std::max<int>(nameClashNum, 0); size_t indexOfNumber = 0; if (stage->GetPrimAtPath(pxr::SdfPath(path))) { appendedNumber = true; std::string name = pxr::SdfPath(path).GetName(); size_t last_ = name.find_last_of('_'); indexOfNumber = path.length() + 1; if (last_ == std::string::npos) { // no '_' found, so just tack on the end. path += "_" + std::to_string(numberAppended); } else { // There was a _, if the last part of that is a number // then replace that number with one higher or nameClashNum, // or just tack on the number if it is last character. if (last_ == name.length() - 1) { path += "_" + std::to_string(numberAppended); } else { char* p; std::string after_ = name.substr(last_ + 1, name.length()); long converted = strtol(after_.c_str(), &p, 10); if (*p) { // not a number path += "_" + std::to_string(numberAppended); } else { numberAppended = nameClashNum == -1 ? converted + 1 : nameClashNum; indexOfNumber = path.length() - name.length() + last_ + 1; path = path.substr(0, indexOfNumber); path += std::to_string(numberAppended); } } } } if (appendedNumber) { // we just added a number, so we have to make sure the new path is unique. while (stage->GetPrimAtPath(pxr::SdfPath(path))) { path = path.substr(0, indexOfNumber); numberAppended += 1; path += std::to_string(numberAppended); } } #if 0 else { while (stage->GetPrimAtPath(pxr::SdfPath(path))) path += ":" + std::to_string(nameClashNum); } #endif return path; } bool addVisualMeshToCollision(UrdfRobot& robot) { for (auto& link : robot.links) { if (!link.second.visuals.empty() && link.second.collisions.empty()) { for (auto& visual : link.second.visuals) { UrdfCollision collision{ visual.name, visual.origin, visual.geometry }; link.second.collisions.push_back(collision); } } } return true; } } } }
14,465
C++
32.87822
119
0.554787
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/MeshImporter.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "MeshImporter.h" #include <carb/logging/Log.h> #include "../core/PathUtils.h" #include "ImportHelpers.h" #include "assimp/Importer.hpp" #include "assimp/postprocess.h" #if __has_include(<filesystem>) #include <filesystem> #elif __has_include(<experimental/filesystem>) #include <experimental/filesystem> #else error "Missing the <filesystem> header." #endif #include "../utils/Path.h" #include <OmniClient.h> #include <cmath> #include <set> #include <stack> #include <unordered_set> namespace omni { namespace importer { namespace urdf { using namespace omni::importer::utils::path; const static size_t INVALID_MATERIAL_INDEX = SIZE_MAX; struct ImportTransform { pxr::GfMatrix4d matrix; pxr::GfVec3f translation; pxr::GfVec3f eulerAngles; // XYZ order pxr::GfVec3f scale; }; struct MeshGeomSubset { pxr::VtArray<int> faceIndices; size_t materialIndex = INVALID_MATERIAL_INDEX; }; struct Mesh { std::string name; pxr::VtArray<pxr::GfVec3f> points; pxr::VtArray<int> faceVertexCounts; pxr::VtArray<int> faceVertexIndices; pxr::VtArray<pxr::GfVec3f> normals; // Face varing normals pxr::VtArray<pxr::VtArray<pxr::GfVec2f>> uvs; // Face varing uvs pxr::VtArray<pxr::VtArray<pxr::GfVec3f>> colors; // Face varing colors std::vector<MeshGeomSubset> meshSubsets; }; // static pxr::GfMatrix4d AiMatrixToGfMatrix(const aiMatrix4x4& matrix) // { // return pxr::GfMatrix4d(matrix.a1, matrix.b1, matrix.c1, matrix.d1, matrix.a2, matrix.b2, matrix.c2, matrix.d2, // matrix.a3, matrix.b3, matrix.c3, matrix.d3, matrix.a4, matrix.b4, matrix.c4, matrix.d4); // } static pxr::GfVec3f AiVector3dToGfVector3f(const aiVector3D& vector) { return pxr::GfVec3f(vector.x, vector.y, vector.z); } static pxr::GfVec2f AiVector3dToGfVector2f(const aiVector3D& vector) { return pxr::GfVec2f(vector.x, vector.y); } // static pxr::GfVec3h AiVector3dToGfVector3h(const aiVector3D& vector) // { // return pxr::GfVec3h(vector.x, vector.y, vector.z); // } // static pxr::GfQuatf AiQuatToGfVector(const aiQuaternion& quat) // { // return pxr::GfQuatf(quat.w, quat.x, quat.y, quat.z); // } // static pxr::GfQuath AiQuatToGfVectorh(const aiQuaternion& quat) // { // return pxr::GfQuath(quat.w, quat.x, quat.y, quat.z); // } // static pxr::GfVec3f AiColor3DToGfVector3f(const aiColor3D& color) // { // return pxr::GfVec3f(color.r, color.g, color.b); // } // static ImportTransform AiMatrixToTransform(const aiMatrix4x4& matrix) // { // ImportTransform transform; // transform.matrix = // pxr::GfMatrix4d(matrix.a1, matrix.b1, matrix.c1, matrix.d1, matrix.a2, matrix.b2, matrix.c2, matrix.d2, // matrix.a3, matrix.b3, matrix.c3, matrix.d3, matrix.a4, matrix.b4, matrix.c4, matrix.d4); // aiVector3D translation, rotation, scale; // matrix.Decompose(scale, rotation, translation); // transform.translation = AiVector3dToGfVector3f(translation); // transform.eulerAngles = AiVector3dToGfVector3f( // aiVector3D(AI_RAD_TO_DEG(rotation.x), AI_RAD_TO_DEG(rotation.y), AI_RAD_TO_DEG(rotation.z))); // transform.scale = AiVector3dToGfVector3f(scale); // return transform; // } pxr::GfVec3f AiColor4DToGfVector3f(const aiColor4D& color) { return pxr::GfVec3f(color.r, color.g, color.b); } struct MeshMaterial { std::string name; std::string texturePaths[5]; bool has_diffuse; aiColor3D diffuse; bool has_emissive; aiColor3D emissive; bool has_metallic; float metallic{ 0 }; bool has_specular; float specular{ 0 }; aiTextureType textures[5] = { aiTextureType_DIFFUSE, aiTextureType_HEIGHT, aiTextureType_REFLECTION, aiTextureType_EMISSIVE, aiTextureType_SHININESS }; const char* props[5] = { "diffuse_texture", "normalmap_texture", "metallic_texture", "emissive_mask_texture", "reflectionroughness_texture", }; MeshMaterial(aiMaterial* m) { name = std::string(m->GetName().C_Str()); std::array<aiTextureMapMode, 2> modes; aiString path; for (int i = 0; i < 5; i++) { if (m->GetTexture(textures[i], 0, &path, nullptr, nullptr, nullptr, nullptr, modes.data()) == aiReturn_SUCCESS) { texturePaths[i] = std::string(path.C_Str()); } } has_diffuse = (m->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse) == aiReturn_SUCCESS); has_metallic = (m->Get(AI_MATKEY_METALLIC_FACTOR, metallic) == aiReturn_SUCCESS); has_specular = (m->Get(AI_MATKEY_SPECULAR_FACTOR, specular) == aiReturn_SUCCESS); has_emissive = (m->Get(AI_MATKEY_COLOR_EMISSIVE, emissive) == aiReturn_SUCCESS); } std::string get_hash() { std::ostringstream ss; ss << name; for (int i = 0; i < 5; i++) { if (texturePaths[i] != "") { ss << std::string(props[i]) + texturePaths[i]; } } ss << std::string("D") << diffuse.r << diffuse.g << diffuse.b; ss << std::string("M") << metallic; ss << std::string("S") << specular; ss << std::string("E") << emissive.r << emissive.g << emissive.g; return ss.str(); } }; std::string ReplaceBackwardSlash(std::string in) { for (auto& c : in) { if (c == '\\') { c = '/'; } } return in; } static aiMatrix4x4 GetLocalTransform(const aiNode* node) { aiMatrix4x4 transform = node->mTransformation; auto parent = node->mParent; while (parent) { std::string name = parent->mName.data; // only take scale from root transform, if the parent has a parent then its not a root node if (parent->mParent) { // parent has a parent, not a root note, use full transform transform = parent->mTransformation * transform; parent = parent->mParent; } else { // this is a root node, only take scale aiVector3D pos, scale; aiQuaternion rot; parent->mTransformation.Decompose(scale, rot, pos); aiMatrix4x4 scale_mat; transform = aiMatrix4x4::Scaling(scale, scale_mat) * transform; break; } } return transform; } std::string copyTexture(std::string usdStageIdentifier, std::string texturePath) { // switch any windows-style path into linux backwards slash (omniclient handles windows paths) usdStageIdentifier = ReplaceBackwardSlash(usdStageIdentifier); texturePath = ReplaceBackwardSlash(texturePath); // Assumes the folder structure has already been created. int path_idx = (int)usdStageIdentifier.rfind('/'); std::string parent_folder = usdStageIdentifier.substr(0, path_idx); int basename_idx = (int)texturePath.rfind('/'); std::string textureName = texturePath.substr(basename_idx + 1); std::string out = (parent_folder + "/materials/" + textureName); omniClientWait(omniClientCopy(texturePath.c_str(), out.c_str(), {}, {})); return out; } pxr::SdfPath SimpleImport(pxr::UsdStageRefPtr usdStage, std::string path, const aiScene* mScene, const std::string meshPath, std::map<pxr::TfToken, std::string>& materialsList, const bool loadMaterials, const bool flipVisuals, const char* subdivisionScheme, const bool instanceable) { std::vector<Mesh> mMeshPrims; std::vector<aiNode*> nodesToProcess; std::vector<std::pair<int, aiMatrix4x4>> meshTransforms; // Traverse tree and get all of the meshes and the full transform for that node nodesToProcess.push_back(mScene->mRootNode); std::string mesh_path = ReplaceBackwardSlash(meshPath); int basename_idx = (int)mesh_path.rfind('/'); std::string base_path = mesh_path.substr(0, basename_idx); while (nodesToProcess.size() > 0) { // remove the node aiNode* node = nodesToProcess.back(); if (!node) { // printf("INVALID NODE\n"); continue; } nodesToProcess.pop_back(); aiMatrix4x4 transform = GetLocalTransform(node); for (size_t i = 0; i < node->mNumMeshes; i++) { // if (flipVisuals) // { // aiMatrix4x4 flip; // flip[0][0] = 1.0; // flip[2][1] = 1.0; // flip[1][2] = -1.0; // flip[3][3] = 1.0f; // transform = transform * flip; // } meshTransforms.push_back(std::pair<int, aiMatrix4x4>(node->mMeshes[i], transform)); } // process any meshes in this node: for (size_t i = 0; i < node->mNumChildren; i++) { nodesToProcess.push_back(node->mChildren[i]); } } // printf("%s TOTAL MESHES: %d\n", path.c_str(), meshTransforms.size()); mMeshPrims.resize(meshTransforms.size()); // for (size_t i = 0; i < mScene->mNumMaterials; i++) // { // auto material = mScene->mMaterials[i]; // // printf("AA %d %s \n", i, material->GetName().C_Str()); // } for (size_t i = 0; i < meshTransforms.size(); i++) { auto transformedMesh = meshTransforms[i]; auto assimpMesh = mScene->mMeshes[transformedMesh.first]; // printf("material index: %d \n", assimpMesh->mMaterialIndex); // Gather all mesh points information to sort std::vector<Mesh> meshImported; for (size_t j = 0; j < assimpMesh->mNumVertices; j++) { auto vertex = assimpMesh->mVertices[j]; vertex *= transformedMesh.second; mMeshPrims[i].points.push_back(AiVector3dToGfVector3f(vertex)); } for (size_t j = 0; j < assimpMesh->mNumFaces; j++) { const aiFace& face = assimpMesh->mFaces[j]; if (face.mNumIndices >= 3) { for (size_t k = 0; k < face.mNumIndices; k++) { mMeshPrims[i].faceVertexIndices.push_back(face.mIndices[k]); } } } mMeshPrims[i].uvs.resize(assimpMesh->GetNumUVChannels()); mMeshPrims[i].colors.resize(assimpMesh->GetNumColorChannels()); for (size_t j = 0; j < assimpMesh->mNumFaces; j++) { const aiFace& face = assimpMesh->mFaces[j]; if (face.mNumIndices >= 3) { for (size_t k = 0; k < face.mNumIndices; k++) { if (assimpMesh->mNormals) { mMeshPrims[i].normals.push_back(AiVector3dToGfVector3f(assimpMesh->mNormals[face.mIndices[k]])); } for (size_t m = 0; m < mMeshPrims[i].uvs.size(); m++) { mMeshPrims[i].uvs[m].push_back( AiVector3dToGfVector2f(assimpMesh->mTextureCoords[m][face.mIndices[k]])); } for (size_t m = 0; m < mMeshPrims[i].colors.size(); m++) { mMeshPrims[i].colors[m].push_back(AiColor4DToGfVector3f(assimpMesh->mColors[m][face.mIndices[k]])); } } mMeshPrims[i].faceVertexCounts.push_back(face.mNumIndices); } } } auto usdMesh = pxr::UsdGeomMesh::Define(usdStage, pxr::SdfPath(omni::importer::urdf::GetNewSdfPathString(usdStage, path))); pxr::VtArray<pxr::GfVec3f> allPoints; pxr::VtArray<int> allFaceVertexCounts; pxr::VtArray<int> allFaceVertexIndices; pxr::VtArray<pxr::GfVec3f> allNormals; pxr::VtArray<pxr::VtArray<pxr::GfVec2f>> uvs; pxr::VtArray<pxr::VtArray<pxr::GfVec3f>> allColors; size_t indexOffset = 0; size_t vertexOffset = 0; std::map<int, pxr::VtArray<int>> materialMap; for (size_t m = 0; m < meshTransforms.size(); m++) { auto transformedMesh = meshTransforms[m]; auto mesh = mScene->mMeshes[transformedMesh.first]; auto& meshPrim = mMeshPrims[m]; for (size_t k = 0; k < meshPrim.uvs.size(); k++) { uvs.push_back(meshPrim.uvs[k]); } for (size_t i = 0; i < meshPrim.points.size(); i++) { allPoints.push_back(meshPrim.points[i]); } for (size_t i = 0; i < meshPrim.faceVertexCounts.size(); i++) { allFaceVertexCounts.push_back(meshPrim.faceVertexCounts[i]); } for (size_t i = 0; i < meshPrim.faceVertexIndices.size(); i++) { allFaceVertexIndices.push_back(static_cast<int>(meshPrim.faceVertexIndices[i] + indexOffset)); } for (size_t i = vertexOffset; i < vertexOffset + meshPrim.faceVertexCounts.size(); i++) { materialMap[mesh->mMaterialIndex].push_back(static_cast<int>(i)); } // printf("faceVertexOffset %d %d %d %d\n", indexOffset, points.size(), vertexOffset, faceVertexCounts.size()); indexOffset = indexOffset + meshPrim.points.size(); vertexOffset = vertexOffset + meshPrim.faceVertexCounts.size(); for (size_t i = 0; i < meshPrim.normals.size(); i++) { allNormals.push_back(meshPrim.normals[i]); } } usdMesh.CreatePointsAttr(pxr::VtValue(allPoints)); usdMesh.CreateFaceVertexCountsAttr(pxr::VtValue(allFaceVertexCounts)); usdMesh.CreateFaceVertexIndicesAttr(pxr::VtValue(allFaceVertexIndices)); pxr::VtArray<pxr::GfVec3f> Extent; pxr::UsdGeomPointBased::ComputeExtent(allPoints, &Extent); usdMesh.CreateExtentAttr().Set(Extent); // Normals if (!allNormals.empty()) { usdMesh.CreateNormalsAttr(pxr::VtValue(allNormals)); usdMesh.SetNormalsInterpolation(pxr::UsdGeomTokens->faceVarying); } // Texture UV for (size_t j = 0; j < uvs.size(); j++) { pxr::TfToken stName; if (j == 0) { stName = pxr::TfToken("st"); } else { stName = pxr::TfToken("st_" + std::to_string(j)); } pxr::UsdGeomPrimvarsAPI primvarsAPI(usdMesh); pxr::UsdGeomPrimvar Primvar = primvarsAPI.CreatePrimvar(stName, pxr::SdfValueTypeNames->TexCoord2fArray, pxr::UsdGeomTokens->faceVarying); Primvar.Set(uvs[j]); } usdMesh.CreateSubdivisionSchemeAttr(pxr::VtValue(pxr::TfToken(subdivisionScheme))); if (loadMaterials) { std::string prefix_path; if (instanceable) { prefix_path = pxr::SdfPath(path).GetParentPath().GetString(); // body category root } else { prefix_path = pxr::SdfPath(path).GetParentPath().GetParentPath().GetString(); // Robot root } // For each material, store the face indices and create GeomSubsets usdStage->DefinePrim(pxr::SdfPath(prefix_path + "/Looks"), pxr::TfToken("Scope")); for (auto const& mat : materialMap) { MeshMaterial material(mScene->mMaterials[mat.first]); // printf("materials: %s\n", name.c_str()); pxr::TfToken mat_token(material.get_hash()); // if (std::find(materialsList.begin(), materialsList.end(),mat_token) == materialsList.end()) if (materialsList.find(mat_token) == materialsList.end()) { pxr::UsdPrim prim; pxr::UsdShadeMaterial matPrim; std::string mat_path(prefix_path + "/Looks/" + makeValidUSDIdentifier("material_" + material.name)); prim = usdStage->GetPrimAtPath(pxr::SdfPath(mat_path)); int counter = 0; while (prim) { mat_path = std::string( prefix_path + "/Looks/" + makeValidUSDIdentifier("material_" + material.name + "_" + std::to_string(++counter))); printf("%s \n", mat_path.c_str()); prim = usdStage->GetPrimAtPath(pxr::SdfPath(mat_path)); } materialsList[mat_token] = mat_path; matPrim = pxr::UsdShadeMaterial::Define(usdStage, pxr::SdfPath(mat_path)); pxr::UsdShadeShader pbrShader = pxr::UsdShadeShader::Define(usdStage, pxr::SdfPath(mat_path + "/Shader")); pbrShader.CreateIdAttr(pxr::VtValue(pxr::UsdImagingTokens->UsdPreviewSurface)); auto shader_out = pbrShader.CreateOutput(pxr::TfToken("out"), pxr::SdfValueTypeNames->Token); matPrim.CreateSurfaceOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out); matPrim.CreateVolumeOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out); matPrim.CreateDisplacementOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out); pbrShader.GetImplementationSourceAttr().Set(pxr::UsdShadeTokens->sourceAsset); pbrShader.SetSourceAsset(pxr::SdfAssetPath("OmniPBR.mdl"), pxr::TfToken("mdl")); pbrShader.SetSourceAssetSubIdentifier(pxr::TfToken("OmniPBR"), pxr::TfToken("mdl")); bool has_emissive_map = false; for (int i = 0; i < 5; i++) { if (material.texturePaths[i] != "") { if (!usdStage->GetRootLayer()->IsAnonymous()) { auto texture_path = copyTexture(usdStage->GetRootLayer()->GetIdentifier(), resolve_absolute(base_path, material.texturePaths[i])); int basename_idx = (int)texture_path.rfind('/'); std::string filename = texture_path.substr(basename_idx + 1); std::string texture_relative_path = "materials/" + filename; pbrShader.CreateInput(pxr::TfToken(material.props[i]), pxr::SdfValueTypeNames->Asset) .Set(pxr::SdfAssetPath(texture_relative_path)); if (material.textures[i] == aiTextureType_EMISSIVE) { pbrShader.CreateInput(pxr::TfToken("emissive_color"), pxr::SdfValueTypeNames->Color3f) .Set(pxr::GfVec3f(1.0f, 1.0f, 1.0f)); pbrShader.CreateInput(pxr::TfToken("enable_emission"), pxr::SdfValueTypeNames->Bool) .Set(true); pbrShader.CreateInput(pxr::TfToken("emissive_intensity"), pxr::SdfValueTypeNames->Float) .Set(10000.0f); has_emissive_map = true; } } else { CARB_LOG_WARN( "Material %s has an image texture, but it won't be imported since the asset is being loaded on memory. Please import it into a destination folder to get all textures.", material.name.c_str()); } } } if (material.has_diffuse) { pbrShader.CreateInput(pxr::TfToken("diffuse_color_constant"), pxr::SdfValueTypeNames->Color3f) .Set(pxr::GfVec3f(material.diffuse.r, material.diffuse.g, material.diffuse.b)); } if (material.has_metallic) { pbrShader.CreateInput(pxr::TfToken("metallic_constant"), pxr::SdfValueTypeNames->Float) .Set(material.metallic); } if (material.has_specular) { pbrShader.CreateInput(pxr::TfToken("specular_level"), pxr::SdfValueTypeNames->Float) .Set(material.specular); } if (!has_emissive_map && material.has_emissive) { pbrShader.CreateInput(pxr::TfToken("emissive_color"), pxr::SdfValueTypeNames->Color3f) .Set(pxr::GfVec3f(material.emissive.r, material.emissive.g, material.emissive.b)); } // auto output = matPrim.CreateSurfaceOutput(); // output.ConnectToSource(pbrShader, pxr::TfToken("surface")); } pxr::UsdShadeMaterial matPrim = pxr::UsdShadeMaterial(usdStage->GetPrimAtPath(pxr::SdfPath(materialsList[mat_token]))); if (materialMap.size() > 1) { auto geomSubset = pxr::UsdGeomSubset::Define( usdStage, pxr::SdfPath(usdMesh.GetPath().GetString() + "/material_" + std::to_string(mat.first))); geomSubset.CreateElementTypeAttr(pxr::VtValue(pxr::TfToken("face"))); geomSubset.CreateFamilyNameAttr(pxr::VtValue(pxr::TfToken("materialBind"))); geomSubset.CreateIndicesAttr(pxr::VtValue(mat.second)); if (matPrim) { pxr::UsdShadeMaterialBindingAPI mbi(geomSubset); mbi.Bind(matPrim); } } else { if (matPrim) { pxr::UsdShadeMaterialBindingAPI mbi(usdMesh); mbi.Bind(matPrim); } } } } return usdMesh.GetPath(); } } } }
22,606
C++
36.804348
200
0.566841
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/UrdfImporter.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "UrdfImporter.h" #include "../core/PathUtils.h" #include "UrdfImporter.h" // #include "../../GymJoint.h" // #include "../../helpers.h" #include "assimp/Importer.hpp" #include "assimp/cfileio.h" #include "assimp/cimport.h" #include "assimp/postprocess.h" #include "assimp/scene.h" #include "ImportHelpers.h" #include <carb/logging/Log.h> #include <physicsSchemaTools/UsdTools.h> #include <physxSchema/jointStateAPI.h> #include <physxSchema/physxArticulationAPI.h> #include <physxSchema/physxCollisionAPI.h> #include <physxSchema/physxJointAPI.h> #include <physxSchema/physxTendonAxisRootAPI.h> #include <physxSchema/physxTendonAxisAPI.h> #include <physxSchema/physxSceneAPI.h> #include <pxr/usd/usdPhysics/articulationRootAPI.h> #include <pxr/usd/usdPhysics/collisionAPI.h> #include <pxr/usd/usdPhysics/driveAPI.h> #include <pxr/usd/usdPhysics/fixedJoint.h> #include <pxr/usd/usdPhysics/joint.h> #include <pxr/usd/usdPhysics/limitAPI.h> #include <pxr/usd/usdPhysics/massAPI.h> #include <pxr/usd/usdPhysics/meshCollisionAPI.h> #include <pxr/usd/usdPhysics/prismaticJoint.h> #include <pxr/usd/usdPhysics/revoluteJoint.h> #include <pxr/usd/usdPhysics/rigidBodyAPI.h> #include <pxr/usd/usdPhysics/scene.h> #include <pxr/usd/usdPhysics/sphericalJoint.h> namespace omni { namespace importer { namespace urdf { UrdfRobot UrdfImporter::createAsset() { UrdfRobot robot; if (!parseUrdf(assetRoot_, urdfPath_, robot)) { CARB_LOG_ERROR("Failed to parse URDF file '%s'", urdfPath_.c_str()); return robot; } if (config.mergeFixedJoints) { collapseFixedJoints(robot); } if (config.collisionFromVisuals) { addVisualMeshToCollision(robot); } return robot; } const char* subdivisionschemes[4] = { "catmullClark", "loop", "bilinear", "none" }; pxr::UsdPrim addMesh(pxr::UsdStageWeakPtr stage, UrdfGeometry geometry, std::string assetRoot, std::string urdfPath, std::string name, Transform origin, const bool loadMaterials, const double distanceScale, const bool flipVisuals, std::map<pxr::TfToken, std::string>& materialsList, const char* subdivisionScheme, const bool instanceable = false, const bool replaceCylindersWithCapsules = false) { pxr::SdfPath path; if (geometry.type == UrdfGeometryType::MESH) { std::string meshUri = geometry.meshFilePath; std::string meshPath = resolveXrefPath(assetRoot, urdfPath, meshUri); // pxr::GfMatrix4d meshMat; if (meshPath.empty()) { CARB_LOG_WARN("Failed to resolve mesh '%s'", meshUri.c_str()); return pxr::UsdPrim(); // move to next shape } // mesh is a usd file, add as a reference directly to a new xform else if (IsUsdFile(meshPath)) { CARB_LOG_INFO("Adding Usd reference '%s'", meshPath.c_str()); path = pxr::SdfPath(omni::importer::urdf::GetNewSdfPathString(stage, name)); pxr::UsdGeomXform usdXform = pxr::UsdGeomXform::Define(stage, path); usdXform.GetPrim().GetReferences().AddReference(meshPath); } else { CARB_LOG_INFO("Found Mesh At: %s", meshPath.c_str()); auto assimpScene = aiImportFile(meshPath.c_str(), aiProcess_GenSmoothNormals | aiProcess_OptimizeMeshes | aiProcess_RemoveRedundantMaterials | aiProcess_GlobalScale); static auto sceneDeleter = [](const aiScene* scene) { if (scene) { aiReleaseImport(scene); } }; auto sceneRAII = std::shared_ptr<const aiScene>(assimpScene, sceneDeleter); // Add visuals if (!sceneRAII || !sceneRAII->mRootNode) { CARB_LOG_WARN("Asset convert failed as asset file is broken."); } else if (sceneRAII->mRootNode->mNumChildren == 0) { CARB_LOG_WARN("Asset convert failed as asset cannot be loaded."); } else { path = SimpleImport(stage, name, sceneRAII.get(), meshPath, materialsList, loadMaterials, flipVisuals, subdivisionScheme, instanceable); } } } else if (geometry.type == UrdfGeometryType::SPHERE) { pxr::UsdGeomSphere gprim = pxr::UsdGeomSphere::Define(stage, pxr::SdfPath(name)); pxr::VtVec3fArray extentArray(2); gprim.ComputeExtent(geometry.radius, &extentArray); gprim.GetExtentAttr().Set(extentArray); gprim.GetRadiusAttr().Set(double(geometry.radius)); path = pxr::SdfPath(name); } else if (geometry.type == UrdfGeometryType::BOX) { pxr::UsdGeomCube gprim = pxr::UsdGeomCube::Define(stage, pxr::SdfPath(name)); pxr::VtVec3fArray extentArray(2); extentArray[1] = pxr::GfVec3f(geometry.size_x * 0.5f, geometry.size_y * 0.5f, geometry.size_z * 0.5f); extentArray[0] = -extentArray[1]; gprim.GetExtentAttr().Set(extentArray); gprim.GetSizeAttr().Set(1.0); path = pxr::SdfPath(name); } else if (geometry.type == UrdfGeometryType::CYLINDER && !replaceCylindersWithCapsules) { pxr::UsdGeomCylinder gprim = pxr::UsdGeomCylinder::Define(stage, pxr::SdfPath(name)); pxr::VtVec3fArray extentArray(2); gprim.ComputeExtent(geometry.length, geometry.radius, pxr::UsdGeomTokens->x, &extentArray); gprim.GetAxisAttr().Set(pxr::UsdGeomTokens->z); gprim.GetExtentAttr().Set(extentArray); gprim.GetHeightAttr().Set(double(geometry.length)); gprim.GetRadiusAttr().Set(double(geometry.radius)); path = pxr::SdfPath(name); } else if (geometry.type == UrdfGeometryType::CAPSULE || (geometry.type == UrdfGeometryType::CYLINDER && replaceCylindersWithCapsules)) { pxr::UsdGeomCapsule gprim = pxr::UsdGeomCapsule::Define(stage, pxr::SdfPath(name)); pxr::VtVec3fArray extentArray(2); gprim.ComputeExtent(geometry.length, geometry.radius, pxr::UsdGeomTokens->x, &extentArray); gprim.GetAxisAttr().Set(pxr::UsdGeomTokens->z); gprim.GetExtentAttr().Set(extentArray); gprim.GetHeightAttr().Set(double(geometry.length)); gprim.GetRadiusAttr().Set(double(geometry.radius)); path = pxr::SdfPath(name); } pxr::UsdPrim prim = stage->GetPrimAtPath(path); if (prim) { Transform transform = origin; pxr::GfVec3d scale; if (geometry.type == UrdfGeometryType::MESH) { scale = pxr::GfVec3d(geometry.scale_x, geometry.scale_y, geometry.scale_z); } else if (geometry.type == UrdfGeometryType::BOX) { scale = pxr::GfVec3d(geometry.size_x, geometry.size_y, geometry.size_z); } else { scale = pxr::GfVec3d(1, 1, 1); } pxr::UsdGeomXformable gprim = pxr::UsdGeomXformable(prim); gprim.ClearXformOpOrder(); gprim.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble) .Set(distanceScale * pxr::GfVec3d(transform.p.x, transform.p.y, transform.p.z)); gprim.AddOrientOp(pxr::UsdGeomXformOp::PrecisionDouble) .Set(pxr::GfQuatd(transform.q.w, transform.q.x, transform.q.y, transform.q.z)); gprim.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(distanceScale * scale); } return prim; } void UrdfImporter::buildInstanceableStage(pxr::UsdStageRefPtr stage, const KinematicChain::Node* parentNode, const std::string& robotBasePath, const UrdfRobot& urdfRobot) { if (parentNode->parentJointName_ == "") { const UrdfLink& urdfLink = urdfRobot.links.at(parentNode->linkName_); addInstanceableMeshes(stage, urdfLink, robotBasePath, urdfRobot); } if (!parentNode->childNodes_.empty()) { for (const auto& childNode : parentNode->childNodes_) { if (urdfRobot.joints.find(childNode->parentJointName_) != urdfRobot.joints.end()) { if (urdfRobot.links.find(childNode->linkName_) != urdfRobot.links.end()) { const UrdfLink& childLink = urdfRobot.links.at(childNode->linkName_); addInstanceableMeshes(stage, childLink, robotBasePath, urdfRobot); // Recurse through the links children buildInstanceableStage(stage, childNode.get(), robotBasePath, urdfRobot); } } } } } void UrdfImporter::addInstanceableMeshes(pxr::UsdStageRefPtr stage, const UrdfLink& link, const std::string& robotBasePath, const UrdfRobot& robot) { std::map<std::string, std::string> linkMatPrimPaths; std::map<pxr::TfToken, std::string> linkMaterialList; // Add visuals for (size_t i = 0; i < link.visuals.size(); i++) { std::string meshName; std::string name = "mesh_" + std::to_string(i); if (link.visuals[i].name.size() > 0) { name = link.visuals[i].name; } meshName = robotBasePath + link.name + "/visuals/" + name; bool loadMaterial = true; auto mat = link.visuals[i].material; auto urdfMatIter = robot.materials.find(link.visuals[i].material.name); if (urdfMatIter != robot.materials.end()) { mat = urdfMatIter->second; } auto& color = mat.color; if (color.r >= 0 && color.g >= 0 && color.b >= 0) { loadMaterial = false; } pxr::UsdPrim prim = addMesh(stage, link.visuals[i].geometry, assetRoot_, urdfPath_, meshName, link.visuals[i].origin, loadMaterial, config.distanceScale, false, linkMaterialList, subdivisionschemes[(int)config.subdivisionScheme], true); if (prim) { if (loadMaterial == false) { // This Material was already created for this link, reuse auto urdfMatIter = linkMatPrimPaths.find(link.visuals[i].material.name); if (urdfMatIter != linkMatPrimPaths.end()) { std::string path = linkMatPrimPaths[link.visuals[i].material.name]; auto matPrim = stage->GetPrimAtPath(pxr::SdfPath(path)); if (matPrim) { auto shadePrim = pxr::UsdShadeMaterial(matPrim); if (shadePrim) { pxr::UsdShadeMaterialBindingAPI mbi(prim); mbi.Bind(shadePrim); } } } else { auto& color = link.visuals[i].material.color; std::stringstream ss; ss << std::uppercase << std::hex << (int)(256 * color.r) << std::uppercase << std::hex << (int)(256 * color.g) << std::uppercase << std::hex << (int)(256 * color.b); std::pair<std::string, UrdfMaterial> mat_pair(ss.str(), link.visuals[i].material); pxr::UsdShadeMaterial matPrim = addMaterial(stage, mat_pair, prim.GetPath().GetParentPath()); std::string matName = link.visuals[i].material.name; std::string matPrimName = matName == "" ? mat_pair.first : matName; linkMatPrimPaths[matName] = prim.GetPath() .GetParentPath() .AppendPath(pxr::SdfPath("Looks/" + makeValidUSDIdentifier("material_" + name))) .GetString(); if (matPrim) { pxr::UsdShadeMaterialBindingAPI mbi(prim); mbi.Bind(matPrim); } } } } else { CARB_LOG_WARN("Prim %s not created", meshName.c_str()); } } // Add collisions CARB_LOG_INFO("Add collisions: %s", link.name.c_str()); for (size_t i = 0; i < link.collisions.size(); i++) { std::string meshName; std::string name = "mesh_" + std::to_string(i); if (link.collisions[i].name.size() > 0) { name = link.collisions[i].name; } meshName = robotBasePath + link.name + "/collisions/" + name; pxr::UsdPrim prim = addMesh(stage, link.collisions[i].geometry, assetRoot_, urdfPath_, meshName, link.collisions[i].origin, false, config.distanceScale, false, materialsList, subdivisionschemes[(int)config.subdivisionScheme], false, config.replaceCylindersWithCapsules); // Enable collisions on prim if (prim) { pxr::UsdPhysicsCollisionAPI::Apply(prim); if (link.collisions[i].geometry.type == UrdfGeometryType::SPHERE) { pxr::UsdPhysicsCollisionAPI::Apply(prim); } else if (link.collisions[i].geometry.type == UrdfGeometryType::BOX) { pxr::UsdPhysicsCollisionAPI::Apply(prim); } else if (link.collisions[i].geometry.type == UrdfGeometryType::CYLINDER) { pxr::UsdPhysicsCollisionAPI::Apply(prim); } else if (link.collisions[i].geometry.type == UrdfGeometryType::CAPSULE) { pxr::UsdPhysicsCollisionAPI::Apply(prim); } else { pxr::UsdPhysicsMeshCollisionAPI physicsMeshAPI = pxr::UsdPhysicsMeshCollisionAPI::Apply(prim); if (config.convexDecomp == true) { physicsMeshAPI.CreateApproximationAttr().Set(pxr::UsdPhysicsTokens.Get()->convexDecomposition); } else { physicsMeshAPI.CreateApproximationAttr().Set(pxr::UsdPhysicsTokens.Get()->convexHull); } } pxr::UsdGeomMesh(prim).CreatePurposeAttr().Set(pxr::UsdGeomTokens->guide); } else { CARB_LOG_WARN("Prim %s not created", meshName.c_str()); } } } void UrdfImporter::addRigidBody(pxr::UsdStageWeakPtr stage, const UrdfLink& link, const Transform& poseBodyToWorld, pxr::UsdGeomXform robotPrim, const UrdfRobot& robot) { std::string robotBasePath = robotPrim.GetPath().GetString() + "/"; CARB_LOG_INFO("Add Rigid Body: %s", link.name.c_str()); // Create Link Prim auto linkPrim = pxr::UsdGeomXform::Define(stage, pxr::SdfPath(robotBasePath + link.name)); if (linkPrim) { Transform transform = poseBodyToWorld; // urdfOriginToTransform(link.inertial.origin); linkPrim.ClearXformOpOrder(); linkPrim.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble) .Set(config.distanceScale * pxr::GfVec3d(transform.p.x, transform.p.y, transform.p.z)); linkPrim.AddOrientOp(pxr::UsdGeomXformOp::PrecisionDouble) .Set(pxr::GfQuatd(transform.q.w, transform.q.x, transform.q.y, transform.q.z)); linkPrim.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfVec3d(1, 1, 1)); for (const auto& pair : link.mergedChildren) { auto childXform = pxr::UsdGeomXform::Define(stage, linkPrim.GetPath().AppendPath(pxr::SdfPath(pair.first))); if (childXform) { childXform.ClearXformOpOrder(); childXform.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble) .Set(config.distanceScale * pxr::GfVec3d(pair.second.p.x, pair.second.p.y, pair.second.p.z)); childXform.AddOrientOp(pxr::UsdGeomXformOp::PrecisionDouble) .Set(pxr::GfQuatd(pair.second.q.w, pair.second.q.x, pair.second.q.y, pair.second.q.z)); childXform.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfVec3d(1, 1, 1)); } } pxr::UsdPhysicsRigidBodyAPI physicsAPI = pxr::UsdPhysicsRigidBodyAPI::Apply(linkPrim.GetPrim()); pxr::UsdPhysicsMassAPI massAPI = pxr::UsdPhysicsMassAPI::Apply(linkPrim.GetPrim()); if (link.inertial.hasMass) { massAPI.CreateMassAttr().Set(link.inertial.mass); } else if (config.density > 0) { // scale from kg/m^2 to specified units massAPI.CreateDensityAttr().Set(config.density); } if (link.inertial.hasInertia && config.importInertiaTensor) { Matrix33 inertiaMatrix; inertiaMatrix.cols[0] = Vec3(link.inertial.inertia.ixx, link.inertial.inertia.ixy, link.inertial.inertia.ixz); inertiaMatrix.cols[1] = Vec3(link.inertial.inertia.ixy, link.inertial.inertia.iyy, link.inertial.inertia.iyz); inertiaMatrix.cols[2] = Vec3(link.inertial.inertia.ixz, link.inertial.inertia.iyz, link.inertial.inertia.izz); Quat principalAxes; Vec3 diaginertia = Diagonalize(inertiaMatrix, principalAxes); // input is meters, but convert to kit units massAPI.CreateDiagonalInertiaAttr().Set(config.distanceScale * config.distanceScale * pxr::GfVec3f(diaginertia.x, diaginertia.y, diaginertia.z)); massAPI.CreatePrincipalAxesAttr().Set( pxr::GfQuatf(principalAxes.w, principalAxes.x, principalAxes.y, principalAxes.z)); } if (link.inertial.hasOrigin) { massAPI.CreateCenterOfMassAttr().Set(pxr::GfVec3f(float(config.distanceScale * link.inertial.origin.p.x), float(config.distanceScale * link.inertial.origin.p.y), float(config.distanceScale * link.inertial.origin.p.z))); } } else { CARB_LOG_WARN("linkPrim %s not created", link.name.c_str()); return; } // Add visuals if (config.makeInstanceable && link.visuals.size() > 0) { pxr::SdfPath visualPrimPath = pxr::SdfPath(robotBasePath + link.name + "/visuals"); pxr::UsdPrim visualPrim = stage->DefinePrim(visualPrimPath); visualPrim.GetReferences().AddReference(config.instanceableMeshUsdPath, visualPrimPath); visualPrim.SetInstanceable(true); } else { for (size_t i = 0; i < link.visuals.size(); i++) { std::string meshName; if (link.visuals.size() > 1) { std::string name = "mesh_" + std::to_string(i); if (link.visuals[i].name.size() > 0) { name = link.visuals[i].name; } meshName = robotBasePath + link.name + "/visuals/" + name; } else { meshName = robotBasePath + link.name + "/visuals"; } bool loadMaterial = true; auto mat = link.visuals[i].material; auto urdfMatIter = robot.materials.find(link.visuals[i].material.name); if (urdfMatIter != robot.materials.end()) { mat = urdfMatIter->second; } auto& color = mat.color; if (color.r >= 0 && color.g >= 0 && color.b >= 0) { loadMaterial = false; } pxr::UsdPrim prim = addMesh(stage, link.visuals[i].geometry, assetRoot_, urdfPath_, meshName, link.visuals[i].origin, loadMaterial, config.distanceScale, false, materialsList, subdivisionschemes[(int)config.subdivisionScheme]); if (prim) { if (loadMaterial == false) { // This Material was in the master list, reuse auto urdfMatIter = robot.materials.find(link.visuals[i].material.name); if (urdfMatIter != robot.materials.end()) { std::string path = matPrimPaths[link.visuals[i].material.name]; auto matPrim = stage->GetPrimAtPath(pxr::SdfPath(path)); if (matPrim) { auto shadePrim = pxr::UsdShadeMaterial(matPrim); if (shadePrim) { pxr::UsdShadeMaterialBindingAPI mbi(prim); mbi.Bind(shadePrim); } } } else { auto& color = link.visuals[i].material.color; std::stringstream ss; ss << std::uppercase << std::hex << (int)(256 * color.r) << std::uppercase << std::hex << (int)(256 * color.g) << std::uppercase << std::hex << (int)(256 * color.b); std::pair<std::string, UrdfMaterial> mat_pair(ss.str(), link.visuals[i].material); pxr::UsdShadeMaterial matPrim = addMaterial(stage, mat_pair, prim.GetPath().GetParentPath().GetParentPath()); if (matPrim) { pxr::UsdShadeMaterialBindingAPI mbi(prim); mbi.Bind(matPrim); } } } } else { CARB_LOG_WARN("Prim %s not created", meshName.c_str()); } } } // Add collisions CARB_LOG_INFO("Add collisions: %s", link.name.c_str()); if (config.makeInstanceable && link.collisions.size() > 0) { pxr::SdfPath collisionPrimPath = pxr::SdfPath(robotBasePath + link.name + "/collisions"); pxr::UsdPrim collisionPrim = stage->DefinePrim(collisionPrimPath); collisionPrim.GetReferences().AddReference(config.instanceableMeshUsdPath, collisionPrimPath); collisionPrim.SetInstanceable(true); } else { for (size_t i = 0; i < link.collisions.size(); i++) { std::string meshName; if (link.collisions.size() > 1 || config.makeInstanceable) { std::string name = "mesh_" + std::to_string(i); if (link.collisions[i].name.size() > 0) { name = link.collisions[i].name; } meshName = robotBasePath + link.name + "/collisions/" + name; } else { meshName = robotBasePath + link.name + "/collisions"; } pxr::UsdPrim prim = addMesh(stage, link.collisions[i].geometry, assetRoot_, urdfPath_, meshName, link.collisions[i].origin, false, config.distanceScale, false, materialsList, subdivisionschemes[(int)config.subdivisionScheme], false, config.replaceCylindersWithCapsules); // Enable collisions on prim if (prim) { pxr::UsdPhysicsCollisionAPI::Apply(prim); if (link.collisions[i].geometry.type == UrdfGeometryType::SPHERE) { pxr::UsdPhysicsCollisionAPI::Apply(prim); } else if (link.collisions[i].geometry.type == UrdfGeometryType::BOX) { pxr::UsdPhysicsCollisionAPI::Apply(prim); } else if (link.collisions[i].geometry.type == UrdfGeometryType::CYLINDER) { pxr::UsdPhysicsCollisionAPI::Apply(prim); } else if (link.collisions[i].geometry.type == UrdfGeometryType::CAPSULE) { pxr::UsdPhysicsCollisionAPI::Apply(prim); } else { pxr::UsdPhysicsMeshCollisionAPI physicsMeshAPI = pxr::UsdPhysicsMeshCollisionAPI::Apply(prim); if (config.convexDecomp == true) { physicsMeshAPI.CreateApproximationAttr().Set(pxr::UsdPhysicsTokens.Get()->convexDecomposition); } else { physicsMeshAPI.CreateApproximationAttr().Set(pxr::UsdPhysicsTokens.Get()->convexHull); } } pxr::UsdGeomMesh(prim).CreatePurposeAttr().Set(pxr::UsdGeomTokens->guide); } else { CARB_LOG_WARN("Prim %s not created", meshName.c_str()); } } } } template <class T> void AddSingleJoint(const UrdfJoint& joint, pxr::UsdStageWeakPtr stage, const pxr::SdfPath& jointPath, pxr::UsdPhysicsJoint& jointPrimBase, const float distanceScale) { T jointPrim = T::Define(stage, pxr::SdfPath(jointPath)); jointPrimBase = jointPrim; jointPrim.CreateAxisAttr().Set(pxr::TfToken("X")); // Set the limits if the joint is anything except a continuous joint if (joint.type != UrdfJointType::CONTINUOUS) { // Angular limits are in degrees so scale accordingly float scale = 180.0f / static_cast<float>(M_PI); if (joint.type == UrdfJointType::PRISMATIC) { scale = distanceScale; } jointPrim.CreateLowerLimitAttr().Set(scale * joint.limit.lower); jointPrim.CreateUpperLimitAttr().Set(scale * joint.limit.upper); } pxr::PhysxSchemaPhysxJointAPI physxJoint = pxr::PhysxSchemaPhysxJointAPI::Apply(jointPrim.GetPrim()); physxJoint.CreateJointFrictionAttr().Set(joint.dynamics.friction); if (joint.type == UrdfJointType::PRISMATIC) { pxr::PhysxSchemaJointStateAPI::Apply(jointPrim.GetPrim(), pxr::TfToken("linear")); if (joint.mimic.joint == "") { pxr::UsdPhysicsDriveAPI driveAPI = pxr::UsdPhysicsDriveAPI::Apply(jointPrim.GetPrim(), pxr::TfToken("linear")); // convert kg*m/s^2 to kg * cm /s^2 driveAPI.CreateMaxForceAttr().Set(joint.limit.effort > 0.0f ? joint.limit.effort * distanceScale : FLT_MAX); // change drive type if (joint.drive.driveType == UrdfJointDriveType::FORCE) { driveAPI.CreateTypeAttr().Set(pxr::TfToken("force")); } else { driveAPI.CreateTypeAttr().Set(pxr::TfToken("acceleration")); } // change drive target type if (joint.drive.targetType == UrdfJointTargetType::POSITION) { driveAPI.CreateTargetPositionAttr().Set(joint.drive.target); } else if (joint.drive.targetType == UrdfJointTargetType::VELOCITY) { driveAPI.CreateTargetVelocityAttr().Set(joint.drive.target); } // change drive stiffness and damping if (joint.drive.targetType != UrdfJointTargetType::NONE) { driveAPI.CreateDampingAttr().Set(joint.dynamics.damping); driveAPI.CreateStiffnessAttr().Set(joint.dynamics.stiffness); } else { driveAPI.CreateDampingAttr().Set(0.0f); driveAPI.CreateStiffnessAttr().Set(0.0f); } } // Prismatic joint velocity should be scaled to stage units, but not revolute physxJoint.CreateMaxJointVelocityAttr().Set( joint.limit.velocity > 0.0f ? static_cast<float>(joint.limit.velocity * distanceScale) : FLT_MAX); } // continuous and revolute are identical except for setting limits else if (joint.type == UrdfJointType::REVOLUTE || joint.type == UrdfJointType::CONTINUOUS) { pxr::PhysxSchemaJointStateAPI::Apply(jointPrim.GetPrim(), pxr::TfToken("angular")); if (joint.mimic.joint == "") { pxr::UsdPhysicsDriveAPI driveAPI = pxr::UsdPhysicsDriveAPI::Apply(jointPrim.GetPrim(), pxr::TfToken("angular")); // convert kg*m/s^2 * m to kg * cm /s^2 * cm driveAPI.CreateMaxForceAttr().Set( joint.limit.effort > 0.0f ? joint.limit.effort * distanceScale * distanceScale : FLT_MAX); // change drive type if (joint.drive.driveType == UrdfJointDriveType::FORCE) { driveAPI.CreateTypeAttr().Set(pxr::TfToken("force")); } else { driveAPI.CreateTypeAttr().Set(pxr::TfToken("acceleration")); } // change drive target type if (joint.drive.targetType == UrdfJointTargetType::POSITION) { driveAPI.CreateTargetPositionAttr().Set(joint.drive.target); } else if (joint.drive.targetType == UrdfJointTargetType::VELOCITY) { driveAPI.CreateTargetVelocityAttr().Set(joint.drive.target); } // change drive stiffness and damping if (joint.drive.targetType != UrdfJointTargetType::NONE) { driveAPI.CreateDampingAttr().Set(joint.dynamics.damping); driveAPI.CreateStiffnessAttr().Set(joint.dynamics.stiffness); } else { driveAPI.CreateDampingAttr().Set(0.0f); driveAPI.CreateStiffnessAttr().Set(0.0f); } } // Convert revolute joint velocity limit to deg/s physxJoint.CreateMaxJointVelocityAttr().Set( joint.limit.velocity > 0.0f ? static_cast<float>(180.0f / M_PI * joint.limit.velocity) : FLT_MAX); } for (auto &mimic : joint.mimicChildren) { auto tendonRoot = pxr::PhysxSchemaPhysxTendonAxisRootAPI::Apply(jointPrim.GetPrim(), pxr::TfToken(mimic.first)); tendonRoot.CreateStiffnessAttr().Set(1.e5f); tendonRoot.CreateDampingAttr().Set(10.0); float scale = 180.0f / static_cast<float>(M_PI); if (joint.type == UrdfJointType::PRISMATIC) { scale = distanceScale; } auto offset = scale*mimic.second; tendonRoot.CreateOffsetAttr().Set(offset); // Manually setting the coefficients to avoid adding an extra API that makes it messy. std::string attrName1 = "physxTendon:"+mimic.first+":forceCoefficient"; auto attr1 = tendonRoot.GetPrim().CreateAttribute( pxr::TfToken(attrName1.c_str()), pxr::SdfValueTypeNames->FloatArray, false); std::string attrName2 = "physxTendon:"+mimic.first+":gearing"; auto attr2 = tendonRoot.GetPrim().CreateAttribute( pxr::TfToken(attrName2.c_str()), pxr::SdfValueTypeNames->FloatArray, false); pxr::VtArray<float> forceattr; pxr::VtArray<float> gearing; forceattr.push_back(-1.0f); gearing.push_back(-1.0f); attr1.Set(forceattr); attr2.Set(gearing); } if (joint.mimic.joint != "") { auto tendon = pxr::PhysxSchemaPhysxTendonAxisAPI::Apply(jointPrim.GetPrim(), pxr::TfToken(joint.name)); pxr::VtArray<float> forceattr; pxr::VtArray<float> gearing; forceattr.push_back(joint.mimic.multiplier>0?1:-1); // Tendon Gear ratio is the inverse of the mimic multiplier gearing.push_back(1.0f/joint.mimic.multiplier); tendon.CreateForceCoefficientAttr().Set(forceattr); tendon.CreateGearingAttr().Set(gearing); } } void UrdfImporter::addJoint(pxr::UsdStageWeakPtr stage, pxr::UsdGeomXform robotPrim, const UrdfJoint& joint, const Transform& poseJointToParentBody) { std::string parentLinkPath = robotPrim.GetPath().GetString() + "/" + joint.parentLinkName; std::string childLinkPath = robotPrim.GetPath().GetString() + "/" + joint.childLinkName; std::string jointPath = parentLinkPath + "/" + joint.name; if (!pxr::SdfPath::IsValidPathString(jointPath)) { // jn->getName starts with a number which is not valid for usd path, so prefix it with "joint" jointPath = parentLinkPath + "/joint" + joint.name; } pxr::UsdPhysicsJoint jointPrim; if (joint.type == UrdfJointType::FIXED) { jointPrim = pxr::UsdPhysicsFixedJoint::Define(stage, pxr::SdfPath(jointPath)); } else if (joint.type == UrdfJointType::PRISMATIC) { AddSingleJoint<pxr::UsdPhysicsPrismaticJoint>( joint, stage, pxr::SdfPath(jointPath), jointPrim, float(config.distanceScale)); } // else if (joint.type == UrdfJointType::SPHERICAL) // { // AddSingleJoint<PhysicsSchemaSphericalJoint>(jn, stage, SdfPath(jointPath), jointPrim, skel, // distanceScale); // } else if (joint.type == UrdfJointType::REVOLUTE || joint.type == UrdfJointType::CONTINUOUS) { AddSingleJoint<pxr::UsdPhysicsRevoluteJoint>( joint, stage, pxr::SdfPath(jointPath), jointPrim, float(config.distanceScale)); } else if (joint.type == UrdfJointType::FLOATING) { // There is no joint, skip return; } pxr::SdfPathVector val0{ pxr::SdfPath(parentLinkPath) }; pxr::SdfPathVector val1{ pxr::SdfPath(childLinkPath) }; if (parentLinkPath != "") { jointPrim.CreateBody0Rel().SetTargets(val0); } pxr::GfVec3f localPos0 = config.distanceScale * pxr::GfVec3f(poseJointToParentBody.p.x, poseJointToParentBody.p.y, poseJointToParentBody.p.z); pxr::GfQuatf localRot0 = pxr::GfQuatf( poseJointToParentBody.q.w, poseJointToParentBody.q.x, poseJointToParentBody.q.y, poseJointToParentBody.q.z); pxr::GfVec3f localPos1 = config.distanceScale * pxr::GfVec3f(0, 0, 0); pxr::GfQuatf localRot1 = pxr::GfQuatf(1, 0, 0, 0); // Need to rotate the joint frame to match the urdf defined axis // convert joint axis to angle-axis representation Vec3 jointAxisRotAxis = -Cross(urdfAxisToVec(joint.axis), Vec3(1.0f, 0.0f, 0.0f)); float jointAxisRotAngle = acos(joint.axis.x); // this is equal to acos(Dot(joint.axis, Vec3(1.0f, 0.0f, 0.0f))) if (Dot(jointAxisRotAxis, jointAxisRotAxis) < 1e-5f) { // for axis along x we define an arbitrary perpendicular rotAxis (along y). // In that case the angle is 0 or 180deg jointAxisRotAxis = Vec3(0.0f, 1.0f, 0.0f); } // normalize jointAxisRotAxis jointAxisRotAxis /= sqrtf(Dot(jointAxisRotAxis, jointAxisRotAxis)); // rotate the parent frame by the axis Quat jointAxisRotQuat = QuatFromAxisAngle(jointAxisRotAxis, jointAxisRotAngle); // apply transforms jointPrim.CreateLocalPos0Attr().Set(localPos0); jointPrim.CreateLocalRot0Attr().Set(localRot0 * pxr::GfQuatf(jointAxisRotQuat.w, jointAxisRotQuat.x, jointAxisRotQuat.y, jointAxisRotQuat.z)); if (childLinkPath != "") { jointPrim.CreateBody1Rel().SetTargets(val1); } jointPrim.CreateLocalPos1Attr().Set(localPos1); jointPrim.CreateLocalRot1Attr().Set(localRot1 * pxr::GfQuatf(jointAxisRotQuat.w, jointAxisRotQuat.x, jointAxisRotQuat.y, jointAxisRotQuat.z)); jointPrim.CreateBreakForceAttr().Set(FLT_MAX); jointPrim.CreateBreakTorqueAttr().Set(FLT_MAX); // TODO: FIx? // auto linkAPI = pxr::UsdPhysicsJoint::Apply(stage->GetPrimAtPath(pxr::SdfPath(jointPath))); // linkAPI.CreateArticulationTypeAttr().Set(pxr::TfToken("articulatedJoint")); } void UrdfImporter::addLinksAndJoints(pxr::UsdStageWeakPtr stage, const Transform& poseParentToWorld, const KinematicChain::Node* parentNode, const UrdfRobot& robot, pxr::UsdGeomXform robotPrim) { // Create root joint only once if (parentNode->parentJointName_ == "") { const UrdfLink& urdfLink = robot.links.at(parentNode->linkName_); addRigidBody(stage, urdfLink, poseParentToWorld, robotPrim, robot); if (config.fixBase) { std::string rootJointPath = robotPrim.GetPath().GetString() + "/root_joint"; pxr::UsdPhysicsFixedJoint rootJoint = pxr::UsdPhysicsFixedJoint::Define(stage, pxr::SdfPath(rootJointPath)); pxr::SdfPathVector val1{ pxr::SdfPath(robotPrim.GetPath().GetString() + "/" + urdfLink.name) }; rootJoint.CreateBody1Rel().SetTargets(val1); } } if (!parentNode->childNodes_.empty()) { for (const auto& childNode : parentNode->childNodes_) { if (robot.joints.find(childNode->parentJointName_) != robot.joints.end()) { if (robot.links.find(childNode->linkName_) != robot.links.end()) { const UrdfJoint urdfJoint = robot.joints.at(childNode->parentJointName_); const UrdfLink& childLink = robot.links.at(childNode->linkName_); // const UrdfLink& parentLink = robot.links.at(parentNode->linkName_); Transform poseJointToLink = urdfJoint.origin; // According to URDF spec, the frame of a link coincides with its parent joint frame Transform poseLinkToWorld = poseParentToWorld * poseJointToLink; // if (!parentLink.softs.size() && !childLink.softs.size()) // rigid parent, rigid child { addRigidBody(stage, childLink, poseLinkToWorld, robotPrim, robot); addJoint(stage, robotPrim, urdfJoint, poseJointToLink); // RigidBodyTopo bodyTopo; // bodyTopo.bodyIndex = asset->bodyLookup.at(childNode->linkName_); // bodyTopo.parentIndex = asset->bodyLookup.at(parentNode->linkName_); // bodyTopo.jointIndex = asset->jointLookup.at(childNode->parentJointName_); // bodyTopo.jointSpecStart = asset->jointLookup.at(childNode->parentJointName_); // // URDF only has 1 DOF joints // bodyTopo.jointSpecCount = 1; // asset->rigidBodyHierarchy.push_back(bodyTopo); } // Recurse through the links children addLinksAndJoints(stage, poseLinkToWorld, childNode.get(), robot, robotPrim); } else { CARB_LOG_ERROR("Failed to Create Joint <%s>: Child link <%s> not found", childNode->parentJointName_.c_str(), childNode->linkName_.c_str()); } } else { CARB_LOG_WARN("Joint <%s> is undefined", childNode->parentJointName_.c_str()); } } } } void UrdfImporter::addMaterials(pxr::UsdStageWeakPtr stage, const UrdfRobot& robot, const pxr::SdfPath& prefixPath) { stage->DefinePrim(pxr::SdfPath(prefixPath.GetString() + "/Looks"), pxr::TfToken("Scope")); for (auto& mat : robot.materials) { addMaterial(stage, mat, prefixPath); } } pxr::UsdShadeMaterial UrdfImporter::addMaterial(pxr::UsdStageWeakPtr stage, const std::pair<std::string, UrdfMaterial>& mat, const pxr::SdfPath& prefixPath) { auto& color = mat.second.color; std::string name = mat.second.name; if (name == "") { name = mat.first; } if (color.r >= 0 && color.g >= 0 && color.b >= 0) { pxr::SdfPath shaderPath = prefixPath.AppendPath(pxr::SdfPath("Looks/" + makeValidUSDIdentifier("material_" + name))); pxr::UsdShadeMaterial matPrim = pxr::UsdShadeMaterial::Define(stage, shaderPath); if (matPrim) { pxr::UsdShadeShader pbrShader = pxr::UsdShadeShader::Define(stage, shaderPath.AppendPath(pxr::SdfPath("Shader"))); if (pbrShader) { auto shader_out = pbrShader.CreateOutput(pxr::TfToken("out"), pxr::SdfValueTypeNames->Token); matPrim.CreateSurfaceOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out); matPrim.CreateVolumeOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out); matPrim.CreateDisplacementOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out); pbrShader.GetImplementationSourceAttr().Set(pxr::UsdShadeTokens->sourceAsset); pbrShader.SetSourceAsset(pxr::SdfAssetPath("OmniPBR.mdl"), pxr::TfToken("mdl")); pbrShader.SetSourceAssetSubIdentifier(pxr::TfToken("OmniPBR"), pxr::TfToken("mdl")); pbrShader.CreateInput(pxr::TfToken("diffuse_color_constant"), pxr::SdfValueTypeNames->Color3f) .Set(pxr::GfVec3f(color.r, color.g, color.b)); matPrimPaths[name] = shaderPath.GetString(); return matPrim; } else { CARB_LOG_WARN("Couldn't create shader at: %s", shaderPath.GetString().c_str()); } } else { CARB_LOG_WARN("Couldn't create material at: %s", shaderPath.GetString().c_str()); } } return pxr::UsdShadeMaterial(); } std::string UrdfImporter::addToStage(pxr::UsdStageWeakPtr stage, const UrdfRobot& urdfRobot) { if (urdfRobot.links.size() == 0) { CARB_LOG_WARN("Cannot add robot to stage, number of links is zero"); return ""; } // The limit for links is now a 32bit index so this shouldn't be needed anymore // if (urdfRobot.links.size() >= 64) // { // CARB_LOG_WARN( // "URDF cannot have more than 63 links to be imported as a physx articulation. Try enabling the merge fixed // joints option to reduce the number of links."); // CARB_LOG_WARN("URDF has %d links", static_cast<int>(urdfRobot.links.size())); // return ""; // } if (config.createPhysicsScene) { bool sceneExists = false; pxr::UsdPrimRange range = stage->Traverse(); for (pxr::UsdPrimRange::iterator iter = range.begin(); iter != range.end(); ++iter) { pxr::UsdPrim prim = *iter; if (prim.IsA<pxr::UsdPhysicsScene>()) { sceneExists = true; } } if (!sceneExists) { // Create physics scene pxr::UsdPhysicsScene scene = pxr::UsdPhysicsScene::Define(stage, pxr::SdfPath("/physicsScene")); scene.CreateGravityDirectionAttr().Set(pxr::GfVec3f(0.0f, 0.0f, -1.0)); scene.CreateGravityMagnitudeAttr().Set(9.81f * config.distanceScale); pxr::PhysxSchemaPhysxSceneAPI physxSceneAPI = pxr::PhysxSchemaPhysxSceneAPI::Apply(stage->GetPrimAtPath(pxr::SdfPath("/physicsScene"))); physxSceneAPI.CreateEnableCCDAttr().Set(true); physxSceneAPI.CreateEnableStabilizationAttr().Set(true); physxSceneAPI.CreateEnableGPUDynamicsAttr().Set(false); physxSceneAPI.CreateBroadphaseTypeAttr().Set(pxr::TfToken("MBP")); physxSceneAPI.CreateSolverTypeAttr().Set(pxr::TfToken("TGS")); } } pxr::SdfPath primPath = pxr::SdfPath(GetNewSdfPathString(stage, stage->GetDefaultPrim().GetPath().GetString() + "/" + makeValidUSDIdentifier(std::string(urdfRobot.name)))); if (config.makeDefaultPrim) primPath = pxr::SdfPath(GetNewSdfPathString(stage, "/" + makeValidUSDIdentifier(std::string(urdfRobot.name)))); // // Remove the prim we are about to add in case it exists // if (stage->GetPrimAtPath(primPath)) // { // stage->RemovePrim(primPath); // } pxr::UsdGeomXform robotPrim = pxr::UsdGeomXform::Define(stage, primPath); pxr::UsdGeomXformable gprim = pxr::UsdGeomXformable(robotPrim); gprim.ClearXformOpOrder(); gprim.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfVec3d(0, 0, 0)); gprim.AddOrientOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfQuatd(1, 0, 0, 0)); gprim.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfVec3d(1, 1, 1)); pxr::UsdPhysicsArticulationRootAPI physicsSchema = pxr::UsdPhysicsArticulationRootAPI::Apply(robotPrim.GetPrim()); pxr::PhysxSchemaPhysxArticulationAPI physxSchema = pxr::PhysxSchemaPhysxArticulationAPI::Apply(robotPrim.GetPrim()); physxSchema.CreateEnabledSelfCollisionsAttr().Set(config.selfCollision); // These are reasonable defaults, might want to expose them via the import config in the future. physxSchema.CreateSolverPositionIterationCountAttr().Set(32); physxSchema.CreateSolverVelocityIterationCountAttr().Set(16); if (config.makeDefaultPrim) { stage->SetDefaultPrim(robotPrim.GetPrim()); } KinematicChain chain; if (!chain.computeKinematicChain(urdfRobot)) { return ""; } if (!config.makeInstanceable) { addMaterials(stage, urdfRobot, primPath); } else { // first create instanceable meshes USD std::string instanceableStagePath = config.instanceableMeshUsdPath; if (config.instanceableMeshUsdPath[0] == '.') { // make relative path relative to output directory std::string relativePath = config.instanceableMeshUsdPath.substr(1); std::string curStagePath = stage->GetRootLayer()->GetIdentifier(); std::string directory; size_t pos = curStagePath.find_last_of("\\/"); directory = (std::string::npos == pos) ? "" : curStagePath.substr(0, pos); instanceableStagePath = directory + relativePath; } pxr::UsdStageRefPtr instanceableMeshStage = pxr::UsdStage::CreateNew(instanceableStagePath); std::string robotBasePath = robotPrim.GetPath().GetString() + "/"; buildInstanceableStage(instanceableMeshStage, chain.baseNode.get(), robotBasePath, urdfRobot); instanceableMeshStage->Export(instanceableStagePath); } addLinksAndJoints(stage, Transform(), chain.baseNode.get(), urdfRobot, robotPrim); return primPath.GetString(); } } } }
48,372
C++
41.432456
146
0.576222
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/KinematicChain.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "../UrdfTypes.h" #include <memory> #include <string> #include <vector> namespace omni { namespace importer { namespace urdf { // Represents the kinematic chain as a tree class KinematicChain { public: // A tree representing a link with its parent joint and child links struct Node { std::string linkName_; std::string parentJointName_; std::vector<std::unique_ptr<Node>> childNodes_; Node(std::string linkName, std::string parentJointName) : linkName_(linkName), parentJointName_(parentJointName) { } }; std::unique_ptr<Node> baseNode; KinematicChain() = default; ~KinematicChain(); // Computes the kinematic chain for a UrdfRobot description bool computeKinematicChain(const UrdfRobot& urdfRobot); private: // Recursively finds a node's children void computeChildNodes(std::unique_ptr<Node>& parentNode, const UrdfRobot& urdfRobot); }; } } }
1,662
C
24.984375
120
0.712996
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/MeshImporter.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once // clang-format off #include "../UsdPCH.h" // clang-format on #include "assimp/scene.h" #include <string> namespace omni { namespace importer { namespace urdf { pxr::SdfPath SimpleImport(pxr::UsdStageRefPtr usdStage, std::string path, const aiScene* mScene, const std::string mesh_path, std::map<pxr::TfToken, std::string>& materialsList, const bool loadMaterials = true, const bool flipVisuals = false, const char* subdvisionScheme = "none", const bool instanceable = false); } } }
1,407
C
27.734693
99
0.635394
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/UrdfImporter.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once // clang-format off #include "../UsdPCH.h" // clang-format on #include "../parse/UrdfParser.h" #include "KinematicChain.h" #include "MeshImporter.h" #include "../math/core/maths.h" #include "../Urdf.h" #include "../UrdfTypes.h" #include <carb/logging/Log.h> #include <pxr/usd/usdPhysics/articulationRootAPI.h> #include <pxr/usd/usdPhysics/collisionAPI.h> #include <pxr/usd/usdPhysics/driveAPI.h> #include <pxr/usd/usdPhysics/fixedJoint.h> #include <pxr/usd/usdPhysics/joint.h> #include <pxr/usd/usdPhysics/limitAPI.h> #include <pxr/usd/usdPhysics/massAPI.h> #include <pxr/usd/usdPhysics/prismaticJoint.h> #include <pxr/usd/usdPhysics/revoluteJoint.h> #include <pxr/usd/usdPhysics/scene.h> #include <pxr/usd/usdPhysics/sphericalJoint.h> namespace omni { namespace importer { namespace urdf { class UrdfImporter { private: std::string assetRoot_; std::string urdfPath_; const ImportConfig config; std::map<std::string, std::string> matPrimPaths; std::map<pxr::TfToken, std::string> materialsList; public: UrdfImporter(const std::string& assetRoot, const std::string& urdfPath, const ImportConfig& options) : assetRoot_(assetRoot), urdfPath_(urdfPath), config(options) { } // Creates and populates a GymAsset UrdfRobot createAsset(); std::string addToStage(pxr::UsdStageWeakPtr stage, const UrdfRobot& robot); private: void buildInstanceableStage(pxr::UsdStageRefPtr stage, const KinematicChain::Node* parentNode, const std::string& robotBasePath, const UrdfRobot& urdfRobot); void addInstanceableMeshes(pxr::UsdStageRefPtr stage, const UrdfLink& link, const std::string& robotBasePath, const UrdfRobot& robot); void addRigidBody(pxr::UsdStageWeakPtr stage, const UrdfLink& link, const Transform& poseBodyToWorld, pxr::UsdGeomXform robotPrim, const UrdfRobot& robot); void addJoint(pxr::UsdStageWeakPtr stage, pxr::UsdGeomXform robotPrim, const UrdfJoint& joint, const Transform& poseJointToParentBody); void addLinksAndJoints(pxr::UsdStageWeakPtr stage, const Transform& poseParentToWorld, const KinematicChain::Node* parentNode, const UrdfRobot& robot, pxr::UsdGeomXform robotPrim); void addMaterials(pxr::UsdStageWeakPtr stage, const UrdfRobot& robot, const pxr::SdfPath& prefixPath); pxr::UsdShadeMaterial addMaterial(pxr::UsdStageWeakPtr stage, const std::pair<std::string, UrdfMaterial>& mat, const pxr::SdfPath& prefixPath); }; } } }
3,651
C
34.803921
106
0.649137
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/core/PathUtils.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once // clang-format off #include "../UsdPCH.h" // clang-format on #include <string> #include <vector> namespace omni { namespace importer { namespace urdf { enum class PathType { eNone, // path does not exist eFile, // path is a regular file eDirectory, // path is a directory eOther, // path is something else }; PathType testPath(const char* path); bool isAbsolutePath(const char* path); bool makeDirectory(const char* path); std::string pathJoin(const std::string& path1, const std::string& path2); std::string getCwd(); // returns filename without extension (e.g. "foo/bar/bingo.txt" -> "bingo") std::string getPathStem(const char* path); std::vector<std::string> getFileListRecursive(const std::string& dir, bool sorted = true); std::string makeValidUSDIdentifier(const std::string& name); } } }
1,532
C
24.98305
99
0.730418
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/core/PathUtils.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "PathUtils.h" #include <carb/logging/Log.h> #include <algorithm> #include <cctype> #include <cstring> #include <errno.h> #include <vector> #ifdef _WIN32 # include <direct.h> # include <windows.h> #else # include <sys/stat.h> # include <dirent.h> # include <unistd.h> #endif namespace omni { namespace importer { namespace urdf { PathType testPath(const char* path) { if (!path || !*path) { return PathType::eNone; } #ifdef _WIN32 DWORD attribs = GetFileAttributesA(path); if (attribs == INVALID_FILE_ATTRIBUTES) { return PathType::eNone; } else if (attribs & FILE_ATTRIBUTE_DIRECTORY) { return PathType::eDirectory; } else { // hmmm return PathType::eFile; } #else struct stat s; if (stat(path, &s) == -1) { return PathType::eNone; } else if (S_ISREG(s.st_mode)) { return PathType::eFile; } else if (S_ISDIR(s.st_mode)) { return PathType::eDirectory; } else { return PathType::eOther; } #endif } bool isAbsolutePath(const char* path) { if (!path || !*path) { return false; } #ifdef _WIN32 if (path[0] == '\\' || path[0] == '/') { return true; } else if (std::isalpha(path[0]) && path[1] == ':') { return true; } else { return false; } #else return path[0] == '/'; #endif } std::string pathJoin(const std::string& path1, const std::string& path2) { if (path1.empty()) { return path2; } else { auto last = path1.rbegin(); #ifdef _WIN32 if (*last != '/' && *last != '\\') #else if (*last != '/') #endif { return path1 + '/' + path2; } else { return path1 + path2; } } } std::string getCwd() { std::vector<char> buf(4096); #ifdef _WIN32 if (!_getcwd(buf.data(), int(buf.size()))) #else if (!getcwd(buf.data(), size_t(buf.size()))) #endif { return std::string(); } return std::string(buf.data()); } static int sysmkdir(const char* path) { #ifdef _WIN32 return _mkdir(path); #else return mkdir(path, 0755); #endif } static std::vector<std::string> tokenizePath(const char* path_) { std::vector<std::string> components; if (!path_ || !*path_) { return components; } std::string path(path_); size_t start = 0; bool done = false; while (!done) { #ifdef _WIN32 size_t end = path.find_first_of("/\\", start); #else size_t end = path.find_first_of('/', start); #endif if (end == std::string::npos) { end = path.length(); done = true; } if (end - start > 0) { components.push_back(path.substr(start, end - start)); } start = end + 1; } return components; } bool makeDirectory(const char* path) { std::vector<std::string> components = tokenizePath(path); if (components.empty()) { return false; } std::string pathSoFar; #ifndef _WIN32 // on Unixes, need to start with leading slash if absolute path if (isAbsolutePath(path)) { pathSoFar = "/"; } #endif for (unsigned i = 0; i < components.size(); i++) { if (i > 0) { pathSoFar += '/'; } pathSoFar += components[i]; if (sysmkdir(pathSoFar.c_str()) != 0 && errno != EEXIST) { fprintf(stderr, "*** Failed to create directory '%s'\n", pathSoFar.c_str()); return false; } // printf("Creating '%s'\n", pathSoFar.c_str()); } return true; } std::string getPathStem(const char* path) { if (!path || !*path) { return ""; } const char* p = strrchr(path, '/'); #ifdef _WIN32 const char* q = strrchr(path, '\\'); if (q > p) { p = q; } #endif const char* fnameStart = p ? p + 1 : path; const char* ext = strrchr(fnameStart, '.'); if (ext) { return std::string(fnameStart, ext); } else { return fnameStart; } } static void getFileListRecursiveRec(const std::string& dir, std::vector<std::string>& flist) { #if _WIN32 WIN32_FIND_DATAA fdata; memset(&fdata, 0, sizeof(fdata)); std::string pattern = dir + "\\*"; HANDLE handle = FindFirstFileA(pattern.c_str(), &fdata); while (handle != INVALID_HANDLE_VALUE) { if ((fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) { if (strcmp(fdata.cFileName, ".") != 0 && strcmp(fdata.cFileName, "..") != 0) { getFileListRecursiveRec(dir + '\\' + fdata.cFileName, flist); } } else { flist.push_back(dir + '\\' + fdata.cFileName); } if (FindNextFileA(handle, &fdata) == FALSE) { break; } } FindClose(handle); #else DIR* d = opendir(dir.c_str()); if (d) { struct dirent* dent; while ((dent = readdir(d)) != nullptr) { if (dent->d_type == DT_DIR) { if (strcmp(dent->d_name, ".") != 0 && strcmp(dent->d_name, "..") != 0) { getFileListRecursiveRec(dir + '/' + dent->d_name, flist); } } else if (dent->d_type == DT_REG) { flist.push_back(dir + '/' + dent->d_name); } } closedir(d); } #endif } std::vector<std::string> getFileListRecursive(const std::string& dir, bool sorted) { std::vector<std::string> flist; getFileListRecursiveRec(dir, flist); if (sorted) { std::sort(flist.begin(), flist.end()); } return flist; } std::string makeValidUSDIdentifier(const std::string& name) { auto validName = pxr::TfMakeValidIdentifier(name); if (validName[0] == '_') { validName = "a" + validName; } if (pxr::TfIsValidIdentifier(name) == false) { CARB_LOG_WARN("The path %s is not a valid usd path, modifying to %s", name.c_str(), validName.c_str()); } return validName; } } } }
7,015
C++
19.635294
111
0.535567
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/utils/Path.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once // clang-format off #include "../UsdPCH.h" // clang-format on #include <string> #include <OmniClient.h> namespace omni { namespace importer { namespace utils { namespace path { inline std::string normalizeUrl(const char* url) { std::string ret; char stringBuffer[1024]; std::unique_ptr<char[]> stringBufferHeap; size_t bufferSize = sizeof(stringBuffer); const char* normalizedUrl = omniClientNormalizeUrl(url, stringBuffer, &bufferSize); if (!normalizedUrl) { stringBufferHeap = std::unique_ptr<char[]>(new char[bufferSize]); normalizedUrl = omniClientNormalizeUrl(url, stringBufferHeap.get(), &bufferSize); if (!normalizedUrl) { normalizedUrl = ""; CARB_LOG_ERROR("Cannot normalize %s", url); } } ret = normalizedUrl; for (auto& c : ret) { if (c == '\\') { c = '/'; } } return ret; } std::string resolve_absolute(std::string parent, std::string relative) { size_t bufferSize = parent.size() + relative.size(); std::unique_ptr<char[]> stringBuffer = std::unique_ptr<char[]>(new char[bufferSize]); std::string combined_url = normalizeUrl((parent + "/" + relative).c_str()); return combined_url; } } } } }
1,987
C
25.157894
99
0.663815
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/parse/UrdfParser.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "UrdfParser.h" #include "../core/PathUtils.h" #include <carb/logging/Log.h> namespace omni { namespace importer { namespace urdf { // Stream operators for nice printing std::ostream& operator<<(std::ostream& out, const Transform& origin) { out << "Origin: "; out << "px=" << origin.p.x << " py=" << origin.p.y << " pz=" << origin.p.z; out << " qx=" << origin.q.x << " qy=" << origin.q.y << " qz=" << origin.q.z << " qw=" << origin.q.w; return out; } std::ostream& operator<<(std::ostream& out, const UrdfInertia& inertia) { out << "Inertia: "; out << "ixx=" << inertia.ixx << " ixy=" << inertia.ixy << " ixz=" << inertia.ixz; out << " iyy=" << inertia.iyy << " iyz=" << inertia.iyz << " izz=" << inertia.izz; return out; } std::ostream& operator<<(std::ostream& out, const UrdfInertial& inertial) { out << "Inertial: " << std::endl; out << " \t \t" << inertial.origin << std::endl; if (inertial.hasMass) { out << " \t \tMass: " << inertial.mass << std::endl; } else { out << " \t \tMass: No mass was specified for the link" << std::endl; } if (inertial.hasInertia) { out << " \t \t" << inertial.inertia; } else { out << " \t \tInertia: No inertia was specified for the link" << std::endl; } return out; } std::ostream& operator<<(std::ostream& out, const UrdfAxis& axis) { out << "Axis: "; out << "x=" << axis.x << " y=" << axis.y << " z=" << axis.z; return out; } std::ostream& operator<<(std::ostream& out, const UrdfColor& color) { out << "Color: "; out << "r=" << color.r << " g=" << color.g << " b=" << color.b << " a=" << color.a; return out; } std::ostream& operator<<(std::ostream& out, const UrdfJointType& type) { out << "Type: "; std::string jointType = "unknown"; switch (type) { case UrdfJointType::REVOLUTE: jointType = "revolute"; break; case UrdfJointType::CONTINUOUS: jointType = "continuous"; break; case UrdfJointType::PRISMATIC: jointType = "prismatic"; break; case UrdfJointType::FIXED: jointType = "fixed"; break; case UrdfJointType::FLOATING: jointType = "floating"; break; case UrdfJointType::PLANAR: jointType = "planar"; break; } out << jointType; return out; } std::ostream& operator<<(std::ostream& out, const UrdfDynamics& dynamics) { out << "Dynamics: "; out << "damping=" << dynamics.damping << " friction=" << dynamics.friction; return out; } std::ostream& operator<<(std::ostream& out, const UrdfLimit& limit) { out << "Limit: "; out << "lower=" << limit.lower << " upper=" << limit.upper << " effort=" << limit.effort << " velocity=" << limit.velocity; out << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const UrdfGeometry& geometry) { out << "Geometry: "; switch (geometry.type) { case UrdfGeometryType::BOX: out << "type=box size=" << geometry.size_x << " " << geometry.size_y << " " << geometry.size_z; break; case UrdfGeometryType::CYLINDER: out << "type=cylinder radius=" << geometry.radius << " length=" << geometry.length; break; case UrdfGeometryType::CAPSULE: out << "type=capsule radius=" << geometry.radius << " length=" << geometry.length; break; case UrdfGeometryType::SPHERE: out << "type=sphere, radius=" << geometry.radius; break; case UrdfGeometryType::MESH: out << "type=mesh filemame=" << geometry.meshFilePath; break; } return out; } std::ostream& operator<<(std::ostream& out, const UrdfMaterial& material) { out << "Material: "; out << " Name=" << material.name << " " << material.color; if (!material.textureFilePath.empty()) out << " textureFilePath=" << material.textureFilePath; return out; } std::ostream& operator<<(std::ostream& out, const UrdfVisual& visual) { out << "Visual:" << std::endl; if (!visual.name.empty()) out << " \t \tName=" << visual.name << std::endl; out << " \t \t" << visual.origin << std::endl; out << " \t \t" << visual.geometry << std::endl; out << " \t \t" << visual.material; return out; } std::ostream& operator<<(std::ostream& out, const UrdfCollision& collision) { out << "Collision:" << std::endl; if (!collision.name.empty()) out << " \t \tName=" << collision.name << std::endl; out << " \t \t" << collision.origin << std::endl; out << " \t \t" << collision.geometry; return out; } std::ostream& operator<<(std::ostream& out, const UrdfLink& link) { out << "Link: "; out << " \tName=" << link.name << std::endl; for (auto& visual : link.visuals) { out << " \t" << visual << std::endl; } for (auto& collision : link.collisions) { out << " \t" << collision << std::endl; } out << " \t" << link.inertial << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const UrdfJoint& joint) { out << "Joint: "; out << " Name=" << joint.name << std::endl; out << " \t" << joint.type << std::endl; out << " \t" << joint.origin << std::endl; out << " \tParentLinkName=" << joint.parentLinkName << std::endl; out << " \tChildLinkName=" << joint.childLinkName << std::endl; out << " \t" << joint.axis << std::endl; out << " \t" << joint.dynamics << std::endl; out << " \t" << joint.limit << std::endl; out << " \t" << joint.dontCollapse << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const UrdfRobot& robot) { out << "Robot: "; out << robot.name << std::endl; for (auto& link : robot.links) { out << link.second << std::endl; } for (auto& joint : robot.joints) { out << joint.second << std::endl; } for (auto& material : robot.materials) { out << material.second << std::endl; } return out; } using namespace tinyxml2; bool parseXyz(const char* str, float& x, float& y, float& z) { if (sscanf(str, "%f %f %f", &x, &y, &z) == 3) { return true; } else { printf("*** Could not parse xyz string '%s' \n", str); return false; } } bool parseColor(const char* str, float& r, float& g, float& b, float& a) { if (sscanf(str, "%f %f %f %f", &r, &g, &b, &a) == 4) { return true; } else { printf("*** Could not parse color string '%s' \n", str); return false; } } bool parseFloat(const char* str, float& value) { if (sscanf(str, "%f", &value) == 1) { return true; } else { printf("*** Could not parse float string '%s' \n", str); return false; } } bool parseInt(const char* str, int& value) { if (sscanf(str, "%d", &value) == 1) { return true; } else { printf("*** Could not parse int string '%s' \n", str); return false; } } bool parseJointType(const char* str, UrdfJointType& type) { if (strcmp(str, "revolute") == 0) { type = UrdfJointType::REVOLUTE; } else if (strcmp(str, "continuous") == 0) { type = UrdfJointType::CONTINUOUS; } else if (strcmp(str, "prismatic") == 0) { type = UrdfJointType::PRISMATIC; } else if (strcmp(str, "fixed") == 0) { type = UrdfJointType::FIXED; } else if (strcmp(str, "floating") == 0) { type = UrdfJointType::FLOATING; } else if (strcmp(str, "planar") == 0) { type = UrdfJointType::PLANAR; } else { printf("*** Unknown joint type '%s' \n", str); return false; } return true; } bool parseJointMimic(const XMLElement& element, UrdfJointMimic& mimic) { auto jointElement = element.Attribute("joint"); if (jointElement) { mimic.joint = std::string(jointElement); } auto multiplierElement = element.Attribute("multiplier"); if (!multiplierElement || !parseFloat(multiplierElement, mimic.multiplier)) { mimic.multiplier = 1.0f; } auto offsetElement = element.Attribute("offset"); if (!offsetElement ||!parseFloat(offsetElement, mimic.offset)) { mimic.offset = 0; } return true; } bool parseOrigin(const XMLElement& element, Transform& origin) { auto originElement = element.FirstChildElement("origin"); if (originElement) { auto attribute = originElement->Attribute("xyz"); if (attribute) { if (!parseXyz(attribute, origin.p.x, origin.p.y, origin.p.z)) { // optional, use zero vector origin.p = Vec3(0.0); } } attribute = originElement->Attribute("rpy"); if (attribute) { // parse roll pitch yaw float roll = 0.0f; float pitch = 0.0f; float yaw = 0.0f; if (!parseXyz(attribute, roll, pitch, yaw)) { roll = pitch = yaw = 0.0; } // convert to transform quaternion: origin.q = rpy2quat(roll, pitch, yaw); } return true; } return false; } bool parseAxis(const XMLElement& element, UrdfAxis& axis) { auto axisElement = element.FirstChildElement("axis"); if (axisElement) { auto attribute = axisElement->Attribute("xyz"); if (attribute) { if (!parseXyz(attribute, axis.x, axis.y, axis.z)) { printf("*** xyz not specified for axis\n"); return false; } } } return true; } bool parseLimit(const XMLElement& element, UrdfLimit& limit) { auto limitElement = element.FirstChildElement("limit"); if (limitElement) { auto attribute = limitElement->Attribute("lower"); if (attribute) { if (!parseFloat(attribute, limit.lower)) { // optional, use zero if not specified limit.lower = 0.0; } } attribute = limitElement->Attribute("upper"); if (attribute) { if (!parseFloat(attribute, limit.upper)) { // optional, use zero if not specified limit.upper = 0.0; } } attribute = limitElement->Attribute("effort"); if (attribute) { if (!parseFloat(attribute, limit.effort)) { printf("*** effort not specified for limit\n"); return false; } } attribute = limitElement->Attribute("velocity"); if (attribute) { if (!parseFloat(attribute, limit.velocity)) { printf("*** velocity not specified for limit\n"); return false; } } } return true; } bool parseDynamics(const XMLElement& element, UrdfDynamics& dynamics) { auto dynamicsElement = element.FirstChildElement("dynamics"); if (dynamicsElement) { auto attribute = dynamicsElement->Attribute("damping"); if (attribute) { if (!parseFloat(attribute, dynamics.damping)) { // optional dynamics.damping = 0; } } attribute = dynamicsElement->Attribute("friction"); if (attribute) { if (!parseFloat(attribute, dynamics.friction)) { // optional dynamics.friction = 0; } } } return true; } bool parseMass(const XMLElement& element, float& mass) { auto massElement = element.FirstChildElement("mass"); if (massElement) { auto attribute = massElement->Attribute("value"); if (attribute) { if (!parseFloat(attribute, mass)) { printf("*** couldn't parse mass \n"); return false; } return true; } else { printf("*** mass missing from inertia \n"); return false; } } return false; } bool parseInertia(const XMLElement& element, UrdfInertia& inertia) { auto inertiaElement = element.FirstChildElement("inertia"); if (inertiaElement) { auto attribute = inertiaElement->Attribute("ixx"); if (attribute) { if (!parseFloat(attribute, inertia.ixx)) { return false; } } else { printf("*** ixx missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("ixz"); if (attribute) { if (!parseFloat(attribute, inertia.ixz)) { return false; } } else { printf("*** ixz missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("ixy"); if (attribute) { if (!parseFloat(attribute, inertia.ixy)) { return false; } } else { printf("*** ixy missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("iyy"); if (attribute) { if (!parseFloat(attribute, inertia.iyy)) { return false; } } else { printf("*** iyy missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("iyz"); if (attribute) { if (!parseFloat(attribute, inertia.iyz)) { return false; } } else { printf("*** iyz missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("izz"); if (attribute) { if (!parseFloat(attribute, inertia.izz)) { return false; } } else { printf("*** izz missing from inertia \n"); return false; } // if we made it here, all elements were parsed successfully return true; } return false; } bool parseInertial(const XMLElement& element, UrdfInertial& inertial) { auto inertialElement = element.FirstChildElement("inertial"); if (inertialElement) { inertial.hasOrigin = parseOrigin(*inertialElement, inertial.origin); inertial.hasMass = parseMass(*inertialElement, inertial.mass); inertial.hasInertia = parseInertia(*inertialElement, inertial.inertia); } return true; } bool parseGeometry(const XMLElement& element, UrdfGeometry& geometry) { auto geometryElement = element.FirstChildElement("geometry"); if (geometryElement) { auto geometryElementChild = geometryElement->FirstChildElement(); if (strcmp(geometryElementChild->Value(), "mesh") == 0) { geometry.type = UrdfGeometryType::MESH; auto filename = geometryElementChild->Attribute("filename"); if (filename) { geometry.meshFilePath = filename; } else { printf("*** mesh geometry requires a file path \n"); return false; } auto scale = geometryElementChild->Attribute("scale"); if (scale) { if (!parseXyz(scale, geometry.scale_x, geometry.scale_y, geometry.scale_z)) { printf("*** scale is missing xyz \n"); return false; } } } else if (strcmp(geometryElementChild->Value(), "box") == 0) { geometry.type = UrdfGeometryType::BOX; auto attribute = geometryElementChild->Attribute("size"); if (attribute) { if (!parseXyz(attribute, geometry.size_x, geometry.size_y, geometry.size_z)) { printf("*** couldn't parse xyz size \n"); return false; } } else { printf("*** box geometry requires a size \n"); return false; } } else if (strcmp(geometryElementChild->Value(), "cylinder") == 0) { geometry.type = UrdfGeometryType::CYLINDER; auto attribute = geometryElementChild->Attribute("radius"); if (attribute) { if (!parseFloat(attribute, geometry.radius)) { printf("*** couldn't parse radius \n"); return false; } } else { printf("*** cylinder geometry requires a radius \n"); return false; } attribute = geometryElementChild->Attribute("length"); if (attribute) { if (!parseFloat(attribute, geometry.length)) { printf("*** couldn't parse length \n"); return false; } } else { printf("*** cylinder geometry requires a length \n"); return false; } } else if (strcmp(geometryElementChild->Value(), "capsule") == 0) { geometry.type = UrdfGeometryType::CAPSULE; auto attribute = geometryElementChild->Attribute("radius"); if (attribute) { if (!parseFloat(attribute, geometry.radius)) { printf("*** couldn't parse radius \n"); return false; } } else { printf("*** capsule geometry requires a radius \n"); return false; } attribute = geometryElementChild->Attribute("length"); if (attribute) { if (!parseFloat(attribute, geometry.length)) { printf("*** couldn't parse length \n"); return false; } } else { printf("*** capsule geometry requires a length \n"); return false; } } else if (strcmp(geometryElementChild->Value(), "sphere") == 0) { geometry.type = UrdfGeometryType::SPHERE; auto attribute = geometryElementChild->Attribute("radius"); if (attribute) { if (!parseFloat(attribute, geometry.radius)) { printf("*** couldn't parse radius \n"); return false; } } else { printf("*** sphere geometry requires a radius \n"); return false; } } } return true; } bool parseChildAttributeFloat(const tinyxml2::XMLElement& element, const char* child, const char* attribute, float& output) { auto childElement = element.FirstChildElement(child); if (childElement) { const char* s = childElement->Attribute(attribute); if (s) { return parseFloat(s, output); } } return false; } bool parseChildAttributeString(const tinyxml2::XMLElement& element, const char* child, const char* attribute, std::string& output) { auto childElement = element.FirstChildElement(child); if (childElement) { const char* s = childElement->Attribute(attribute); if (s) { output = s; return true; } } return false; } // bool parseFem(const tinyxml2::XMLElement& element, UrdfFem& fem) // { // parseOrigin(element, fem.origin); // if (!parseChildAttributeFloat(element, "density", "value", fem.density)) // fem.density = 1000.0f; // if (!parseChildAttributeFloat(element, "youngs", "value", fem.youngs)) // fem.youngs = 1.e+4f; // if (!parseChildAttributeFloat(element, "poissons", "value", fem.poissons)) // fem.poissons = 0.3f; // if (!parseChildAttributeFloat(element, "damping", "value", fem.damping)) // fem.damping = 0.0f; // if (!parseChildAttributeFloat(element, "attachDistance", "value", fem.attachDistance)) // fem.attachDistance = 0.0f; // if (!parseChildAttributeString(element, "tetmesh", "filename", fem.meshFilePath)) // fem.meshFilePath = ""; // if (!parseChildAttributeFloat(element, "scale", "value", fem.scale)) // fem.scale = 1.0f; // return true; // } bool parseMaterial(const XMLElement& element, UrdfMaterial& material) { auto materialElement = element.FirstChildElement("material"); if (materialElement) { auto name = materialElement->Attribute("name"); if (name && strlen(name) > 0) { material.name = makeValidUSDIdentifier(name); } else { if (materialElement->FirstChildElement("color")) { if (!parseColor(materialElement->FirstChildElement("color")->Attribute("rgba"), material.color.r, material.color.g, material.color.b, material.color.a)) { // optional material.color = UrdfColor(); } } if (materialElement->FirstChildElement("texture")) { auto matString = materialElement->FirstChildElement("texture")->Attribute("filename"); if (matString == nullptr) { printf("*** filename required for material with texture \n"); return false; } material.textureFilePath = matString; } } } return true; } bool parseMaterials(const XMLElement& root, std::map<std::string, UrdfMaterial>& urdfMaterials) { auto materialElement = root.FirstChildElement("material"); if (materialElement) { do { UrdfMaterial material; auto name = materialElement->Attribute("name"); if (name) { material.name = makeValidUSDIdentifier(name); } else { printf("*** Found unnamed material \n"); return false; } auto elem = materialElement->FirstChildElement("color"); if (elem) { if (!parseColor(elem->Attribute("rgba"), material.color.r, material.color.g, material.color.b, material.color.a)) { return false; } } elem = materialElement->FirstChildElement("texture"); if (elem) { auto matString = elem->Attribute("filename"); if (matString == nullptr) { printf("*** filename required for material with texture \n"); return false; } } urdfMaterials.emplace(material.name, material); } while ((materialElement = materialElement->NextSiblingElement("material"))); } return true; } bool parseLinks(const XMLElement& root, std::map<std::string, UrdfLink>& urdfLinks) { auto linkElement = root.FirstChildElement("link"); if (linkElement) { do { UrdfLink link; // name auto name = linkElement->Attribute("name"); if (name) { link.name = makeValidUSDIdentifier(name); } else { printf("*** Found unnamed link \n"); return false; } // visuals auto visualElement = linkElement->FirstChildElement("visual"); if (visualElement) { do { UrdfVisual visual; auto name = visualElement->Attribute("name"); if (name) { visual.name = makeValidUSDIdentifier(name); } if (!parseOrigin(*visualElement, visual.origin)) { // optional default to identity transform visual.origin = Transform(); } if (!parseGeometry(*visualElement, visual.geometry)) { printf("*** Found visual without geometry \n"); return false; } if (!parseMaterial(*visualElement, visual.material)) { // optional, use default if not specified visual.material = UrdfMaterial(); } link.visuals.push_back(visual); } while ((visualElement = visualElement->NextSiblingElement("visual"))); } // collisions auto collisionElement = linkElement->FirstChildElement("collision"); if (collisionElement) { do { UrdfCollision collision; auto name = collisionElement->Attribute("name"); if (name) { collision.name = makeValidUSDIdentifier(name); } if (!parseOrigin(*collisionElement, collision.origin)) { // optional default to identity transform collision.origin = Transform(); } if (!parseGeometry(*collisionElement, collision.geometry)) { printf("*** Found collision without geometry \n"); return false; } link.collisions.push_back(collision); } while ((collisionElement = collisionElement->NextSiblingElement("collision"))); } // inertia if (!parseInertial(*linkElement, link.inertial)) { // optional, use default if not specified link.inertial = UrdfInertial(); } // auto femElement = linkElement->FirstChildElement("fem"); // if (femElement) // { // do // { // UrdfFem fem; // if (!parseFem(*femElement, fem)) // { // return false; // } // link.softs.push_back(fem); // } while ((femElement = femElement->NextSiblingElement("fem"))); // } urdfLinks.emplace(link.name, link); } while ((linkElement = linkElement->NextSiblingElement("link"))); } return true; } bool parseJoints(const XMLElement& root, std::map<std::string, UrdfJoint>& urdfJoints) { for(auto jointElement = root.FirstChildElement("joint"); jointElement; jointElement = jointElement->NextSiblingElement("joint")) { UrdfJoint joint; // name auto name = jointElement->Attribute("name"); if (name) { joint.name = makeValidUSDIdentifier(name); } else { printf("*** Found unnamed joint \n"); return false; } auto type = jointElement->Attribute("type"); if (type) { if (!parseJointType(type, joint.type)) { return false; } } else { printf("*** Found untyped joint \n"); return false; } auto dontCollapse = jointElement->Attribute("dont_collapse"); if (dontCollapse) { joint.dontCollapse = dontCollapse; } else { // default: if not specified, collapse the joint joint.dontCollapse = false; } auto parentElement = jointElement->FirstChildElement("parent"); if (parentElement) { joint.parentLinkName = makeValidUSDIdentifier(parentElement->Attribute("link")); } else { printf("*** Joint has no parent link \n"); return false; } auto childElement = jointElement->FirstChildElement("child"); if (childElement) { joint.childLinkName = makeValidUSDIdentifier(childElement->Attribute("link")); } else { printf("*** Joint has no child link \n"); return false; } if (!parseOrigin(*jointElement, joint.origin)) { // optional, default to identity joint.origin = Transform(); } if (!parseAxis(*jointElement, joint.axis)) { // optional, default to (1,0,0) joint.axis = UrdfAxis(); } if (!parseLimit(*jointElement, joint.limit)) { if (joint.type == UrdfJointType::REVOLUTE || joint.type == UrdfJointType::PRISMATIC) { printf("*** limit must be specified for revolute and prismatic \n"); return false; } joint.limit = UrdfLimit(); } if (!parseDynamics(*jointElement, joint.dynamics)) { // optional joint.dynamics = UrdfDynamics(); } urdfJoints.emplace(joint.name, joint); } // Add second pass to parse mimic information for(auto jointElement = root.FirstChildElement("joint"); jointElement; jointElement = jointElement->NextSiblingElement("joint")) { auto name = jointElement->Attribute("name"); if (name) { UrdfJoint& joint = urdfJoints[makeValidUSDIdentifier(name)]; auto mimicElement = jointElement->FirstChildElement("mimic"); if (mimicElement) { if(!parseJointMimic(*mimicElement, joint.mimic)) { joint.mimic.joint = ""; } else { auto& parentJoint = urdfJoints[joint.mimic.joint]; parentJoint.mimicChildren[joint.name] = joint.mimic.offset; } } } } return true; } // bool parseSpringGroup(const XMLElement& element, UrdfSpringGroup& springGroup) // { // auto start = element.Attribute("start"); // auto count = element.Attribute("size"); // auto scale = element.Attribute("scale"); // if (!start || !parseInt(start, springGroup.springStart)) // { // return false; // } // if (!count || !parseInt(count, springGroup.springCount)) // { // return false; // } // if (!scale || !parseFloat(scale, springGroup.scale)) // { // return false; // } // return true; // } // bool parseSoftActuators(const XMLElement& root, std::vector<UrdfSoft1DActuator>& urdfActs) // { // auto actuatorElement = root.FirstChildElement("actuator"); // while (actuatorElement) // { // auto name = actuatorElement->Attribute("name"); // auto type = actuatorElement->Attribute("type"); // if (type) // { // if (strcmp(type, "pneumatic1D") == 0) // { // UrdfSoft1DActuator act; // act.name = std::string(name); // act.link = std::string(actuatorElement->Attribute("link")); // auto gains = actuatorElement->FirstChildElement("gains"); // auto thresholds = actuatorElement->FirstChildElement("thresholds"); // auto springGroups = actuatorElement->FirstChildElement("springGroups"); // auto maxPressure = actuatorElement->Attribute("maxPressure"); // if (!maxPressure || !parseFloat(maxPressure, act.maxPressure)) // { // act.maxPressure = 0.0f; // } // if (gains) // { // auto inflate = gains->Attribute("inflate"); // auto deflate = gains->Attribute("deflate"); // if (!inflate || !parseFloat(inflate, act.inflateGain)) // { // act.inflateGain = 1.0f; // } // if (!deflate || !parseFloat(deflate, act.deflateGain)) // { // act.deflateGain = 1.0f; // } // } // if (thresholds) // { // auto deflate = thresholds->Attribute("deflate"); // auto deactivate = thresholds->Attribute("deactivate"); // if (!deflate || !parseFloat(deflate, act.deflateThreshold)) // { // act.deflateThreshold = 1.0f; // } // if (!deactivate || !parseFloat(deactivate, act.deactivateThreshold)) // { // act.deactivateThreshold = 1.0e-2f; // } // } // if (springGroups) // { // auto springGroup = springGroups->FirstChildElement("springGroup"); // while (springGroup) // { // UrdfSpringGroup sg; // if (parseSpringGroup(*springGroup, sg)) // { // act.springGroups.push_back(sg); // } // springGroup = springGroup->NextSiblingElement("springGroup"); // } // } // if (maxPressure && gains && thresholds && springGroups) // urdfActs.push_back(act); // else // { // printf("*** unable to parse soft actuator %s \n", act.name.c_str()); // return false; // } // } // } // actuatorElement = actuatorElement->NextSiblingElement("actuator"); // } // return true; // } bool parseRobot(const XMLElement& root, UrdfRobot& urdfRobot) { auto name = root.Attribute("name"); if (name) { urdfRobot.name = makeValidUSDIdentifier(name); } urdfRobot.links.clear(); urdfRobot.joints.clear(); urdfRobot.materials.clear(); if (!parseMaterials(root, urdfRobot.materials)) { return false; } if (!parseLinks(root, urdfRobot.links)) { return false; } if (!parseJoints(root, urdfRobot.joints)) { return false; } // if (!parseSoftActuators(root, urdfRobot.softActuators)) // { // return false; // } return true; } bool parseUrdf(const std::string& urdfPackagePath, const std::string& urdfFileRelativeToPackage, UrdfRobot& urdfRobot) { std::string path; // #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) // path = GetFilePathByPlatform((urdfPackagePath + "\\" + urdfFileRelativeToPackage).c_str()); //#else // path = GetFilePathByPlatform((urdfPackagePath + "/" + urdfFileRelativeToPackage).c_str()); //#endif path = urdfPackagePath + "/" + urdfFileRelativeToPackage; CARB_LOG_INFO("Loading URDF at '%s'", path.c_str()); // Weird stack smashing error with tinyxml2 when the descructor is called static tinyxml2::XMLDocument doc; if (doc.LoadFile(path.c_str()) != XML_SUCCESS) { printf("*** Failed to load '%s'", path.c_str()); return false; } XMLElement* root = doc.RootElement(); if (!root) { printf("*** Empty document '%s' \n", path.c_str()); return false; } if (!parseRobot(*root, urdfRobot)) { return false; } // std::cout << urdfRobot << std::endl; return true; } } // namespace urdf } }
37,675
C++
28.138438
135
0.503331
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/parse/UrdfParser.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "../UrdfTypes.h" #include <tinyxml2.h> namespace omni { namespace importer { namespace urdf { // Parsers bool parseJointType(const std::string& str, UrdfJointType& type); bool parseOrigin(const tinyxml2::XMLElement& element, Transform& origin); bool parseAxis(const tinyxml2::XMLElement& element, UrdfAxis& axis); bool parseLimit(const tinyxml2::XMLElement& element, UrdfLimit& limit); bool parseDynamics(const tinyxml2::XMLElement& element, UrdfDynamics& dynamics); bool parseMass(const tinyxml2::XMLElement& element, float& mass); bool parseInertia(const tinyxml2::XMLElement& element, UrdfInertia& inertia); bool parseInertial(const tinyxml2::XMLElement& element, UrdfInertial& inertial); bool parseGeometry(const tinyxml2::XMLElement& element, UrdfGeometry& geometry); bool parseMaterial(const tinyxml2::XMLElement& element, UrdfMaterial& material); bool parseMaterials(const tinyxml2::XMLElement& root, std::map<std::string, UrdfMaterial>& urdfMaterials); bool parseLinks(const tinyxml2::XMLElement& root, std::map<std::string, UrdfLink>& urdfLinks); bool parseJoints(const tinyxml2::XMLElement& root, std::map<std::string, UrdfJoint>& urdfJoints); bool parseUrdf(const std::string& urdfPackagePath, const std::string& urdfFileRelativeToPackage, UrdfRobot& urdfRobot); } // namespace urdf } }
2,032
C
32.327868
119
0.773622
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/docs/CHANGELOG.md
# Changelog ## [1.1.4] - 2023-10-18 ### Changed - Update code dependencies ## [1.1.3] - 2023-10-02 ### Changed - Mesh path parser now allows for prefixes other than "package://" ## [1.1.2] - 2023-08-21 ### Added - Added processing of capsule bodies to replace cylinders ### Fixed - Fixed computation of joint axis. Earlier arbitrary axis were not supported. - Fixed bug in merging joints when multiple levels of fixed joints exist. ## [1.1.1] - 2023-08-08 ### Added - Added support for the boolean attribute ``<joint dont_collapse>``: setting this parameter to true in the URDF joint tag prevents the child link from collapsing when the associated joint type is "fixed". ## [1.1.0] - 2023-08-04 ### Added - Suport for direct mimic joints - Maintain Merged Links as frames inside parent rigid body ### Fixed - Arbitrary joint axis were adding random 56.7 rotation degrees in the joint axis orientation ## [1.0.0] - 2023-07-03 ### Changed - Renamed the extension to omni.importer.urdf - Published the extension to the default registry ## [0.5.16] - 2023-06-27 ### Fixed - Support for arbitrary joint axis. ## [0.5.15] - 2023-06-26 ### Fixed - Support for non-diagonal inertia matrix - Support for convex decomposition mesh collision method ## [0.5.14] - 2023-06-13 ### Fixed - Kit 105.1 update - Accessing primvars is accessed through the PrimvarsAPI instead of usd convenience functions ## [0.5.13] - 2023-06-07 ### Fixed - Crash when name was not provided for a material, added check for null pointer and unit test ## [0.5.12] - 2023-05-16 ### Fixed - Removed duplicated code to copy collision geometry from the mesh visuals. ## [0.5.11] - 2023-05-06 ### Added - Collision geometry from visual meshes. ## [0.5.10] - 2023-05-04 ### Added - Code overview and limitations in README. ## [0.5.9] - 2023-02-28 ### Fixed - Appearance of carb warnings when setting the joint damping and stiffness to 0 for `NONE` drive type ## [0.5.8] - 2023-02-22 ### Fixed - removed max joint effort scaling by 60 during import - removed custom collision api when the shape is a cylinder ## [0.5.7] - 2023-02-17 ### Added - Unit test for joint limits. - URDF data file for joint limit unit test (test_limits.urdf) ## [0.5.6] - 2023-02-14 ### Fixed - Imported negative URDF effort and velocity joint constraints set the physics constraint value to infinity. ## [0.5.5] - 2023-01-06 ### Fixed - onclick_fn warning when creating UI ## [0.5.4] - 2022-10-13 ### Fixed - Fixes materials on instanceable imports ## [0.5.3] - 2022-10-13 ### Fixed - Added Test for import stl with custom material ## [0.5.2] - 2022-09-07 ### Fixed - Fixes for kit 103.5 ## [0.5.1] - 2022-01-02 ### Changed - Use omni.kit.viewport.utility when setting camera ## [0.5.0] - 2022-08-30 ### Changed - Remove direct legacy viewport calls ## [0.4.1] - 2022-08-30 ### Changed - Modified default gains in URDF -> USD converter to match gains for Franka and UR10 robots ## [0.4.0] - 2022-08-09 ### Added - Cobotta 900 urdf data files ## [0.3.1] - 2022-08-08 ### Fixed - Missing argument in example docstring ## [0.3.0] - 2022-07-09 ### Added - Add instanceable option to importer ## [0.2.2] - 2022-06-02 ### Changed - Fix title for file picker ## [0.2.1] - 2022-05-23 ### Changed - Fix units for samples ## [0.2.0] - 2022-05-17 ### Changed - Add joint values API ## [0.1.16] - 2022-04-19 ### Changed - Add Texture import compatibility for Windows. ## [0.1.16] - 2022-02-08 ### Changed - Revamped UI ## [0.1.15] - 2021-12-20 ### Changed - Fixed bug where missing mesh on part with urdf material assigned would crash on material binding in a non-existing prim. ## [0.1.14] - 2021-12-20 ### Changed - Fix bug where material was indexed by name and removing false duplicates. - Add Normal subdivision group import parameter. ## [0.1.13] - 2021-12-10 ### Changed - Texture support for OBJ and Collada assets. - Remove bug where an invalid link on a joint would stop importing the remainder of the urdf. raises an error message instead. ## [0.1.12] - 2021-12-03 ### Changed - Default to save Imported assets on a new USD and reference it on open stage. - Change base robot prim to also use orientOP instead of rotateOP - Change behavior where any stage event (e.g selection changed) was resetting some options on the UI ## [0.1.11] - 2021-11-29 ### Changed - Use double precision for xform ops to match isaac sim defaults ## [0.1.10] - 2021-11-04 ### Changed - create physics scene is false for import config - create physics scene will not create a scene if one exists - set default prim is false for import config ## [0.1.9] - 2021-10-25 ### Added - Support to specify usd paths for urdf meshes. ### Changed - distance_scale sets the stage to the same units for consistency - None drive mode still applies DriveAPI, but keeps the stiffness/damping at zero - rootJoint prim is renamed to root_joint for consistency with other joint names. ### Fixed - warnings when setting attributes as double when they should have been float ## [0.1.8] - 2021-10-18 ### Added - Floating joints are ignored but place any child links at the correct location. ### Fixed - Crash when urdf contained a floating joint ## [0.1.7] - 2021-09-23 ### Added - Default position drive damping to UI ### Fixed - Default config parameters are now respected ## [0.1.6] - 2021-08-31 ### Changed - Updated to New UI - Spheres and Cubes are treated as shapes - Cylinders are by default imported with custom geometry enabled - Joint drives are default force instead of acceleration ### Fixed - Meshes were not imported correctly, fixed subdivision scheme setting ### Removed - Parsing URDF is not a separate step with its own UI ## [0.1.5] - 2021-07-30 ### Fixed - Zero joint velocity issue - Artifact when dragging URDF file due to transform matrix ## [0.1.4] - 2021-06-09 ### Added - Fixed bugs with default density ## [0.1.3] - 2021-05-26 ### Added - Fixed bugs with import units - Streamlined UI and fixed missing elements - Fixed issues with creating new stage on import ## [0.1.2] - 2020-12-11 ### Added - Unit tests to extension - Add test urdf files - Fix unit issues with samples - Fix unit conversion issue with import ## [0.1.1] - 2020-12-03 ### Added - Sample URDF files for carter, franka ur10 and kaya ## [0.1.0] - 2020-12-03 ### Added - Initial version of URDF importer extension
6,385
Markdown
22.477941
205
0.701018
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/docs/index.rst
URDF Import Extension [omni.importer.urdf] ########################################## URDF Import Commands ==================== The following commands can be used to simplify the import process. Below is a sample demonstrating how to import the Carter URDF included with this extension .. code-block:: python :linenos: import omni.kit.commands from pxr import UsdLux, Sdf, Gf, UsdPhysics, PhysicsSchemaTools # setting up import configuration: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.convex_decomp = False import_config.import_inertia_tensor = True import_config.fix_base = False import_config.collision_from_visuals = False # Get path to extension data: ext_manager = omni.kit.app.get_app().get_extension_manager() ext_id = ext_manager.get_enabled_extension_id("omni.importer.urdf") extension_path = ext_manager.get_extension_path(ext_id) # import URDF omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=extension_path + "/data/urdf/robots/carter/urdf/carter.urdf", import_config=import_config, ) # get stage handle stage = omni.usd.get_context().get_stage() # enable physics scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) # set gravity scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) # add ground plane PhysicsSchemaTools.addGroundPlane(stage, "/World/groundPlane", "Z", 1500, Gf.Vec3f(0, 0, -50), Gf.Vec3f(0.5)) # add lighting distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) .. automodule:: omni.importer.urdf.scripts.commands :members: :undoc-members: :exclude-members: do, undo .. automodule:: omni.importer.urdf._urdf .. autoclass:: omni.importer.urdf._urdf.Urdf :members: :undoc-members: :no-show-inheritance: .. autoclass:: omni.importer.urdf._urdf.ImportConfig :members: :undoc-members: :no-show-inheritance:
2,157
reStructuredText
31.208955
113
0.684747
NVIDIA-Omniverse/kit-extension-sample-defectsgen/README.md
# Defect Extension Sample ![Defect Preview](exts/omni.example.defects/data/preview.PNG) ### About This extension allows user's to generate a single defect on a target prim using images to project the defect onto the prim. Using Replicator's API the user can generate thousands of synthetic data to specify the dimensions, rotation, and position of the defect. ### Pre-req This extension has been tested to work with Omniverse Code 2022.3.3 or higher. ### [README](exts/omni.example.defects) See the [README for this extension](exts/omni.example.defects) to learn more about it including how to use it. ## Adding This Extension This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths. Link might look like this: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-defects?branch=main&dir=exts` Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual. To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path ## Linking with an Omniverse app If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
1,971
Markdown
34.214285
261
0.763064
NVIDIA-Omniverse/kit-extension-sample-defectsgen/tools/scripts/link_app.py
import argparse import json import os import sys import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,814
Python
32.117647
133
0.562189
NVIDIA-Omniverse/kit-extension-sample-defectsgen/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
NVIDIA-Omniverse/kit-extension-sample-defectsgen/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import shutil import sys import tempfile import zipfile __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,844
Python
33.166666
108
0.703362
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.1.1" # The title and description fields are primarily for displaying extension info in UI title = "Defects Generation Sample" description="Example of a replicator extension that creates material defects using a Decal Proxy Object" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Icon to show in the extension manager icon = "data/icon.png" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "omnigraph", "replicator", "defect", "material"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.ui" = {} "omni.replicator.core" = {} "omni.kit.window.file_importer" = {} "omni.kit.commands" = {} "omni.usd" = {} "omni.kit.notification_manager" = {} # Main python module this extension provides, it will be publicly available as "import omni.code.snippets". [[python.module]] name = "omni.example.defects"
1,068
TOML
25.724999
107
0.72191
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/rep_widgets.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui from .widgets import MinMaxWidget, CustomDirectory, PathWidget from .utils import * from pxr import Sdf from pathlib import Path import omni.kit.notification_manager as nm TEXTURE_DIR = Path(__file__).parent / "data" SCRATCHES_DIR = TEXTURE_DIR / "scratches" # Parameter Objects class DefectParameters: def __init__(self) -> None: self.semantic_label = ui.SimpleStringModel("defect") self.count = ui.SimpleIntModel(1) self._build_semantic_label() self.defect_text = CustomDirectory("Defect Texture Folder", default_dir=str(SCRATCHES_DIR.as_posix()), tooltip="A folder location containing a single or set of textures (.png)", file_types=[("*.png", "PNG"), ("*", "All Files")]) self.dim_w = MinMaxWidget("Defect Dimensions Width", min_value=0.1, tooltip="Defining the Minimum and Maximum Width of the Defect") self.dim_h = MinMaxWidget("Defect Dimensions Length", min_value=0.1, tooltip="Defining the Minimum and Maximum Length of the Defect") self.rot = MinMaxWidget("Defect Rotation", tooltip="Defining the Minimum and Maximum Rotation of the Defect") def _build_semantic_label(self): with ui.HStack(height=0, tooltip="The label that will be associated with the defect"): ui.Label("Defect Semantic") ui.StringField(model=self.semantic_label) def destroy(self): self.semantic_label = None self.defect_text.destroy() self.defect_text = None self.dim_w.destroy() self.dim_w = None self.dim_h.destroy() self.dim_h = None self.rot.destroy() self.rot = None class ObjectParameters(): def __init__(self) -> None: self.target_prim = PathWidget("Target Prim") def apply_primvars(prim): # Apply prim vars prim.CreateAttribute('primvars:d1_forward_vector', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) prim.CreateAttribute('primvars:d1_right_vector', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) prim.CreateAttribute('primvars:d1_up_vector', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) prim.CreateAttribute('primvars:d1_position', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) prim.CreateAttribute('primvars:v3_scale', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) nm.post_notification(f"Applied Primvars to: {prim.GetPath()}", hide_after_timeout=True, duration=5, status=nm.NotificationStatus.INFO) def apply(): # Check Paths if not check_path(self.target_prim.path_value): return # Check if prim is valid prim = is_valid_prim(self.target_prim.path_value) if prim is None: return apply_primvars(prim) ui.Button("Apply", style={"padding": 5}, clicked_fn=lambda: apply(), tooltip="Apply Primvars and Material to selected Prim." ) def destroy(self): self.target_prim.destroy() self.target_prim = None class MaterialParameters(): def __init__(self) -> None: pass
4,224
Python
40.831683
146
0.608191
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/widgets.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui from omni.kit.window.file_importer import get_file_importer from typing import List import carb import omni.usd class CustomDirectory: def __init__(self, label: str, tooltip: str = "", default_dir: str = "", file_types: List[str] = None) -> None: self._label_text = label self._tooltip = tooltip self._file_types = file_types self._dir = ui.SimpleStringModel(default_dir) self._build_directory() @property def directory(self) -> str: """ Selected Directory name from file importer :type: str """ return self._dir.get_value_as_string() def _build_directory(self): with ui.HStack(height=0, tooltip=self._tooltip): ui.Label(self._label_text) ui.StringField(model=self._dir) ui.Button("Open", width=0, style={"padding": 5}, clicked_fn=self._pick_directory) def _pick_directory(self): file_importer = get_file_importer() if not file_importer: carb.log_warning("Unable to get file importer") file_importer.show_window(title="Select Folder", import_button_label="Import Directory", import_handler=self.import_handler, file_extension_types=self._file_types ) def import_handler(self, filename: str, dirname: str, selections: List[str] = []): self._dir.set_value(dirname) def destroy(self): self._dir = None class MinMaxWidget: def __init__(self, label: str, min_value: float = 0, max_value: float = 1, tooltip: str = "") -> None: self._min_model = ui.SimpleFloatModel(min_value) self._max_model = ui.SimpleFloatModel(max_value) self._label_text = label self._tooltip = tooltip self._build_min_max() @property def min_value(self) -> float: """ Min Value of the UI :type: int """ return self._min_model.get_value_as_float() @property def max_value(self) -> float: """ Max Value of the UI :type: int """ return self._max_model.get_value_as_float() def _build_min_max(self): with ui.HStack(height=0, tooltip=self._tooltip): ui.Label(self._label_text) with ui.HStack(): ui.Label("Min", width=0) ui.FloatDrag(model=self._min_model) ui.Label("Max", width=0) ui.FloatDrag(model=self._max_model) def destroy(self): self._max_model = None self._min_model = None class PathWidget: def __init__(self, label: str, button_label: str = "Copy", read_only: bool = False, tooltip: str = "") -> None: self._label_text = label self._tooltip = tooltip self._button_label = button_label self._read_only = read_only self._path_model = ui.SimpleStringModel() self._top_stack = ui.HStack(height=0, tooltip=self._tooltip) self._button = None self._build() @property def path_value(self) -> str: """ Path of the Prim in the scene :type: str """ return self._path_model.get_value_as_string() @path_value.setter def path_value(self, value) -> None: """ Sets the path value :type: str """ self._path_model.set_value(value) def _build(self): def copy(): ctx = omni.usd.get_context() selection = ctx.get_selection().get_selected_prim_paths() if len(selection) > 0: self._path_model.set_value(str(selection[0])) with self._top_stack: ui.Label(self._label_text) ui.StringField(model=self._path_model, read_only=self._read_only) self._button = ui.Button(self._button_label, width=0, style={"padding": 5}, clicked_fn=lambda: copy(), tooltip="Copies the Current Selected Path in the Stage") def destroy(self): self._path_model = None
4,815
Python
31.986301
171
0.58837
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/style.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui default_defect_main = { "Button": { "width": 0, "background_color": ui.color.black }, "HStack": { "padding": 5 } }
859
Python
29.714285
98
0.710128
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/extension.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ext from .window import DefectsWindow class DefectsGenerator(omni.ext.IExt): WINDOW_NAME = "Defects Sample Extension" MENU_PATH = f"Window/{WINDOW_NAME}" def __init__(self) -> None: super().__init__() self._window = None def on_startup(self, ext_id): self._menu = omni.kit.ui.get_editor_menu().add_item( DefectsGenerator.MENU_PATH, self.show_window, toggle=True, value=True ) self.show_window(None, True) def on_shutdown(self): if self._menu: omni.kit.ui.get_editor_menu().remove_item(DefectsGenerator.MENU_PATH) self._menu if self._window: self._window.destroy() self._window = None def _set_menu(self, value): omni.kit.ui.get_editor_menu().set_value(DefectsGenerator.MENU_PATH, value) def _visibility_changed_fn(self, visible): self._set_menu(visible) if not visible: self._window = None def show_window(self, menu, value): self._set_menu(value) if value: self._set_menu(True) self._window = DefectsWindow(DefectsGenerator.WINDOW_NAME, width=450, height=700) self._window.set_visibility_changed_fn(self._visibility_changed_fn) elif self._window: self._window.visible = False
2,037
Python
34.13793
98
0.65783
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/__init__.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .extension import *
705
Python
40.529409
98
0.770213
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/utils.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.usd import carb import omni.kit.commands import os def get_current_stage(): context = omni.usd.get_context() stage = context.get_stage() return stage def check_path(path: str) -> bool: if not path: carb.log_error("No path was given") return False return True def is_valid_prim(path: str): prim = get_prim(path) if not prim.IsValid(): carb.log_warn(f"No valid prim at path given: {path}") return None return prim def delete_prim(path: str): omni.kit.commands.execute('DeletePrims', paths=[path], destructive=False) def get_prim_attr(prim_path: str, attr_name: str): prim = get_prim(prim_path) return prim.GetAttribute(attr_name).Get() def get_textures(dir_path, png_type=".png"): textures = [] dir_path += "/" for file in os.listdir(dir_path): if file.endswith(png_type): textures.append(dir_path + file) return textures def get_prim(prim_path: str): stage = get_current_stage() prim = stage.GetPrimAtPath(prim_path) return prim
1,768
Python
28
98
0.687783
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/window.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import carb import omni.ui as ui from omni.ui import DockPreference from .style import * from .widgets import CustomDirectory from .replicator_defect import create_defect_layer, rep_preview, does_defect_layer_exist, rep_run, get_defect_layer from .rep_widgets import DefectParameters, ObjectParameters from .utils import * from pathlib import Path class DefectsWindow(ui.Window): def __init__(self, title: str, dockPreference: DockPreference = DockPreference.DISABLED, **kwargs) -> None: super().__init__(title, dockPreference, **kwargs) # Models self.frames = ui.SimpleIntModel(1, min=1) self.rt_subframes = ui.SimpleIntModel(1, min=1) # Widgets self.defect_params = None self.object_params = None self.output_dir = None self.frame_change = None self.frame.set_build_fn(self._build_frame) def _build_collapse_base(self, label: str, collapsed: bool = False): v_stack = None with ui.CollapsableFrame(label, height=0, collapsed=collapsed): with ui.ZStack(): ui.Rectangle() v_stack = ui.VStack() return v_stack def _build_frame(self): with self.frame: with ui.ScrollingFrame(style=default_defect_main): with ui.VStack(style={"margin": 3}): self._build_object_param() self._build_defect_param() self._build_replicator_param() def _build_object_param(self): with self._build_collapse_base("Object Parameters"): self.object_params = ObjectParameters() def _build_defect_param(self): with self._build_collapse_base("Defect Parameters"): self.defect_params = DefectParameters() def _build_replicator_param(self): def preview_data(): if does_defect_layer_exist(): rep_preview() else: create_defect_layer(self.defect_params, self.object_params) self.rep_layer_button.text = "Recreate Replicator Graph" def remove_replicator_graph(): if get_defect_layer() is not None: layer, pos = get_defect_layer() omni.kit.commands.execute('RemoveSublayer', layer_identifier=layer.identifier, sublayer_position=pos) if is_valid_prim('/World/Looks/ProjectPBRMaterial'): delete_prim('/World/Looks/ProjectPBRMaterial') if is_valid_prim(self.object_params.target_prim.path_value + "/Projection"): delete_prim(self.object_params.target_prim.path_value + "/Projection") if is_valid_prim('/Replicator'): delete_prim('/Replicator') def run_replicator(): remove_replicator_graph() total_frames = self.frames.get_value_as_int() subframes = self.rt_subframes.get_value_as_int() if subframes <= 0: subframes = 0 if total_frames > 0: create_defect_layer(self.defect_params, self.object_params, total_frames, self.output_dir.directory, subframes, self._use_seg.as_bool, self._use_bb.as_bool) self.rep_layer_button.text = "Recreate Replicator Graph" rep_run() else: carb.log_error(f"Number of frames is {total_frames}. Input value needs to be greater than 0.") def create_replicator_graph(): remove_replicator_graph() create_defect_layer(self.defect_params, self.object_params) self.rep_layer_button.text = "Recreate Replicator Graph" def set_text(label, model): label.text = model.as_string with self._build_collapse_base("Replicator Parameters"): home_dir = Path.home() valid_out_dir = home_dir / "omni.replicator_out" self.output_dir = CustomDirectory("Output Directory", default_dir=str(valid_out_dir.as_posix()), tooltip="Directory to specify where the output files will be stored. Default is [DRIVE/Users/USER/omni.replicator_out]") with ui.HStack(height=0, tooltip="Check off which annotator you want to use; You can also use both"): ui.Label("Annotations: ", width=0) ui.Spacer() ui.Label("Segmentation", width=0) self._use_seg = ui.CheckBox().model ui.Label("Bounding Box", width=0) self._use_bb = ui.CheckBox().model ui.Spacer() with ui.HStack(height=0): ui.Label("Render Subframe Count: ", width=0, tooltip="Defines how many subframes of rendering occur before going to the next frame") ui.Spacer(width=ui.Fraction(0.25)) ui.IntField(model=self.rt_subframes) self.rep_layer_button = ui.Button("Create Replicator Layer", clicked_fn=lambda: create_replicator_graph(), tooltip="Creates/Recreates the Replicator Graph, based on the current Defect Parameters") with ui.HStack(height=0): ui.Button("Preview", width=0, clicked_fn=lambda: preview_data(), tooltip="Preview a Replicator Scene") ui.Label("or", width=0) ui.Button("Run for", width=0, clicked_fn=lambda: run_replicator(), tooltip="Run replicator for so many frames") with ui.ZStack(width=0): l = ui.Label("", style={"color": ui.color.transparent, "margin_width": 10}) self.frame_change = ui.StringField(model=self.frames) self.frame_change_cb = self.frame_change.model.add_value_changed_fn(lambda m, l=l: set_text(l, m)) ui.Label("frame(s)") def destroy(self) -> None: self.frames = None self.defect_semantic = None if self.frame_change is not None: self.frame_change.model.remove_value_changed_fn(self.frame_change_cb) if self.defect_params is not None: self.defect_params.destroy() self.defect_params = None if self.object_params is not None: self.object_params.destroy() self.object_params = None return super().destroy()
7,174
Python
46.833333
229
0.597017
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/replicator_defect.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.replicator.core as rep import carb from .rep_widgets import DefectParameters, ObjectParameters from .utils import * camera_path = "/World/Camera" def rep_preview(): rep.orchestrator.preview() def rep_run(): rep.orchestrator.run() def does_defect_layer_exist() -> bool: stage = get_current_stage() for layer in stage.GetLayerStack(): if layer.GetDisplayName() == "Defect": return True return False def get_defect_layer(): stage = get_current_stage() pos = 0 for layer in stage.GetLayerStack(): if layer.GetDisplayName() == "Defect": return layer, pos pos = pos + 1 return None def create_randomizers(defect_params: DefectParameters, object_params: ObjectParameters): diffuse_textures = get_textures(defect_params.defect_text.directory, "_D.png") normal_textures = get_textures(defect_params.defect_text.directory, "_N.png") roughness_textures = get_textures(defect_params.defect_text.directory, "_R.png") def move_defect(): defects = rep.get.prims(semantics=[('class', defect_params.semantic_label.as_string + '_mesh')]) plane = rep.get.prim_at_path(object_params.target_prim.path_value) with defects: rep.randomizer.scatter_2d(plane) rep.modify.pose( rotation=rep.distribution.uniform( (defect_params.rot.min_value, 0, 90), (defect_params.rot.max_value, 0, 90) ), scale=rep.distribution.uniform( (1, defect_params.dim_h.min_value,defect_params.dim_w.min_value), (1, defect_params.dim_h.max_value, defect_params.dim_w.max_value) ) ) return defects.node def change_defect_image(): projections = rep.get.prims(semantics=[('class', defect_params.semantic_label.as_string + '_projectmat')]) with projections: rep.modify.projection_material( diffuse=rep.distribution.sequence(diffuse_textures), normal=rep.distribution.sequence(normal_textures), roughness=rep.distribution.sequence(roughness_textures)) return projections.node rep.randomizer.register(move_defect) rep.randomizer.register(change_defect_image) def create_camera(target_path): if is_valid_prim(camera_path) is None: camera = rep.create.camera(position=1000, look_at=rep.get.prim_at_path(target_path)) carb.log_info(f"Creating Camera: {camera}") else: camera = rep.get.prim_at_path(camera_path) return camera def create_defects(defect_params: DefectParameters, object_params: ObjectParameters): target_prim = rep.get.prims(path_pattern=object_params.target_prim.path_value) count = 1 if defect_params.count.as_int > 1: count = defect_params.count.as_int for i in range(count): cube = rep.create.cube(visible=False, semantics=[('class', defect_params.semantic_label.as_string + '_mesh')], position=0, scale=1, rotation=(0, 0, 90)) with target_prim: rep.create.projection_material(cube, [('class', defect_params.semantic_label.as_string + '_projectmat')]) def create_defect_layer(defect_params: DefectParameters, object_params: ObjectParameters, frames: int = 1, output_dir: str = "_defects", rt_subframes: int = 0, use_seg: bool = False, use_bb: bool = True): if len(defect_params.defect_text.directory) <= 0: carb.log_error("No directory selected") return with rep.new_layer("Defect"): create_defects(defect_params, object_params) create_randomizers(defect_params=defect_params, object_params=object_params) # Create / Get camera camera = create_camera(object_params.target_prim.path_value) # Add Default Light distance_light = rep.create.light(rotation=(315,0,0), intensity=3000, light_type="distant") render_product = rep.create.render_product(camera, (1024, 1024)) # Initialize and attach writer writer = rep.WriterRegistry.get("BasicWriter") writer.initialize(output_dir=output_dir, rgb=True, semantic_segmentation=use_seg, bounding_box_2d_tight=use_bb) # Attach render_product to the writer writer.attach([render_product]) # Setup randomization with rep.trigger.on_frame(num_frames=frames, rt_subframes=rt_subframes): rep.randomizer.move_defect() rep.randomizer.change_defect_image()
5,247
Python
40.984
204
0.66438
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.1.1] - 2023-08-23 ### Changed - Changed annotations to use Tight Bounding Box instead of Loose - Updated ReadMe ## [1.1.0] - 2023-08-15 ### Removed - Ogn nodes, these nodes are now apart of the replicator pipeline - proxy.usd, Replicator has built in functionality in their nodes that creates the proxy - Functions in `utils.py` that are not longer being used - Region selection ### Added - Options to either use bounding boxes or segmentation - Functionality to remove new prims created by Replicator - Notificataion popup for when the prim vars are applied to the mesh ### Changed - Textures are now represented as a D, N, and R - D is Diffuse - N is Normal - R is Roughness - Default values for dimensions start at 0.1 - Output Directory UI defaults to replicator default output directory - Textures folder UI defaults to folder inside of extension with sample scratches - Updated README talking about the new images being used ## [1.0.1] - 2023-04-18 ### Changed - CustomDirectory now takes file_types if the user wants to specify the files they can filter by - Material that is applied to the prim ### Fixed - Nodes not connecting properly with Code 2022.3.3 - In utils.py if rotation is not found use (0,0,0) as default - lookat in utils.py could not subtract Vec3f by Vec3d
1,484
Markdown
28.117647
96
0.745957
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/docs/README.md
# Defects Sample Extension (omni.sample.defects) ![Defects Preview](../data/preview.png) ## Overview The Defects Sample Extension allows users to choose a texture, that represents a defect, to apply to a [Prim](https://docs.omniverse.nvidia.com/prod_usd/prod_usd/quick-start/prims.html) and generate synthetic data of the position, rotation, and dimensions of that texture. This Sample Extension utilizes Omniverse's [Replicator](https://developer.nvidia.com/omniverse/replicator) functionality for randomizing and generating synthetic data. ## UI Overview ### Object Parameters ![Object Params](../data/objparam.png) 1. Target Prim - This defines what prim the material to apply to. To get the prim path, **select** a prim in the scene then hit the **Copy button** 2. Apply - Once you have a Target Prim selected and Copied it's path, hitting Apply will bring in the proxy, decal material and create the primvar's on the Target Prim. ### Defect Parameters ![Defect Params](../data/defectparam.png) Randomizations are based on Replicator's [Distributions](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator/distribution_examples.html) 1. Defect Semantic - The semantic label that will be used to represent the defect in the output file produced by Replicator. - Default Value: `defect` 2. Defect Texture Folder - A folder location that holds all the texture(s) to choose from. Textures should be in PNG format. - Default Value: data folder within the Defect Extension - Defect textures are composed of a Diffuse, Normal, and Roughness texture to represent the defect. Example shown below: Diffuse Texture | Normal Texture | Roughness Texture :-------------------------:|:-------------------------:|:-------------------------: ![](../omni/example/defects/data/scratches/scratch_0_D.png) | ![](../omni/example/defects/data/scratches/scratch_0_N.png) | ![](../omni/example/defects/data/scratches/scratch_0_R.png) 3. Defect Dimensions Width - Replicator will choose random values between the Min and Max defined (cms) - Default Value Min: `0.1` - Default Value Max: `1` 4. Defect Dimensions Length - Replicator will choose random values between the Min and Max defined (cms) - Default Value Min: `0.1` - Default Value Max: `1` 5. Defect Rotation - Replicator will choose random values between the Min and Max defined (cms) and will set that rotation. - Default Value Min: `0.1` - Default Value Max: `1` A recommended set of values using the CarDefectPanel scene is the following: - Defect Semantics: Scratch - Defect Texture: [Path to Scratchs located in Extension] - Defect Dimensions Width: Min 0.1 Max 0.2 - Defect Dimensions Length: Min 0.15 Max 0.2 - Defect Rotation: Min 0 Max 360 ### Replicator Parameters ![Rep Params](../data/repparam.png) 1. Output Directory - Defines the location in which Replicator will use to output data. By default it will be `DRIVE/Users/USER/omni.replicator_out` 2. Annotations - There are two types of annotations you can choose from: Segmentation and/or Bounding Box. You can select both of these. For other annotation options you will need to adjust the code inside the extension. 3. [Render Subframe](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator/subframes_examples.html) Count - If rendering in RTX Realtime mode, specifies the number of subframes to render in order to reduce artifacts caused by large changes in the scene. 4. Create Replicator Layer - Generates the [OmniGraph](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph.html) or Omni.Replicator graph architecture, if changes are made the user can click this button to reflect changes. This does not run the actual execution or logic. 5. Preview - **Preview** performs a single iteration of randomizations and prevents data from being written to disk. 6. Run for X frames - **Run for** will run the generation for a specified amount of frames. Each frame will be one data file so 100 frames will produce 100 images/json/npy files. ![scratch](../data/scratch.gif)
4,187
Markdown
50.703703
276
0.736566
NVIDIA-Omniverse/kit-extension-sample-apiconnect/README.md
# API Connect Sample Omniverse Extension ![preview.png](/exts/omni.example.apiconnect/data/preview.png) ### About This Sample Omniverse Extension demonstrates how connect to an API. In this sample, we create a palette of colors using the [HueMint.com](https://huemint.com/). API. ### [README](exts/omni.example.apiconnect) See the [README for this extension](exts/omni.example.apiconnect) to learn more about it including how to use it. ## [Tutorial](exts/omni.example.apiconnect/docs/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.apiconnect/docs/tutorial.md) that walks you through how to build this extension using [asyncio](https://docs.python.org/3/library/asyncio.html) and [aiohttp](https://docs.aiohttp.org/en/stable/). ## Adding This Extension To add a this extension to your Omniverse app: 1. Go into: Extension Manager -> Hamburger Icon -> Settings -> Extension Search Path 2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-apiconnect.git?branch=main&dir=exts` Alternatively: 1. Download or Clone the extension, unzip the file if downloaded 2. Copy the `exts` folder path within the extension folder - i.e. home/.../kit-extension-sample-apiconnect/exts (Linux) or C:/.../kit-extension-sample-apiconnect/exts (Windows) 3. Go into: Extension Manager -> Hamburger Icon -> Settings -> Extension Search Path 4. Add the `exts` folder path as a search path ## Linking with an Omniverse app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash # Windows > link_app.bat ``` ```shell # Linux ~$ ./link_app.sh ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps are installed the script will select the recommended one. Or you can explicitly pass an app: ```bash # Windows > link_app.bat --app code ``` ```shell # Linux ~$ ./link_app.sh --app code ``` You can also pass a path that leads to the Omniverse package folder to create the link: ```bash # Windows > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3" ``` ```shell # Linux ~$ ./link_app.sh --path "home/bob/.local/share/ov/pkg/create-2022.1.3" ``` ## Attribution & Acknowledgements This extension uses the [Huemint.com API](https://huemint.com/about/). Huemint uses machine learning to create unique color schemes. Special thanks to Jack Qiao for allowing us to use the Huemint API for this demonstration. Check out [Huemint.com](https://huemint.com/) ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
2,739
Markdown
33.25
246
0.744797
NVIDIA-Omniverse/kit-extension-sample-apiconnect/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
NVIDIA-Omniverse/kit-extension-sample-apiconnect/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
NVIDIA-Omniverse/kit-extension-sample-apiconnect/tools/packman/bootstrap/install_package.py
# Copyright 2023 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.1.0" # The title and description fields are primarily for displaying extension info in UI title = "API Connect Sample" description="A sample extension that demonstrate how to connect to an API. In this sample we use the HueMint.com API to generate a set of colors." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.apiconnect". [[python.module]] name = "omni.example.apiconnect" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,118
TOML
26.974999
146
0.737925
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/extension.py
# SPDX-License-Identifier: Apache-2.0 import asyncio import aiohttp import carb import omni.ext import omni.ui as ui class APIWindowExample(ui.Window): def __init__(self, title: str, **kwargs) -> None: """ Initialize the widget. Args: title : Title of the widget. This is used to display the window title on the GUI. """ super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) # async function to get the color palette from huemint.com and print it async def get_colors_from_api(self, color_widgets): """ Get colors from HueMint API and store them in color_widgets. Args: color_widgets : List of widgets to """ # Create the task for progress indication and change button text self.button.text = "Loading" task = asyncio.create_task(self.run_forever()) # Create a aiohttp session to make the request, building the url and the data to send # By default it will timeout after 5 minutes. # See more here: https://docs.aiohttp.org/en/latest/client_quickstart.html async with aiohttp.ClientSession() as session: url = "https://api.huemint.com/color" data = { "mode": "transformer", # transformer, diffusion or random "num_colors": "5", # max 12, min 2 "temperature": "1.2", # max 2.4, min 0 "num_results": "1", # max 50 for transformer, 5 for diffusion "adjacency": ["0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0", ], # nxn adjacency matrix as a flat array of strings "palette": ["-", "-", "-", "-", "-"], # locked colors as hex codes, or '-' if blank } # make the request try: async with session.post(url, json=data) as resp: # get the response as json result = await resp.json(content_type=None) # get the palette from the json palette = result["results"][0]["palette"] # apply the colors to the color widgets await self.apply_colors(palette, color_widgets) # Cancel the progress indication and return the button to the original text task.cancel() self.button.text = "Refresh" except Exception as e: carb.log_info(f"Caught Exception {e}") # Cancel the progress indication and return the button to the original text task.cancel() self.button.text = "Connection Timed Out \nClick to Retry" # apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): """ Apply the colors to the ColorWidget. This is a helper method to allow us to get the color values from the API and set them in the color widgets Args: palette : The palette that we want to apply color_widgets : The list of color widgets """ colors = [palette[i] for i in range(5)] index = 0 # This will fetch the RGB colors from the color widgets and set them to the color of the color widget. for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() # we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) # we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 async def run_forever(self): """ Run the loop until we get a response from omni. """ count = 0 dot_count = 0 # Update the button text. while True: # Reset the button text to Loading if count % 10 == 0: # Reset the text for the button # Add a dot after Loading. if dot_count == 3: self.button.text = "Loading" dot_count = 0 # Add a dot after Loading else: self.button.text += "." dot_count += 1 count += 1 await omni.kit.app.get_app().next_update_async() # hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): """ Convert hex values to floating point numbers. This is useful for color conversion to a 3 or 5 digit hex value Args: h : RGB string in the format 0xRRGGBB Returns: float tuple of ( r g b ) where r g b are floats between 0 and 1 and b """ # Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i : i + 2], 16) / 255.0 for i in (1, 3, 5)) # skip '#' def _build_fn(self): """ Build the function to call the api when the app starts. """ with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): # Get the run loop run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette", height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1, 1, 1) for i in range(5)] def on_click(): """ Get colors from API and run task in run_loop. This is called when user clicks the button """ run_loop.create_task(self.get_colors_from_api(color_widgets)) # create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) # we execute the api call once on startup run_loop.create_task(self.get_colors_from_api(color_widgets)) # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): """ Called when the extension is started. Args: ext_id - id of the extension """ print("[omni.example.apiconnect] MyExtension startup") # create a new window self._window = APIWindowExample("API Connect Demo - HueMint", width=260, height=270) def on_shutdown(self): """ Called when the extension is shut down. Destroys the window if it exists and sets it to None """ print("[omni.example.apiconnect] MyExtension shutdown") # Destroys the window and releases the reference to the window. if self._window: self._window.destroy() self._window = None
7,649
Python
40.351351
130
0.569355
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/__init__.py
# SPDX-License-Identifier: Apache-2.0 from .extension import *
64
Python
15.249996
37
0.75
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.example.apiconnect # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = omni.example.apiconnect.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,682
Python
34.80851
142
0.68371
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2022-10-07 ### Added - Initial version of extension ## [1.1.0] - 2023-10-17 ### Added - Step by Step tutorial - APIWindowExample class - Progress indicator when the API is being called - `next_update_async()` to prevent the App from hanging ### Changed - Updated README - Sizing of UI is dynamic rather than static - Using `create_task` rather than `ensure_future` - Moved Window functionality into it's own class - Moved outer functions to Window Class ### Removed - Unused imports
594
Markdown
23.791666
80
0.720539
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/docs/README.md
# API Connection (omni.example.apiconnect) ![](../data/preview.gif) ​ ## Overview This Extension makes a single API call and updates UI elements. It demonstrates how to make API calls without interfering with the main loop of Omniverse. See [Adding the Extension](../../../README.md#adding-this-extension) on how to add the extension to your project. ​ ## [Tutorial](tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. Learn how to create an Extension that calls an API and use that information to update components within Omniverse. ​[Get started with the tutorial here.](tutorial.md) ## Usage Once the extension is enabled in the *Extension Manager*, you should see a similar line inside the viewport like in the to the image before [Overview section](#overview). Clicking on the *Refresh* button will send a request to [HueMint.com](https://huemint.com/) API. HueMint then sends back a palette of colors which is used to update the 5 color widgets in the UI. Hovering over each color widget will display the values used to define the color. The color widgets can also be clicked on which opens a color picker UI.
1,230
Markdown
54.954543
349
0.772358
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/docs/tutorial.md
# Connecting API to Omniverse Extension The API Connection extension shows how to communicate with an API within Omniverse. This guide is great for extension builders who want to start using their own API tools or external API tools within Omniverse. > NOTE: Visual Studio Code is the preferred IDE, hence forth we will be referring to it throughout this guide. > NOTE: Omniverse Code is the preferred platform, hence forth we will be referring to it throughout this guide. # Learning Objectives In this tutorial you learn how to: - Use `asyncio` - Use `aiohttp` calls - Send an API Request - Use Results from API Request - Use async within Omniverse # Prerequisites We recommend that you complete these tutorials before moving forward: - [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial) - [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims) - [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_window/tutorial/tutorial.md) # Step 1: Create an Extension > **Note:** This is a review, if you know how to create an extension, feel free to skip this step. For this guide, we will briefly go over how to create an extension. If you have not completed [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) we recommend you pause here and complete that before moving forward. ## Step 1.1: Create the extension template In Omniverse Code navigate to the `Extensions` tab and create a new extension by clicking the ➕ icon in the upper left corner and select `New Extension Template Project`. Name the project to `kit-ext-apiconnect` and the extension name to `my.api.connect`. ![](./images/ext_tab.png) > **Note:** If you don't see the *Extensions* Window, enable **Window > Extensions**: > > ![Show the Extensions panel](images/window_extensions.png) <icon> | <new template> :-------------------------:|:-------------------------: ![icon](./images/icon_create.png "Plus Icon") | ![new template](./images/new_template.png "New Extension Template") A new extension template window and Visual Studio Code will open after you have selected the folder location, folder name, and extension ID. ## Step 1.2: Naming your extension Before beginning to code, navigate into `VS Code` and change how the extension is viewed in the **Extension Manager**. It's important to give your extension a title and description for the end user to understand the extension's purpose. Inside of the `config` folder, locate the `extension.toml` file: > **Note:** `extension.toml` is located inside of the `exts` folder you created for your extension. ![](./images/fileStructTOML.PNG) Inside of this file, there is a title and description for how the extension will look in the **Extension Manager**. Change the title and description for the extension. ``` python title = "API Connection" description="Example on how to make an API response in Omniverse" ``` # Step 2: Set Up Window All coding will be contained within `extension.py`. Before setting up the API request, the first step is to get a window. The UI contained in the window will have a button to call the API and color widgets whose values will be updated based on the API's response. ## Step 2.1: Replace with Boilerplate Code With *VS Code* open, **go to** `extension.py` and replace all the code inside with the following: ```python import omni.ext import omni.ui as ui # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None ``` If you were to save `extension.py` it would throw an error since we have not defined `APIWindowExample`. This step is to setup a starting point for which our window can be created and destroyed when starting up or shutting down the extension. `APIWindowExample` will be the class we work on throughout the rest of the tutorial. ## Step 2.2: Create `APIWindowExample` class At the bottom of `extension.py`, **create** a new class called `APIWindowExample()` ```python class APIWindowExample(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) ``` Save `extension.py` and go back to Omniverse. Right now, the Window should only have a label. ![](./images/step2-2.png) ## Step 2.3: Add Color Widgets Color Widgets are buttons that display a color and can open a picker window. In `extension.py`, **add** the following code block under `ui.Label()`: ```python with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] #create a button to trigger the api call self.button = ui.Button("Refresh") ``` Make sure `with ui.HStack()` is at the same indentation as `ui.Label()`. Here we create a Horizontal Stack that will contain 5 Color Widgets. Below that will be a button labeled Refresh. **Save** `extension.py` and go back to Omniverse. The Window will now have 5 white boxes. When hovered it will show the color values and when clicked on it will open a color picker window. ![](./images/step2-3.gif) After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] #create a button to trigger the api call self.button = ui.Button("Refresh") ``` # Step 3: Create API Request To make an API Request we use the `aiohttp` library. This comes packaged in the Python environment with Omniverse. We use the `asyncio` library as well to avoid the user interface freezing when there are very expensive Python operations. Async is a single threaded / single process design because it's using cooperative multitasking. ## Step 3.1: Create a Task 1. **Add** `import asyncio` at the top of `extension.py`. 2. In `APIWindowExample` class, **add** the following function: ```python #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): print("a") await asyncio.sleep(1) print("b") ``` This function contains the keyword `async` in front, meaning we cannot call it statically. To call this function we first need to grab the current event loop. 3. Before `ui.Label()` **add** the following line: - `run_loop = asyncio.get_event_loop()` Now we can use the event loop to create a task that runs concurrently. 4. Before `self.button`, **add** the following block of code: ```python def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) ``` `create_task` takes a coroutine, where coroutine is an object with the keyword async. 5. To connect it together **add** the following parameter in `self.button`: - `clicked_fn=on_click` After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): print("a") await asyncio.sleep(1) print("b") def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. Now when we click on the Refresh button, in the Console tab it will print 'a' and after one second it will print 'b'. ![](./images/step3-1.gif) ## Step 3.2: Make API Request To **create** the API Request, we first need to create an `aiohttp` session. 1. Add `import aiohttp` at the top of `extension.py`. 2. In `get_colors_from_api()` remove: ```python print("a") await asyncio.sleep(1) print("b") ``` and **add** the following: - `async with aiohttp.ClientSession() as session:` With the session created, we can build the URL and data to send to the API. For this example we are using the [HueMint.com](https://huemint.com/) API. 3. Under `aiohttp.ClientSession()`, **add** the following block of code: ```python url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } ``` > **Note:** If you are using a different URL make sure the data passed is correct. 4. Based on HueMint.com we will create a POST request. **Add** the following code block under `data`: ```python try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] print(palette) except Exception as e: import carb carb.log_info(f"Caught Exception {e}") ``` The `try / except` is used to catch when a Timeout occurs. To read more about Timeouts see [aiohttp Client Quick Start](https://docs.aiohttp.org/en/latest/client_quickstart.html). After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio import aiohttp # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): async with aiohttp.ClientSession() as session: url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] print(palette) except Exception as e: import carb carb.log_info(f"Caught Exception {e}") def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. When clicking on the Refresh button our Extension will now call the API, grab the JSON response, and store it in `palette`. We can see the value for `palette` in the Console Tab. ![](./images/step3-3.gif) # Step 4: Apply Results Now that the API call is returning a response, we can now take that response and apply it to our color widgets in the Window. ## Step 4.1: Setup `apply_colors()` To apply the colors received from the API, **create** the following two functions inside of `APIWindowExample`: ```python #apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): colors = [palette[i] for i in range(5)] index = 0 for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() #we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) #we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 #hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): #Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#' ``` In Kit there is a special awaitable: `await omni.kit.app.get_app().next_update_async()` - This waits for the next frame within Omniverse to run. It is used when you want to execute something with a one-frame delay. - Why do we need this? - Without this, running Python code that is expensive can cause the user interface to freeze ## Step 4.2: Link it together Inside `get_colors_from_api()` **replace** `print()` with the following line: - `await self.apply_colors(palette, color_widgets)` After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio import aiohttp # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): async with aiohttp.ClientSession() as session: url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] await self.apply_colors(palette, color_widgets) except Exception as e: import carb carb.log_info(f"Caught Exception {e}") #apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): colors = [palette[i] for i in range(5)] index = 0 for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() #we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) #we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 #hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): #Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#' def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. When clicking on the Refresh button our color widgets in the window will now update based on the results given by the API response. ![](./images/step4-2.gif) # Step 5: Visualize Progression Some API responses might not be as quick to return a result. Visual indicators can be added to indicate to the user that the extension is waiting for an API response. Examples can be loading bars, spinning circles, percent numbers, etc. For this example, we are going to change "Refresh" to "Loading" and as time goes on it will add up to three periods after Loading before resetting. How it looks when cycling: - Loading - Loading. - Loading.. - Loading... - Loading ## Step 5.1: Run Forever Task Using `async`, we can create as many tasks to run concurrently. One task so far is making a request to the API and our second task will be running the Loading visuals. **Add** the following code block in `APIWindowExample`: ```python async def run_forever(self): count = 0 dot_count = 0 while True: if count % 10 == 0: if dot_count == 3: self.button.text = "Loading" dot_count = 0 else: self.button.text += "." dot_count += 1 count += 1 await omni.kit.app.get_app().next_update_async() ``` > **Note:** This function will run forever. When creating coroutines make sure there is a way to end the process or cancel it to prevent it from running the entire time. Again we use `next_update_async()` to prevent the user interface from freezing. ## Step 5.2: Cancelling Tasks As noted before this coroutine runs forever so after we apply the colors we will cancel that task to stop it from running. 1. At the front of `get_colors_from_api()` **add** the following lines: ```python self.button.text = "Loading" task = asyncio.create_task(self.run_forever()) ``` To cancel a task we need a reference to the task that was created. 2. In `get_colors_from_api()` and after `await self.apply_colors()` **add** the following lines: ```python task.cancel() self.button.text = "Refresh" ``` 3. After `carb.log_info()`, **add** the following lines: ```python task.cancel() self.button.text = "Connection Timed Out \nClick to Retry" ``` After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio import aiohttp # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): self.button.text = "Loading" task = asyncio.create_task(self.run_forever()) async with aiohttp.ClientSession() as session: url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] await self.apply_colors(palette, color_widgets) task.cancel() self.button.text = "Refresh" except Exception as e: import carb carb.log_info(f"Caught Exception {e}") task.cancel() self.button.text = "Connection Timed Out \nClick to Retry" #apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): colors = [palette[i] for i in range(5)] index = 0 for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() #we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) #we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 async def run_forever(self): count = 0 dot_count = 0 while True: if count % 10 == 0: if dot_count == 3: self.button.text = "Loading" dot_count = 0 else: self.button.text += "." dot_count += 1 count += 1 await omni.kit.app.get_app().next_update_async() #hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): #Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#' def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. Clicking the Refresh Button now will display a visual progression to let the user know that the program is running. Once the program is done the button will revert back to displaying "Refresh" instead of "Loading". ![](./images/step5-2.gif)
30,812
Markdown
41.618257
338
0.642315
NVIDIA-Omniverse/kit-extension-sample-reticle/README.md
# Viewport Reticle Kit Extension Sample ## [Viewport Reticle (omni.example.reticle)](exts/omni.example.reticle) ![Camera Reticle Preview](exts/omni.example.reticle/data/preview.png) ### About This extension shows how to build a viewport reticle extension. The focus of this sample extension is to show how to use omni.ui.scene to draw additional graphical primitives on the viewport. ### [README](exts/omni.example.reticle) See the [README for this extension](exts/omni.example.reticle) to learn more about it including how to use it. ### [Tutorial](tutorial/tutorial.md) Follow a [step-by-step tutorial](tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## Adding This Extension To add this extension to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-reticle?branch=main&dir=exts` ## Linking with an Omniverse app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app code ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3" ``` ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
1,757
Markdown
36.404255
193
0.759818
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
NVIDIA-Omniverse/kit-extension-sample-reticle/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
NVIDIA-Omniverse/kit-extension-sample-reticle/tutorial/tutorial.md
![NVIDIA Omniverse Logo](images/logo.png) # Create a Reusable Reticle with Omniverse Kit Extensions Camera [reticles](https://en.wikipedia.org/wiki/Reticle) are patterns and lines you use to line up a camera to a scene. In this tutorial, you learn how to make a reticle extension. You'll test it in Omniverse Code, but it can be used in any Omniverse Application. ## Learning Objectives In this guide, you learn how to: * Create an Omniverse Extension * Include your Extension in Omniverse Code * Draw a line on top of the [viewport](https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_viewport.html) * Divide the viewport with multiple lines * Create a crosshair and letterboxes ## Prerequisites Before you begin, install [Omniverse Code](https://docs.omniverse.nvidia.com/app_code/app_code/overview.html) version 2022.1.2 or higher. We recommend that you understand the concepts in the following tutorial before proceeding: * [How to make an extension by spawning primitives](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) ## Step 1: Familiarize Yourself with the Starter Project In this section, you download and familiarize yourself with the starter project you use throughout this tutorial. ### Step 1.1: Clone the Repository Clone the `tutorial-start` branch of the `kit-extension-sample-reticle` [github repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-reticle/tree/tutorial-start): ```shell git clone -b tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-reticle.git ``` This repository contains the assets you use in this tutorial ### Step 1.2: Navigate to `views.py` From the root directory of the project, navigate to `exts/omni.example.reticle/omni/example/reticle/views.py`. ### Step 1.3: Familiarize Yourself with `build_viewport_overlay()` In `views.py`, navigate to `build_viewport_overlay()`: ```python def build_viewport_overlay(self, *args): """Build all viewport graphics and ReticleMenu button.""" if self.vp_win is not None: self.vp_win.frame.clear() with self.vp_win.frame: with ui.ZStack(): # Set the aspect ratio policy depending if the viewport is wider than it is taller or vice versa. if self.vp_win.width / self.vp_win.height > self.get_aspect_ratio_flip_threshold(): self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL) else: self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL) # Build all the scene view guidelines with self.scene_view.scene: if self.model.composition_mode.as_int == CompositionGuidelines.THIRDS: self._build_thirds() elif self.model.composition_mode.as_int == CompositionGuidelines.QUAD: self._build_quad() elif self.model.composition_mode.as_int == CompositionGuidelines.CROSSHAIR: self._build_crosshair() if self.model.action_safe_enabled.as_bool: self._build_safe_rect(self.model.action_safe_percentage.as_float / 100.0, color=cl.action_safe_default) if self.model.title_safe_enabled.as_bool: self._build_safe_rect(self.model.title_safe_percentage.as_float / 100.0, color=cl.title_safe_default) if self.model.custom_safe_enabled.as_bool: self._build_safe_rect(self.model.custom_safe_percentage.as_float / 100.0, color=cl.custom_safe_default) if self.model.letterbox_enabled.as_bool: self._build_letterbox() # Build ReticleMenu button with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() self.reticle_menu = ReticleMenu(self.model) ``` Here, `self.vp_win` is the [viewport](https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_viewport.html) on which you'll build your reticle overlay. If there is no viewport, there's nothing to build on, so execution stops here: ```python if self.vp_win is not None: ``` If there is a viewport, you create a clean slate by calling [`clear()`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Container.clear) on the [frame](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Frame): ```python self.vp_win.frame.clear() ``` Next, you create a [ZStack](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Stack): ```python with self.vp_win.frame: with ui.ZStack(): ``` ZStack is a type of [Stack](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Stack) that orders elements along the Z axis (forward and backward from the camera, as opposed to up and down or left and right). After that, you create a [SceneView](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.SceneView), a widget that renders the [Scene](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Scene): ```python if self.vp_win.width / self.vp_win.height > self.get_aspect_ratio_flip_threshold(): self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL) else: self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL) ``` When doing this, you make a calculation to determine what the appropriate `aspect_ratio_policy`, which defines how to handle a [Camera](https://docs.omniverse.nvidia.com/app_create/prod_materials-and-rendering/cameras.html) with an aspect ratio different than the SceneView. The SceneView does not consider non-rendered areas such as [letterboxes](https://en.wikipedia.org/wiki/Letterboxing_(filming)), hence `get_aspect_ratio_flip_threshold()`. Further down in `build_viewport_overlay()`, there are a number of `if` statements: ```python with self.scene_view.scene: if self.model.composition_mode.as_int == CompositionGuidelines.THIRDS: self._build_thirds() elif self.model.composition_mode.as_int == CompositionGuidelines.QUAD: self._build_quad() elif self.model.composition_mode.as_int == CompositionGuidelines.CROSSHAIR: self._build_crosshair() if self.model.action_safe_enabled.as_bool: self._build_safe_rect(self.model.action_safe_percentage.as_float / 100.0, color=cl.action_safe_default) if self.model.title_safe_enabled.as_bool: self._build_safe_rect(self.model.title_safe_percentage.as_float / 100.0, color=cl.title_safe_default) if self.model.custom_safe_enabled.as_bool: self._build_safe_rect(self.model.custom_safe_percentage.as_float / 100.0, color=cl.custom_safe_default) if self.model.letterbox_enabled.as_bool: self._build_letterbox() # Build ReticleMenu button with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() self.reticle_menu = ReticleMenu(self.model) ``` These are the different modes and tools the user can select from the **ReticleMenu**. Throughout this tutorial, you write the logic for the following functions: - `self._build_quad()` - `self._build_thirds()` - `self._build_crosshair()` - `self._build_crosshair()` - `_build_safe_rect()` - `_build_letterbox()` Before you do that, you need to import your custom Extension into Omniverse Code. ## Step 2: Import your Extension into Omniverse Code In order to use and test your Extension, you need to add it to Omniverse Code. > **Important:** Make sure you're using Code version 2022.1.2 or higher. ### Step 2.1: Navigate to the Extensions List In Omniverse Code, navigate to the *Extensions* panel: ![Click the Extensions panel](images/extensions_panel.png) Here, you see a list of Omniverse Extensions that you can activate and use in Code. > **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**: > > ![Show the Extensions panel](images/window_extensions.png) ### Step 2.2: Import your Extension Click the **gear** icon to open *Extension Search Paths*: ![Click the gear icon](images/extension_search_paths.png) In this panel, you can add your custom Extension to the Extensions list. ### Step 2.3: Create a New Search Path Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field: ![New search path](images/new_search_path.png) When you submit your new search path, you should be able to find your extension in the *Extensions* list. Activate it: ![Reticle extensions list](images/reticle_extensions_list.png) Now that your Extension is imported and active, you can make changes to the code and see them in your Application. ## Step 3: Draw a Single Line The first step to building a camera reticle is drawing a line. Once you can do that, you can construct more complex shapes using the line as a foundation. For example, you can split the viewport into thirds or quads using multiple lines. ### Step 3.1: Familiarize Yourself with Some Useful Modules At the top of `views.py`, review the following imported modules: ```py from omni.ui import color as cl from omni.ui import scene ``` - `omni.ui.color` offers color functionality. - [`omni.ui.scene`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html) offers a number of useful classes including [Line](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Line). ### Step 3.2: Draw a Line in `build_viewport_overlay()` In `build_viewport_overlay()`, create a line, providing a start, stop, and color: ```python with self.scene_view.scene: start_point = [0, -1, 0] # [x, y, z] end_point = [0, 1, 0] line_color = cl.white scene.Line(start_point, end_point, color=line_color) ``` In the Code viewport, you'll see the white line: ![Viewport line](images/white_line.png) > **Optional Challenge:** Change the `start_point`, `end_point`, and `line_color` values to see how it renders in Code. ### Step 3.3: Remove the Line Now that you've learned how to use `omni.ui.scene` to draw a line, remove it to prepare your viewport for more meaningful shapes. ## Step 4: Draw Quadrants Now that you know how to draw a line, implement `_build_quad()` to construct four quadrants. In other words, split the view into four zones: ![Break the Viewport into quadrants](images/quad.png) ### Step 4.1: Draw Two Dividers Draw your quadrant dividers in `_build_quad()`: ```python def _build_quad(self): """Build the scene ui graphics for the Quad composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, -1, 0], [0, 1, 0], color=line_color) scene.Line([-aspect_ratio, 0, 0], [aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, -inverse_ratio, 0], [0, inverse_ratio, 0], color=line_color) scene.Line([-1, 0, 0], [1, 0, 0], color=line_color) ``` To divide the viewport into quadrants, you only need two lines, so why are there four lines in this code? Imagine the aspect ratio can grow and shrink in the horizontal direction, but the vertical height is static. That would preserve the vertical aspect ratio as with [scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL). In this case, a vertical position in the viewport is bound between -1 and 1, but the horizontal position bounds are determined by the aspect ratio. Conversely, if your horizontal width bounds are static and the vertical height bounds can change, you would need the inverse of the aspect ratio (`inverse_ratio`). ### Step 4.2: Review Your Change In Omniverse Code, select **Quad** from the **Reticle** menu: ![Select quad](images/select_quad.png) With this option selected, the viewport is divided into quadrants. ## Step 5: Draw Thirds The [Rule of Thirds](https://en.wikipedia.org/wiki/Rule_of_thirds) is a theory in photography that suggests the best way to align elements in an image is like this: ![Break the Viewport into nine zones](images/thirds.png) Like you did in the last section, here you draw a number of lines. This time, though, you use four lines to make nine zones in your viewport. But like before, these lines depend on the [Aspect Ratio Policy](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.AspectRatioPolicy). ### Step 5.1: Draw Four Dividers Draw your dividers in `_build_thirds()`: ```python def _build_thirds(self): """Build the scene ui graphics for the Thirds composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([-0.333 * aspect_ratio, -1, 0], [-0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([0.333 * aspect_ratio, -1, 0], [0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([-aspect_ratio, -0.333, 0], [aspect_ratio, -0.333, 0], color=line_color) scene.Line([-aspect_ratio, 0.333, 0], [aspect_ratio, 0.333, 0], color=line_color) else: scene.Line([-1, -0.333 * inverse_ratio, 0], [1, -0.333 * inverse_ratio, 0], color=line_color) scene.Line([-1, 0.333 * inverse_ratio, 0], [1, 0.333 * inverse_ratio, 0], color=line_color) scene.Line([-0.333, -inverse_ratio, 0], [-0.333, inverse_ratio, 0], color=line_color) scene.Line([0.333, -inverse_ratio, 0], [0.333, inverse_ratio, 0], color=line_color) ``` > **Optional Challenge:** Currently, you call `scene.Line` eight times to draw four lines based on two situations. Optimize this logic so you only call `scene.Line` four times to draw four lines, regardless of the aspect ratio. > > **Hint:** You may need to define new variables. > > <details> > <summary>One Possible Solution</summary> > > is_preserving_aspect_vertical = scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL > > x, y = aspect_ratio, 1 if is_preserving_aspect_vertical else 1, inverse_ratio > x1, x2, y1, y2 = .333 * x, 1 * x, 1 * y, .333 * y > > scene.Line([-x1, -y1, 0], [-x1, y1, 0], color=line_color) > scene.Line([x1, -y1, 0], [x1, y1, 0], color=line_color) > scene.Line([-x2, -y2, 0], [x2, -y2, 0], color=line_color) > scene.Line([-x2, y2, 0], [x2, y2, 0], color=line_color) > </details> ### Step 5.2: Review Your Change In Omniverse Code, select **Thirds** from the **Reticle** menu: ![Select thirds](images/select_thirds.png) With this option selected, the viewport is divided into nine zones. ## Step 6: Draw a Crosshair A crosshair is a type of reticle commonly used in [first-person shooter](https://en.wikipedia.org/wiki/First-person_shooter) games to designate a projectile's expected position. For the purposes of this tutorial, you draw a crosshair at the center of the screen. To do this, you draw four small lines about the center of the viewport, based on the Aspect Ratio Policy. ### Step 6.1: Draw Your Crosshair Draw your crosshair in `_build_crosshair()`: ```python def _build_crosshair(self): """Build the scene ui graphics for the Crosshair composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, 0.05 * aspect_ratio, 0], [0, 0.1 * aspect_ratio, 0], color=line_color) scene.Line([0, -0.05 * aspect_ratio, 0], [0, -0.1 * aspect_ratio, 0], color=line_color) scene.Line([0.05 * aspect_ratio, 0, 0], [0.1 * aspect_ratio, 0, 0], color=line_color) scene.Line([-0.05 * aspect_ratio, 0, 0], [-0.1 * aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, 0.05 * 1, 0], [0, 0.1 * 1, 0], color=line_color) scene.Line([0, -0.05 * 1, 0], [0, -0.1 * 1, 0], color=line_color) scene.Line([0.05 * 1, 0, 0], [0.1 * 1, 0, 0], color=line_color) scene.Line([-0.05 * 1, 0, 0], [-0.1 * 1, 0, 0], color=line_color) scene.Points([[0.00005, 0, 0]], sizes=[2], colors=[line_color]) ``` This implementation is similar to your previous reticles except for the addition of a [point](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Points) at the true center of the crosshair. > **Optional Challenge:** Express the crosshair length as a variable. ### Step 6.2: Review Your Change In Omniverse Code, select **Crosshair** from the **Reticle** menu: ![Select crosshair](images/select_crosshair.png) With this option selected, the viewport shows a centered crosshair. ## Step 7: Draw Safe Area Rectangles Different televisions or monitors may display video in different ways, cutting off the edges. To account for this, producers use [Safe Areas](https://en.wikipedia.org/wiki/Safe_area_(television)) to make sure text and graphics are rendered nicely regardless of the viewer's hardware. In this section, you implement three rectangles: - **Title Safe:** This helps align text so that it's not too close to the edge of the screen. - **Action Safe:** This helps align graphics such as news tickers and logos. - **Custom Safe:** This helps the user define their own alignment rectangle. ### Step 7.1: Draw Your Rectangle Draw your safe [rectangle](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Rectangle) in `_build_safe_rect()`: ```python def _build_safe_rect(self, percentage, color): """Build the scene ui graphics for the safe area rectangle Args: percentage (float): The 0-1 percentage the render target that the rectangle should fill. color: The color to draw the rectangle wireframe with. """ aspect_ratio = self.get_aspect_ratio() inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Rectangle(aspect_ratio*2*percentage, 1*2*percentage, thickness=1, wireframe=True, color=color) else: scene.Rectangle(1*2*percentage, inverse_ratio*2*percentage, thickness=1, wireframe=True, color=color) ``` Like before, you draw two different rectangles based on how the aspect is preserved. You draw them from the center after defining the width and height. Since the center is at `[0, 0, 0]` and either the horizontal or vertical axis goes from -1 to 1 (as opposed to from 0 to 1), you multiply the width and height by two. ### Step 7.2: Review Your Change In Omniverse Code, select your **Safe Areas** from the **Reticle** menu: ![Select safe areas](images/select_safe_areas.png) With these option selected, the viewport shows your safe areas. ## Step 8: Draw Letterboxes [Letterboxes](https://en.wikipedia.org/wiki/Letterboxing_(filming)) are large rectangles (typically black), on the edges of a screen used to help fit an image or a movie constructed with one aspect ratio into another. It can also be used for dramatic effect to give something a more theatrical look. ### Step 8.1 Draw Your Letterbox Helper Write a function to draw and place a [rectangle](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Rectangle): ```python def _build_letterbox(self): def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) ``` The [scene.Matrix44.get_translation_matrix](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Matrix44.get_translation_matrix) creates a 4x4 matrix that can be multiplied with a point to offset it by an x, y, or z amount. Since you don't need to move your rectangles toward or away from the camera, the z value is 0. > **Further Reading:** To learn more about the math behind this operation, please check out [this article](https://medium.com/swlh/understanding-3d-matrix-transforms-with-pixijs-c76da3f8bd8). `build_letterbox_helper()` first defines the coordinates of where you expect to rectangle to be placed with `move`. Then, it creates a rectangle with that [transform](https://medium.com/swlh/understanding-3d-matrix-transforms-with-pixijs-c76da3f8bd8). Finally, it repeats the same steps to place and create a rectangle in the opposite direction of the first. Now that you have your helper function, you it to construct your letterboxes. ### Step 8.2: Review Your Potential Aspect Ratios Consider the following situations: ![Letterbox ratio diagram](images/letterbox_ratio.png) In this case, the viewport height is static, but the horizontal width can change. Additionally, the letterbox ratio is larger than the aspect ratio, meaning the rendered area is just as wide as the viewport, but not as tall. Next, write your logic to handle this case. ### Step 8.3: Build Your First Letterbox Build your letterbox to handle the case you analyzed in the last step: ```python def _build_letterbox(self): """Build the scene ui graphics for the letterbox.""" aspect_ratio = self.get_aspect_ratio() letterbox_color = cl.letterbox_default letterbox_ratio = self.model.letterbox_ratio.as_float def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: if letterbox_ratio >= aspect_ratio: height = 1 - aspect_ratio / letterbox_ratio rect_height = height / 2 rect_offset = 1 - rect_height build_letterbox_helper(aspect_ratio, rect_height, 0, rect_offset) ``` Here, you can think of the `height` calculated above as the percentage of the viewport height to be covered by the letterboxes. If the `aspect_ratio` is 2 to 1, but the `letterbox_ratio` is 4 to 1, then `aspect_ratio / letterbox_ratio` is .5, meaning the letterboxes will cover half of the height. However, this is split by both the top and bottom letterboxes, so you divide the `height` by 2 to get the rectangle height (`rect_height`), which, with our example above, is .25. Now that you know the height of the rectangle, you need to know where to place it. Thankfully, the vertical height is bound from -1 to 1, and since you're mirroring the letterboxes along both the top and bottom, so you can subtract `rect_height` from the maximum viewport height (1). ### Step 8.4: Build The Other Letterboxes Using math similar to that explained in the last step, write the `_build_letterbox()` logic for the other three cases: ```python def _build_letterbox(self): """Build the scene ui graphics for the letterbox.""" aspect_ratio = self.get_aspect_ratio() letterbox_color = cl.letterbox_default letterbox_ratio = self.model.letterbox_ratio.as_float def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: if letterbox_ratio >= aspect_ratio: height = 1 - aspect_ratio / letterbox_ratio rect_height = height / 2 rect_offset = 1 - rect_height build_letterbox_helper(aspect_ratio, rect_height, 0, rect_offset) else: width = aspect_ratio - letterbox_ratio rect_width = width / 2 rect_offset = aspect_ratio - rect_width build_letterbox_helper(rect_width, 1, rect_offset, 0) else: inverse_ratio = 1 / aspect_ratio if letterbox_ratio >= aspect_ratio: height = inverse_ratio - 1 / letterbox_ratio rect_height = height / 2 rect_offset = inverse_ratio - rect_height build_letterbox_helper(1, rect_height, 0, rect_offset) else: width = (aspect_ratio - letterbox_ratio) * inverse_ratio rect_width = width / 2 rect_offset = 1 - rect_width build_letterbox_helper(rect_width, inverse_ratio, rect_offset, 0) ``` ## 8. Congratulations! Great job completing this tutorial! Interested in improving your skills further? Check out the [Omni.ui.scene Example](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene). ![NVIDIA Omniverse Logo](images/logo.png)
26,738
Markdown
49.546314
621
0.69908
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/config/extension.toml
[package] version = "1.3.1" title = "Example Viewport Reticle" description="An example kit extension of a viewport reticle using omni.ui.scene." authors=["Matias Codesal <[email protected]>"] readme = "docs/README.md" changelog="docs/CHANGELOG.md" repository = "" category = "Rendering" keywords = ["camera", "reticle", "viewport"] preview_image = "data/preview.png" icon = "icons/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.viewport.utility" = {} "omni.ui.scene" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.example.reticle"
654
TOML
26.291666
105
0.724771
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/styles.py
from pathlib import Path import omni.ui as ui from omni.ui import color as cl CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.joinpath("icons") cl.action_safe_default = cl(1.0, 0.0, 0.0) cl.title_safe_default = cl(1.0, 1.0, 0.0) cl.custom_safe_default = cl(0.0, 1.0, 0.0) cl.letterbox_default = cl(0.0, 0.0, 0.0, 0.75) cl.comp_lines_default = cl(1.0, 1.0, 1.0, 0.6) safe_areas_group_style = { "Label:disabled": { "color": cl(1.0, 1.0, 1.0, 0.2) }, "FloatSlider:enabled": { "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl(0.75, 0.75, 0.75, 1), "color": cl.black }, "FloatSlider:disabled": { "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl(0.75, 0.75, 0.75, 0.2), "color": cl(0.0, 0.0, 1.0, 0.2) }, "CheckBox": { "background_color": cl(0.75, 0.75, 0.75, 1), "color": cl.black }, "Rectangle::ActionSwatch": { "background_color": cl.action_safe_default }, "Rectangle::TitleSwatch": { "background_color": cl.title_safe_default }, "Rectangle::CustomSwatch": { "background_color": cl.custom_safe_default } } comp_group_style = { "Button.Image::Off": { "image_url": str(ICON_PATH / "off.png") }, "Button.Image::Thirds": { "image_url": str(ICON_PATH / "thirds.png") }, "Button.Image::Quad": { "image_url": str(ICON_PATH / "quad.png") }, "Button.Image::Crosshair": { "image_url": str(ICON_PATH / "crosshair.png") }, "Button:checked": { "background_color": cl(1.0, 1.0, 1.0, 0.2) } }
1,688
Python
26.688524
63
0.560427
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/constants.py
"""Constants used by the CameraReticleExtension""" import enum class CompositionGuidelines(enum.IntEnum): """Enum representing all of the composition modes.""" OFF = 0 THIRDS = 1 QUAD = 2 CROSSHAIR = 3 DEFAULT_ACTION_SAFE_PERCENTAGE = 93 DEFAULT_TITLE_SAFE_PERCENTAGE = 90 DEFAULT_CUSTOM_SAFE_PERCENTAGE = 85 DEFAULT_LETTERBOX_RATIO = 2.35 DEFAULT_COMPOSITION_MODE = CompositionGuidelines.OFF SETTING_RESOLUTION_WIDTH = "/app/renderer/resolution/width" SETTING_RESOLUTION_HEIGHT = "/app/renderer/resolution/height" SETTING_RESOLUTION_FILL = "/app/runLoops/rendering_0/fillResolution"
609
Python
26.727272
68
0.760263
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/extension.py
import carb import omni.ext from omni.kit.viewport.utility import get_active_viewport_window from . import constants from .models import ReticleModel from .views import ReticleOverlay class ExampleViewportReticleExtension(omni.ext.IExt): def on_startup(self, ext_id): carb.log_info("[omni.example.reticle] ExampleViewportReticleExtension startup") # Reticle should ideally be used with "Fill Viewport" turned off. settings = carb.settings.get_settings() settings.set(constants.SETTING_RESOLUTION_FILL, False) viewport_window = get_active_viewport_window() if viewport_window is not None: reticle_model = ReticleModel() self.reticle = ReticleOverlay(reticle_model, viewport_window, ext_id) self.reticle.build_viewport_overlay() def on_shutdown(self): """ Executed when the extension is disabled.""" carb.log_info("[omni.example.reticle] ExampleViewportReticleExtension shutdown") self.reticle.destroy()
1,025
Python
34.379309
88
0.709268
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/__init__.py
from .extension import ExampleViewportReticleExtension
55
Python
26.999987
54
0.909091
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/models.py
"""Models used by the CameraReticleExtension""" import omni.ui as ui from . import constants class ReticleModel: """Model containing all of the data used by the ReticleOverlay and ReticleMenu The ReticleOverlay and ReticleMenu classes need to share the same data and stay in sync with updates from user input. This is achieve by passing the same ReticleModel object to both classes. """ def __init__(self): self.composition_mode = ui.SimpleIntModel(constants.DEFAULT_COMPOSITION_MODE) self.action_safe_enabled = ui.SimpleBoolModel(False) self.action_safe_percentage = ui.SimpleFloatModel(constants.DEFAULT_ACTION_SAFE_PERCENTAGE, min=0, max=100) self.title_safe_enabled = ui.SimpleBoolModel(False) self.title_safe_percentage = ui.SimpleFloatModel(constants.DEFAULT_TITLE_SAFE_PERCENTAGE, min=0, max=100) self.custom_safe_enabled = ui.SimpleBoolModel(False) self.custom_safe_percentage = ui.SimpleFloatModel(constants.DEFAULT_CUSTOM_SAFE_PERCENTAGE, min=0, max=100) self.letterbox_enabled = ui.SimpleBoolModel(False) self.letterbox_ratio = ui.SimpleFloatModel(constants.DEFAULT_LETTERBOX_RATIO, min=0.001) self._register_submodel_callbacks() self._callbacks = [] def _register_submodel_callbacks(self): """Register to listen to when any submodel values change.""" self.composition_mode.add_value_changed_fn(self._reticle_changed) self.action_safe_enabled.add_value_changed_fn(self._reticle_changed) self.action_safe_percentage.add_value_changed_fn(self._reticle_changed) self.title_safe_enabled.add_value_changed_fn(self._reticle_changed) self.title_safe_percentage.add_value_changed_fn(self._reticle_changed) self.custom_safe_enabled.add_value_changed_fn(self._reticle_changed) self.custom_safe_percentage.add_value_changed_fn(self._reticle_changed) self.letterbox_enabled.add_value_changed_fn(self._reticle_changed) self.letterbox_ratio.add_value_changed_fn(self._reticle_changed) def _reticle_changed(self, model): """Executes all registered callbacks of this model. Args: model (Any): The submodel that has changed. [Unused] """ for callback in self._callbacks: callback() def add_reticle_changed_fn(self, callback): """Add a callback to be executed whenever any ReticleModel submodel data changes. This is useful for rebuilding the overlay whenever any data changes. Args: callback (function): The function to call when the reticle model changes. """ self._callbacks.append(callback)
2,712
Python
44.98305
115
0.703171
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/views.py
from functools import partial import carb import omni.ui as ui from omni.ui import color as cl from omni.ui import scene from . import constants from .constants import CompositionGuidelines from .models import ReticleModel from . import styles class ReticleOverlay: """The reticle viewport overlay. Build the reticle graphics and ReticleMenu button on the given viewport window. """ _instances = [] def __init__(self, model: ReticleModel, vp_win: ui.Window, ext_id: str): """ReticleOverlay constructor Args: model (ReticleModel): The reticle model vp_win (Window): The viewport window to build the overlay on. ext_id (str): The extension id. """ self.model = model self.vp_win = vp_win self.ext_id = ext_id # Rebuild the overlay whenever the viewport window changes self.vp_win.set_height_changed_fn(self.on_window_changed) self.vp_win.set_width_changed_fn(self.on_window_changed) self._view_change_sub = None try: # VP2 resolution change sub self._view_change_sub = self.vp_win.viewport_api.subscribe_to_view_change(self.on_window_changed) except AttributeError: carb.log_info("Using Viewport Legacy: Reticle will not automatically update on resolution changes.") # Rebuild the overlay whenever the model changes self.model.add_reticle_changed_fn(self.build_viewport_overlay) ReticleOverlay._instances.append(self) resolution = self.vp_win.viewport_api.get_texture_resolution() self._aspect_ratio = resolution[0] / resolution[1] @classmethod def get_instances(cls): """Get all created instances of ReticleOverlay""" return cls._instances def __del__(self): self.destroy() def destroy(self): self._view_change_sub = None self.scene_view.scene.clear() self.scene_view = None self.reticle_menu.destroy() self.reticle_menu = None self.vp_win = None def on_window_changed(self, *args): """Update aspect ratio and rebuild overlay when viewport window changes.""" if self.vp_win is None: return settings = carb.settings.get_settings() if type(self.vp_win).__name__ == "LegacyViewportWindow": fill = settings.get(constants.SETTING_RESOLUTION_FILL) else: fill = self.vp_win.viewport_api.fill_frame if fill: width = self.vp_win.frame.computed_width + 8 height = self.vp_win.height else: width, height = self.vp_win.viewport_api.resolution self._aspect_ratio = width / height self.build_viewport_overlay() def get_aspect_ratio_flip_threshold(self): """Get magic number for aspect ratio policy. Aspect ratio policy doesn't seem to swap exactly when window_aspect_ratio == window_texture_aspect_ratio. This is a hack that approximates where the policy changes. """ return self.get_aspect_ratio() - self.get_aspect_ratio() * 0.05 def build_viewport_overlay(self, *args): """Build all viewport graphics and ReticleMenu button.""" if self.vp_win is not None: # Create a unique frame for our overlay with self.vp_win.get_frame(self.ext_id): with ui.ZStack(): # Set the aspect ratio policy depending if the viewport is wider than it is taller or vice versa. if self.vp_win.width / self.vp_win.height > self.get_aspect_ratio_flip_threshold(): self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL) else: self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL) # Build all the scene view guidelines with self.scene_view.scene: if self.model.composition_mode.as_int == CompositionGuidelines.THIRDS: self._build_thirds() elif self.model.composition_mode.as_int == CompositionGuidelines.QUAD: self._build_quad() elif self.model.composition_mode.as_int == CompositionGuidelines.CROSSHAIR: self._build_crosshair() if self.model.action_safe_enabled.as_bool: self._build_safe_rect(self.model.action_safe_percentage.as_float / 100.0, color=cl.action_safe_default) if self.model.title_safe_enabled.as_bool: self._build_safe_rect(self.model.title_safe_percentage.as_float / 100.0, color=cl.title_safe_default) if self.model.custom_safe_enabled.as_bool: self._build_safe_rect(self.model.custom_safe_percentage.as_float / 100.0, color=cl.custom_safe_default) if self.model.letterbox_enabled.as_bool: self._build_letterbox() # Build ReticleMenu button with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() self.reticle_menu = ReticleMenu(self.model) def _build_thirds(self): """Build the scene ui graphics for the Thirds composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([-0.333 * aspect_ratio, -1, 0], [-0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([0.333 * aspect_ratio, -1, 0], [0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([-aspect_ratio, -0.333, 0], [aspect_ratio, -0.333, 0], color=line_color) scene.Line([-aspect_ratio, 0.333, 0], [aspect_ratio, 0.333, 0], color=line_color) else: scene.Line([-1, -0.333 * inverse_ratio, 0], [1, -0.333 * inverse_ratio, 0], color=line_color) scene.Line([-1, 0.333 * inverse_ratio, 0], [1, 0.333 * inverse_ratio, 0], color=line_color) scene.Line([-0.333, -inverse_ratio, 0], [-0.333, inverse_ratio, 0], color=line_color) scene.Line([0.333, -inverse_ratio, 0], [0.333, inverse_ratio, 0], color=line_color) def _build_quad(self): """Build the scene ui graphics for the Quad composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, -1, 0], [0, 1, 0], color=line_color) scene.Line([-aspect_ratio, 0, 0], [aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, -inverse_ratio, 0], [0, inverse_ratio, 0], color=line_color) scene.Line([-1, 0, 0], [1, 0, 0], color=line_color) def _build_crosshair(self): """Build the scene ui graphics for the Crosshair composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, 0.05 * aspect_ratio, 0], [0, 0.1 * aspect_ratio, 0], color=line_color) scene.Line([0, -0.05 * aspect_ratio, 0], [0, -0.1 * aspect_ratio, 0], color=line_color) scene.Line([0.05 * aspect_ratio, 0, 0], [0.1 * aspect_ratio, 0, 0], color=line_color) scene.Line([-0.05 * aspect_ratio, 0, 0], [-0.1 * aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, 0.05 * 1, 0], [0, 0.1 * 1, 0], color=line_color) scene.Line([0, -0.05 * 1, 0], [0, -0.1 * 1, 0], color=line_color) scene.Line([0.05 * 1, 0, 0], [0.1 * 1, 0, 0], color=line_color) scene.Line([-0.05 * 1, 0, 0], [-0.1 * 1, 0, 0], color=line_color) scene.Points([[0.00005, 0, 0]], sizes=[2], colors=[line_color]) def _build_safe_rect(self, percentage, color): """Build the scene ui graphics for the safe area rectangle Args: percentage (float): The 0-1 percentage the render target that the rectangle should fill. color: The color to draw the rectangle wireframe with. """ aspect_ratio = self.get_aspect_ratio() inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Rectangle(aspect_ratio*2*percentage, 1*2*percentage, thickness=1, wireframe=True, color=color) else: scene.Rectangle(1*2*percentage, inverse_ratio*2*percentage, thickness=1, wireframe=True, color=color) def _build_letterbox(self): """Build the scene ui graphics for the letterbox.""" aspect_ratio = self.get_aspect_ratio() letterbox_color = cl.letterbox_default letterbox_ratio = self.model.letterbox_ratio.as_float def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: if letterbox_ratio >= aspect_ratio: height = 1 - aspect_ratio / letterbox_ratio rect_height = height / 2 rect_offset = 1 - rect_height build_letterbox_helper(aspect_ratio, rect_height, 0, rect_offset) else: width = aspect_ratio - letterbox_ratio rect_width = width / 2 rect_offset = aspect_ratio - rect_width build_letterbox_helper(rect_width, 1, rect_offset, 0) else: inverse_ratio = 1 / aspect_ratio if letterbox_ratio >= aspect_ratio: height = inverse_ratio - 1 / letterbox_ratio rect_height = height / 2 rect_offset = inverse_ratio - rect_height build_letterbox_helper(1, rect_height, 0, rect_offset) else: width = (aspect_ratio - letterbox_ratio) * inverse_ratio rect_width = width / 2 rect_offset = 1 - rect_width build_letterbox_helper(rect_width, inverse_ratio, rect_offset, 0) def get_aspect_ratio(self): """Get the aspect ratio of the viewport. Returns: float: The viewport aspect ratio. """ return self._aspect_ratio class ReticleMenu: """The popup reticle menu""" def __init__(self, model: ReticleModel): """ReticleMenu constructor Stores the model and builds the Reticle button. Args: model (ReticleModel): The reticle model """ self.model = model self.button = ui.Button("Reticle", width=0, height=0, mouse_pressed_fn=self.show_reticle_menu, style={"margin": 10, "padding": 5, "color": cl.white}) self.reticle_menu = None def destroy(self): self.button.destroy() self.button = None self.reticle_menu = None def on_group_check_changed(self, safe_area_group, model): """Enables/disables safe area groups When a safe area checkbox state changes, all the widgets of the respective group should be enabled/disabled. Args: safe_area_group (HStack): The safe area group to enable/disable model (SimpleBoolModel): The safe group checkbox model. """ safe_area_group.enabled = model.as_bool def on_composition_mode_changed(self, guideline_type): """Sets the selected composition mode. When a composition button is clicked, it should be checked on and the other buttons should be checked off. Sets the composition mode on the ReticleModel too. Args: guideline_type (_type_): _description_ """ self.model.composition_mode.set_value(guideline_type) self.comp_off_button.checked = guideline_type == CompositionGuidelines.OFF self.comp_thirds_button.checked = guideline_type == CompositionGuidelines.THIRDS self.comp_quad_button.checked = guideline_type == CompositionGuidelines.QUAD self.comp_crosshair_button.checked = guideline_type == CompositionGuidelines.CROSSHAIR def show_reticle_menu(self, x, y, button, modifier): """Build and show the reticle menu popup.""" self.reticle_menu = ui.Menu("Reticle", width=400, height=200) self.reticle_menu.clear() with self.reticle_menu: with ui.Frame(width=0, height=100): with ui.HStack(): with ui.VStack(): ui.Label("Composition", alignment=ui.Alignment.LEFT, height=30) with ui.VGrid(style=styles.comp_group_style, width=150, height=0, column_count=2, row_height=75): current_comp_mode = self.model.composition_mode.as_int with ui.HStack(): off_checked = current_comp_mode == CompositionGuidelines.OFF callback = partial(self.on_composition_mode_changed, CompositionGuidelines.OFF) self.comp_off_button = ui.Button("Off", name="Off", checked=off_checked, width=70, height=70, clicked_fn=callback) with ui.HStack(): thirds_checked = current_comp_mode == CompositionGuidelines.THIRDS callback = partial(self.on_composition_mode_changed, CompositionGuidelines.THIRDS) self.comp_thirds_button = ui.Button("Thirds", name="Thirds", checked=thirds_checked, width=70, height=70, clicked_fn=callback) with ui.HStack(): quad_checked = current_comp_mode == CompositionGuidelines.QUAD callback = partial(self.on_composition_mode_changed, CompositionGuidelines.QUAD) self.comp_quad_button = ui.Button("Quad", name="Quad", checked=quad_checked, width=70, height=70, clicked_fn=callback) with ui.HStack(): crosshair_checked = current_comp_mode == CompositionGuidelines.CROSSHAIR callback = partial(self.on_composition_mode_changed, CompositionGuidelines.CROSSHAIR) self.comp_crosshair_button = ui.Button("Crosshair", name="Crosshair", checked=crosshair_checked, width=70, height=70, clicked_fn=callback) ui.Spacer(width=10) with ui.VStack(style=styles.safe_areas_group_style): ui.Label("Safe Areas", alignment=ui.Alignment.LEFT, height=30) with ui.HStack(width=0): ui.Spacer(width=20) cb = ui.CheckBox(model=self.model.action_safe_enabled) action_safe_group = ui.HStack(enabled=self.model.action_safe_enabled.as_bool) callback = partial(self.on_group_check_changed, action_safe_group) cb.model.add_value_changed_fn(callback) with action_safe_group: ui.Spacer(width=10) ui.Label("Action Safe", alignment=ui.Alignment.TOP) ui.Spacer(width=14) with ui.VStack(): ui.FloatSlider(self.model.action_safe_percentage, width=100, format="%.0f%%", min=0, max=100, step=1) ui.Rectangle(name="ActionSwatch", height=5) ui.Spacer() with ui.HStack(width=0): ui.Spacer(width=20) cb = ui.CheckBox(model=self.model.title_safe_enabled) title_safe_group = ui.HStack(enabled=self.model.title_safe_enabled.as_bool) callback = partial(self.on_group_check_changed, title_safe_group) cb.model.add_value_changed_fn(callback) with title_safe_group: ui.Spacer(width=10) ui.Label("Title Safe", alignment=ui.Alignment.TOP) ui.Spacer(width=25) with ui.VStack(): ui.FloatSlider(self.model.title_safe_percentage, width=100, format="%.0f%%", min=0, max=100, step=1) ui.Rectangle(name="TitleSwatch", height=5) ui.Spacer() with ui.HStack(width=0): ui.Spacer(width=20) cb = ui.CheckBox(model=self.model.custom_safe_enabled) custom_safe_group = ui.HStack(enabled=self.model.custom_safe_enabled.as_bool) callback = partial(self.on_group_check_changed, custom_safe_group) cb.model.add_value_changed_fn(callback) with custom_safe_group: ui.Spacer(width=10) ui.Label("Custom Safe", alignment=ui.Alignment.TOP) ui.Spacer(width=5) with ui.VStack(): ui.FloatSlider(self.model.custom_safe_percentage, width=100, format="%.0f%%", min=0, max=100, step=1) ui.Rectangle(name="CustomSwatch", height=5) ui.Spacer() ui.Label("Letterbox", alignment=ui.Alignment.LEFT, height=30) with ui.HStack(width=0): ui.Spacer(width=20) cb = ui.CheckBox(model=self.model.letterbox_enabled) letterbox_group = ui.HStack(enabled=self.model.letterbox_enabled.as_bool) callback = partial(self.on_group_check_changed, letterbox_group) cb.model.add_value_changed_fn(callback) with letterbox_group: ui.Spacer(width=10) ui.Label("Letterbox Ratio", alignment=ui.Alignment.TOP) ui.Spacer(width=5) ui.FloatDrag(self.model.letterbox_ratio, width=35, min=0.001, step=0.01) self.reticle_menu.show_at(x - self.reticle_menu.width, y - self.reticle_menu.height)
20,496
Python
52.939474
129
0.541472
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. ## [Unreleased] ## [1.3.1] - 2022-09-09 ### Changed - Fixed on_window_changed callback for VP2 ## [1.3.0] - 2022-09-09 ### Changed - Fixed bad use of viewport window frame for VP2 - Now using ViewportAPI.subscribe_to_view_change() to update reticle on resolution changes. ## [1.2.0] - 2022-06-24 ### Changed - Refactored to omni.example.reticle - Updated preview.png - Cleaned up READMEs ### Removed - menu.png ## [1.1.0] - 2022-06-22 ### Changed - Refactored reticle.py to views.py - Fixed bug where Viewport Docs was being treated as viewport. - Moved Reticle button to bottom right of viewport to not overlap axes decorator. ### Removed - All mutli-viewport logic. ## [1.0.0] - 2022-05-25 ### Added - Initial add of the Sample Viewport Reticle extension.
846
Markdown
23.199999
91
0.712766
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/docs/README.md
# Viewport Reticle (omni.example.reticle) ![Camera Reticle Preview](../data/preview.png) ## Overview The Viewport Reticle Sample extension adds a new menu button at the bottom, right of the viewport. From this menu, users can enable and configure: 1. Composition Guidelines 2. Safe Area Guidelines 3. Letterbox ## [Tutorial](../../../tutorial/tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. [Get started with the tutorial.](../../../tutorial/tutorial.md) ## Usage ### Composition Guidelines * Click on the **Thirds**, **Quad**, or **Crosshair** button to enable a different composition mode. * Use the guidelines to help frame your shots. Click on the **Off** button to disable the composition guidelines. ### Safe Area Guidelines * Click on the checkbox for the safe area that you are interested in to enable the safe area guidelines. * Use the slider to adjust the area percentage for the respective safe areas. * NOTE: The sliders are disabled if their respective checkbox is unchecked. ### Letterbox * Check on **Letterbox Ratio** to enable the letterbox. * Enter a value or drag on the **Letterbox Ratio** field to adjust the letterbox ratio.
1,263
Markdown
45.814813
146
0.756136
NVIDIA-Omniverse/kit-extension-sample-ui-window/README.md
# omni.ui Kit Extension Samples ## [Generic Window (omni.example.ui_window)](exts/omni.example.ui_window) ![Object Info](exts/omni.example.ui_window/data/preview.png) ### About This extension provides an end-to-end example and general recommendations on creating a simple window using `omni.ui`. It contains the best practices of building an extension, a menu item, a window itself, a custom widget, and a generic style. ### [README](exts/omni.example.ui_window) See the [README for this extension](exts/omni.example.ui_window) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_window/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_window/tutorial/tutorial.md) that walks you through how to use omni.ui to build this extension. ## [Julia Modeler (omni.example.ui_julia_modeler)](exts/omni.example.ui_julia_modeler) ![Julia Modeler](exts/omni.example.ui_julia_modeler/data/preview.png) ### About This extension is an example of a more advanced window with custom styling and custom widgets. Study this example to learn more about applying styles to `omni.ui` widgets and building your own custom widgets. ### [README](exts/omni.example.ui_julia_modeler/) See the [README for this extension](exts/omni.example.ui_julia_modeler/) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_julia_modeler/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_julia_modeler/tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## [Gradient Window (omni.example.ui_gradient_window)](exts/omni.example.ui_gradient_window/) ![Gradient Window](exts/omni.example.ui_gradient_window/data/Preview.png) ### About This extension shows how to build a Window that applys gradient styles to widgets. The focus of this sample extension is to show how to use omni.ui to create gradients with `ImageWithProvider`. ### [README](exts/omni.example.ui_gradient_window/) See the [README for this extension](exts/omni.example.ui_gradient_window/) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_gradient_window/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_gradient_window/tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## Adding These Extensions To add these extensions to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window?branch=main&dir=exts` ## Linking with an Omniverse app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app code ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3" ``` ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
3,432
Markdown
44.773333
208
0.766026
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
NVIDIA-Omniverse/kit-extension-sample-ui-window/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/tutorial/tutorial.md
![](images/logo.png) # Gradient Style Window Tutorial In this tutorial we will cover how we can create a gradient style that will be used in various widgets. This tutorial will cover how to create a gradient image / style that can be applied to UI. ## Learning Objectives - How to use `ImageWithProvider` to create Image Widgets - Create functions to interpolate between colors - Apply custom styles to widgets ## Prerequisites - [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/Tutorial/exts/omni.example.ui_window/tutorial/tutorial.md) - Omniverse Code version 2022.1.2 or higher ## Step 1: Add the Extension ### Step 1.1: Clone the repository Clone the `gradient-tutorial-start` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/gradient-tutorial-start): ```shell git clone -b gradient-tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git ``` This repository contains the assets you use in this tutorial. ### Step 1.2: Open Extension Search Paths Go to *Extension Manager -> Gear Icon -> Extension Search Path*: ![cog](images/extension_search_paths.png#center) ### Step 1.3: Add the Path Create a new search path to the exts directory of your Extension by clicking the green plus icon and double-clicking on the path field: ![search path](images/new_search_path.png#center) When you submit your new search path, you should be able to find your extension in the Extensions list. ### Step 1.4: Enable the Extension ![enable](images/enable%20extension.png#center) After Enabling the extension the following window will appear: <center> ![png1](images/tut-png1.PNG#center) </center> Unlike the main repo, this extension is missing quite a few things that we will need to add, mainly the gradient. Moving forward we will go into detail on how to create the gradient style and apply it to our UI Window. ## Step 2: Familiarize Yourself with Interpolation What is interpolation? [Interpolation](https://en.wikipedia.org/wiki/Interpolation) a way to find or estimate a point based on a range of discrete set of known data points. For our case we interpolate between colors to appropriately set the slider handle color. Let's say the start point is black and our end point is white. What is a color that is in between black and white? Gray is what most would say. Using interpolation we can get more than just gray. Here's a picture representation of what it looks like to interpolate between black and white: ![png2](images/tut-png2.PNG) We can also use blue instead of black. It would then look something like this: ![png3](images/tut-png3.PNG) Interpolation can also be used with a spectrum of colors: ![png4](images/tut-png4.PNG) ## Step 3: Set up the Gradients Hexadecimal (Hex) is a base 16 numbering system where `0-9` represents their base 10 counterparts and `A-F` represent the base 10 values `10-15`. A Hex color is written as `#RRGGBB` where `RR` is red, `GG` is green and `BB` is blue. The hex values have the range `00` - `ff` which is equivalent to `0` - `255` in base 10. So to write the hex value to a color for red it would be: `#ff0000`. This is equivalent to saying `R=255, G=0, B=0`. To flesh out the `hex_to_color` function we will use bit shift operations to convert the hex value to color. ### Step 3.1: Navigate to `style.py` Open the project in VS Code and open the `style.py` file inside of `omni.example.ui_gradient_window\omni\example\ui_gradient_window` > **Tip:** Remember to open up any extension in VS Code by browsing to that extension in the `Extension` tab, then select the extension and click on the VS Code logo. Locate the function `hex_to_color` towards the bottom of the file. There will be other functions that are not yet filled out: ``` python def hex_to_color(hex: int) -> tuple: # YOUR CODE HERE pass def generate_byte_data(colors): # YOUR CODE HERE pass def _interpolate_color(hex_min: int, hex_max: int, intep): # YOUR CODE HERE pass def get_gradient_color(value, max, colors): # YOUR CODE HERE pass def build_gradient_image(colors, height, style_name): # YOUR CODE HERE pass ``` Currently we have the `pass` statement in each of the functions because each function needs at least one statement to run. > **Warning:** Removing the pass in these functions without adding any code will break other features of this extension! ### Step 3.2: Add Red to `hex_to_color` Replace `pass` with `red = hex & 255`: ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 ``` > **Warning:** Don't save yet! We must return a tuple before our function will run. ### Step 3.3: Add Green to `hex_to_color` Underneath where we declared `red`, add the following line `green = (hex >> 8) & 255`: ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 ``` > **Note:** 255 in binary is 0b11111111 (8 set bits) ### Step 3.4: Add the remaining colors to `hex_to_color` Try to fill out the rest of the following code for `blue` and `alpha`: ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = # YOUR CODE alpha = # YOUR CODE rgba_values = [red, green, blue, alpha] return rgba_values ``` <details> <summary>Click for solution</summary> ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = (hex >> 16) & 255 alpha = (hex >> 24) & 255 rgba_values = [red, green, blue, alpha] return rgba_values ``` </details> ## Step 4: Create `generate_byte_data` We will now be filling out the function `generate_byte_data`. This function will take our colors and generate byte data that we can use to make an image using `ImageWithProvider`. Here is the function we will be editing: ``` python def generate_byte_data(colors): # YOUR CODE HERE pass ``` ### Step 4.1: Create an Array for Color Values Replace `pass` with `data = []`. This will contain the color values: ``` python def generate_byte_data(colors): data = [] ``` ### Step 4.2: Loop Through the Colors Next we will loop through all provided colors in hex form to color form and add it to `data`. This will use `hex_to_color` created previously: ``` python def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) ``` ### Step 4.3: Loop Through the Colors Use [ByteImageProvider](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html?highlight=byteimage#omni.ui.ByteImageProvider) to set the sequence as byte data that will be used later to generate the image: ``` python def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) _byte_provider = ui.ByteImageProvider() _byte_provider.set_bytes_data(data [len(colors), 1]) return _byte_provider ``` ## Step 5: Build the Image Now that we have our data we can use it to create our image. ### Step 5.1: Locate `build_gradient_image()` In `style.py`, navigate to `build_gradient_image()`: ``` python def build_gradient_image(colors, height, style_name): # YOUR CODE HERE pass ``` ### Step 5.2: Create Byte Sequence Replace `pass` with `byte_provider = generate_byte_data(colors)`: ``` python def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ``` ### Step 5.3: Transform Bytes into the Gradient Image Use [ImageWithProvider](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html?highlight=byteimage#omni.ui.ImageWithProvider) to transform our sequence of bytes to an image. ``` python def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name) return byte_provider ``` Save `style.py` and take a look at our window. It should look like the following: <center> ![png5](images/tut-png5.PNG) </center> > **Note:** If the extension does not look like the following, close down Code and try to relaunch. ### Step 5.4: How are the Gradients Used? Head over to `color_widget.py`, then scroll to around line 90: ``` python self.color_button_gradient_R = build_gradient_image([cl_attribute_dark, cl_attribute_red], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_G = build_gradient_image([cl_attribute_dark, cl_attribute_green], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_B = build_gradient_image([cl_attribute_dark, cl_attribute_blue], 22, "button_background_gradient") ``` This corresponds to the widgets that look like this: <center> ![png6](images/tut-png6.PNG) </center> ### Step 5.5: Experiment - Change the red to pink Go to `style.py`, locate the pre-defined constants, change `cl_attribute_red`'s value to `cl("#fc03be")` ``` python # Pre-defined constants. It's possible to change them runtime. fl_attr_hspacing = 10 fl_attr_spacing = 1 fl_group_spacing = 5 cl_attribute_dark = cl("#202324") cl_attribute_red = cl("#fc03be") # previously was cl("#ac6060") cl_attribute_green = cl("#60ab7c") cl_attribute_blue = cl("#35889e") cl_line = cl("#404040") cl_text_blue = cl("#5eb3ff") cl_text_gray = cl("#707070") cl_text = cl("#a1a1a1") cl_text_hovered = cl("#ffffff") cl_field_text = cl("#5f5f5f") cl_widget_background = cl("#1f2123") cl_attribute_default = cl("#505050") cl_attribute_changed = cl("#55a5e2") cl_slider = cl("#383b3e") cl_combobox_background = cl("#252525") cl_main_background = cl("#2a2b2c") cls_temperature_gradient = [cl("#fe0a00"), cl("#f4f467"), cl("#a8b9ea"), cl("#2c4fac"), cl("#274483"), cl("#1f334e")] cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")] cls_tint_gradient = [cl("#1D1D92"), cl("#7E7EC9"), cl("#FFFFFF")] cls_grey_gradient = [cl("#020202"), cl("#525252"), cl("#FFFFFF")] cls_button_gradient = [cl("#232323"), cl("#656565")] ``` > **Tip:** Storing colors inside of the style.py file will help with reusing those values for other widgets. The value only has to change in one location, inside of style.py, rather than everywhere that the hex value was hard coded. <center> ![png7](images/tut-png7.PNG) </center> The colors for the sliders can be changed the same way. ## Step 6: Get the Handle of the Slider to Show the Color as it's Moved Currently, the handle on the slider turns to black when interacting with it. <center> ![gif1](images/gif1.gif) </center> This is because we need to let it know what color we are on. This can be a bit tricky since the sliders are simple images. However, using interpolation we can approximate the color we are on. During this step we will be filling out `_interpolate_color` function inside of `style.py`. ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): pass ``` ### Step 6.1: Set the color range Define `max_color` and `min_color`. Then remove `pass`. ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) ``` ### Step 6.2: Calculate the color ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)] ``` ### Step 6.3: Return the interpolated color ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)] return (color[3] << 8 * 3) + (color[2] << 8 * 2) + (color[1] << 8 * 1) + color[0] ``` ## Step 7: Getting the Gradient Color Now that we can interpolate between two colors we can grab the color of the gradient in which the slider is on. To do this we will be using value which is the position of the slider along the gradient image, max being the maximum number the value can be, and a list of all the colors. After calculating the step size between the colors that made up the gradient image, we can then grab the index to point to the appropriate color in our list of colors that our slider is closest to. From that we can interpolate between the first color reference in the list and the next color in the list based on the index. ### Step 7.1: Locate `get_gradient_color` function ``` python def get_gradient_color(value, max, colors): pass ``` ### Step 7.2: Declare `step_size` and `step` ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) ``` ### Step 7.3: Declare `percentage` and `idx` ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) ``` ### Step 7.4: Check to see if our index is equal to our step size, to prevent an Index out of bounds exception ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) if idx == step_size: color = colors[-1] ``` ### Step 7.5: Else interpolate between the current index color and the next color in the list. Return the result afterwards. ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) if idx == step_size: color = colors[-1] else: color = _interpolate_color(colors[idx], colors[idx+1], percentage) return color ``` Save the file and head back into Omniverse to test out the slider. Now when moving the slider it will update to the closest color within the color list. <center> ![gif2](images/gif2.gif) </center> ## Conclusion This was a tutorial about how to create gradient styles in the Window. Check out the complete code in the main branch to see how other styles were created. To learn more about how to create custom widgets check out the [Julia Modeler](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/main/exts/omni.example.ui_julia_modeler) example. As a challenge, try to use the color that gets set by the slider to update something in the scene.
15,265
Markdown
32.849224
356
0.693089
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/config/extension.toml
[package] title = "omni.ui Gradient Window Example" description = "The full end to end example of the window" version = "1.0.1" category = "Example" authors = ["Min Jiang"] repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows" keywords = ["example", "window", "ui"] changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.example.ui_gradient_window" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
710
TOML
22.699999
84
0.676056
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/style.py
# Copyright (c) 2022, 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. # __all__ = ["main_window_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. fl_attr_hspacing = 10 fl_attr_spacing = 1 fl_group_spacing = 5 cl_attribute_dark = cl("#202324") cl_attribute_red = cl("#ac6060") cl_attribute_green = cl("#60ab7c") cl_attribute_blue = cl("#35889e") cl_line = cl("#404040") cl_text_blue = cl("#5eb3ff") cl_text_gray = cl("#707070") cl_text = cl("#a1a1a1") cl_text_hovered = cl("#ffffff") cl_field_text = cl("#5f5f5f") cl_widget_background = cl("#1f2123") cl_attribute_default = cl("#505050") cl_attribute_changed = cl("#55a5e2") cl_slider = cl("#383b3e") cl_combobox_background = cl("#252525") cl_main_background = cl("#2a2b2c") cls_temperature_gradient = [cl("#fe0a00"), cl("#f4f467"), cl("#a8b9ea"), cl("#2c4fac"), cl("#274483"), cl("#1f334e")] cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")] cls_tint_gradient = [cl("#1D1D92"), cl("#7E7EC9"), cl("#FFFFFF")] cls_grey_gradient = [cl("#020202"), cl("#525252"), cl("#FFFFFF")] cls_button_gradient = [cl("#232323"), cl("#656565")] # The main style dict main_window_style = { "Button::add": {"background_color": cl_widget_background}, "Field::add": { "font_size": 14, "color": cl_text}, "Field::search": { "font_size": 16, "color": cl_field_text}, "Field::path": { "font_size": 14, "color": cl_field_text}, "ScrollingFrame::main_frame": {"background_color": cl_main_background}, # for CollapsableFrame "CollapsableFrame::group": { "margin_height": fl_group_spacing, "background_color": 0x0, "secondary_color": 0x0, }, "CollapsableFrame::group:hovered": { "margin_height": fl_group_spacing, "background_color": 0x0, "secondary_color": 0x0, }, # for Secondary CollapsableFrame "Circle::group_circle": { "background_color": cl_line, }, "Line::group_line": {"color": cl_line}, # all the labels "Label::collapsable_name": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text }, "Label::attribute_bool": { "alignment": ui.Alignment.LEFT_BOTTOM, "margin_height": fl_attr_spacing, "margin_width": fl_attr_hspacing, "color": cl_text }, "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_CENTER, "margin_height": fl_attr_spacing, "margin_width": fl_attr_hspacing, "color": cl_text }, "Label::attribute_name:hovered": {"color": cl_text_hovered}, "Label::header_attribute_name": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text }, "Label::details": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text_blue, "font_size": 19, }, "Label::layers": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text_gray, "font_size": 19, }, "Label::attribute_r": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_attribute_red }, "Label::attribute_g": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_attribute_green }, "Label::attribute_b": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_attribute_blue }, # for Gradient Float Slider "Slider::float_slider":{ "background_color": cl_widget_background, "secondary_color": cl_slider, "border_radius": 3, "corner_flag": ui.CornerFlag.ALL, "draw_mode": ui.SliderDrawMode.FILLED, }, # for color slider "Circle::slider_handle":{"background_color": 0x0, "border_width": 2, "border_color": cl_combobox_background}, # for Value Changed Widget "Rectangle::attribute_changed": {"background_color":cl_attribute_changed, "border_radius": 2}, "Rectangle::attribute_default": {"background_color":cl_attribute_default, "border_radius": 1}, # all the images "Image::pin": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/Pin.svg"}, "Image::expansion": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/Details_options.svg"}, "Image::transform": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/offset_dark.svg"}, "Image::link": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/link_active_dark.svg"}, "Image::on_off": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/on_off.svg"}, "Image::header_frame": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/head.png"}, "Image::checked": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/checked.svg"}, "Image::unchecked": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/unchecked.svg"}, "Image::separator":{"image_url": f"{EXTENSION_FOLDER_PATH}/icons/separator.svg"}, "Image::collapsable_opened": {"color": cl_text, "image_url": f"{EXTENSION_FOLDER_PATH}/icons/closed.svg"}, "Image::collapsable_closed": {"color": cl_text, "image_url": f"{EXTENSION_FOLDER_PATH}/icons/open.svg"}, "Image::combobox": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/combobox_bg.svg"}, # for Gradient Image "ImageWithProvider::gradient_slider":{"border_radius": 4, "corner_flag": ui.CornerFlag.ALL}, "ImageWithProvider::button_background_gradient": {"border_radius": 3, "corner_flag": ui.CornerFlag.ALL}, # for Customized ComboBox "ComboBox::dropdown_menu":{ "color": cl_text, # label color "background_color": cl_combobox_background, "secondary_color": 0x0, # button background color }, } def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = (hex >> 16) & 255 alpha = (hex >> 24) & 255 rgba_values = [red, green, blue, alpha] return rgba_values def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)] return (color[3] << 8 * 3) + (color[2] << 8 * 2) + (color[1] << 8 * 1) + color[0] def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) if idx == step_size: color = colors[-1] else: color = _interpolate_color(colors[idx], colors[idx+1], percentage) return color def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) _byte_provider = ui.ByteImageProvider() _byte_provider.set_bytes_data(data, [len(colors), 1]) return _byte_provider def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name) return byte_provider
7,557
Python
34.819905
117
0.633849
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/extension.py
# Copyright (c) 2022, 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. # __all__ = ["ExampleWindowExtension"] from .window import PropertyWindowExample from functools import partial import asyncio import omni.ext import omni.kit.ui import omni.ui as ui class ExampleWindowExtension(omni.ext.IExt): """The entry point for Gradient Style Window Example""" WINDOW_NAME = "Gradient Style Window Example" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Put the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(ExampleWindowExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user pressed "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = PropertyWindowExample(ExampleWindowExtension.WINDOW_NAME, width=450, height=900) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
2,895
Python
36.610389
108
0.666321
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/__init__.py
# Copyright (c) 2018-2020, 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. # __all__ = ["ExampleWindowExtension", "PropertyWindowExample"] from .extension import ExampleWindowExtension from .window import PropertyWindowExample
584
Python
43.999997
76
0.811644
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/collapsable_widget.py
# Copyright (c) 2022, 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. # __all__ = ["CustomCollsableFrame"] import omni.ui as ui def build_collapsable_header(collapsed, title): """Build a custom title of CollapsableFrame""" with ui.HStack(): ui.Spacer(width=10) ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=16, height=16) class CustomCollsableFrame: """The compound widget for color input""" def __init__(self, frame_name, collapsed=False): with ui.ZStack(): self.collapsable_frame = ui.CollapsableFrame( frame_name, name="group", build_header_fn=build_collapsable_header, collapsed=collapsed) with ui.VStack(): ui.Spacer(height=29) with ui.HStack(): ui.Spacer(width=20) ui.Image(name="separator", fill_policy=ui.FillPolicy.STRETCH, height=15) ui.Spacer(width=20)
1,519
Python
35.190475
104
0.655036
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/color_widget.py
# Copyright (c) 2022, 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. # __all__ = ["ColorWidget"] from ctypes import Union from typing import List, Optional import omni.ui as ui from .style import build_gradient_image, cl_attribute_red, cl_attribute_green, cl_attribute_blue, cl_attribute_dark SPACING = 16 class ColorWidget: """The compound widget for color input""" def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = args self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.__multifield: Optional[ui.MultiFloatDragField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__draw_colorpicker = kwargs.pop("draw_colorpicker", True) self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__model = None self.__multifield = None self.__colorpicker = None self.__frame = None def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__root_frame, attr) @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__multifield: return self.__multifield.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__multifield.model = value self.__colorpicker.model = value def _build_fn(self): def _on_value_changed(model, rect_changed, rect_default): if model.get_item_value_model().get_value_as_float() != 0: rect_changed.visible = False rect_default.visible = True else: rect_changed.visible = True rect_default.visible = False def _restore_default(model, rect_changed, rect_default): items = model.get_item_children() for id, item in enumerate(items): model.get_item_value_model(item).set_value(self.__defaults[id]) rect_changed.visible = False rect_default.visible = True with ui.HStack(spacing=SPACING): # The construction of multi field depends on what the user provided, # defaults or a model if self.__model: # the user provided a model self.__multifield = ui.MultiFloatDragField( min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color" ) model = self.__model else: # the user provided a list of default values with ui.ZStack(): with ui.HStack(): self.color_button_gradient_R = build_gradient_image([cl_attribute_dark, cl_attribute_red], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_G = build_gradient_image([cl_attribute_dark, cl_attribute_green], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_B = build_gradient_image([cl_attribute_dark, cl_attribute_blue], 22, "button_background_gradient") ui.Spacer(width=2) with ui.HStack(): with ui.VStack(): ui.Spacer(height=1) self.__multifield = ui.MultiFloatDragField( *self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color") ui.Spacer(width=3) with ui.HStack(spacing=22): labels = ["R", "G", "B"] if self.__draw_colorpicker else ["X", "Y", "Z"] ui.Label(labels[0], name="attribute_r") ui.Label(labels[1], name="attribute_g") ui.Label(labels[2], name="attribute_b") model = self.__multifield.model if self.__draw_colorpicker: self.__colorpicker = ui.ColorWidget(model, width=0) rect_changed, rect_default = self.__build_value_changed_widget() model.add_item_changed_fn(lambda model, i: _on_value_changed(model, rect_changed, rect_default)) rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(model, rect_changed, rect_default)) def __build_value_changed_widget(self): with ui.VStack(width=0): ui.Spacer(height=3) rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False) ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=3) rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True) return rect_changed, rect_default
5,735
Python
43.465116
150
0.565998
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/window.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved./icons/ # # 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. # __all__ = ["PropertyWindowExample"] from ast import With from ctypes import alignment import omni.kit import omni.ui as ui from .style import main_window_style, get_gradient_color, build_gradient_image from .style import cl_combobox_background, cls_temperature_gradient, cls_color_gradient, cls_tint_gradient, cls_grey_gradient, cls_button_gradient from .color_widget import ColorWidget from .collapsable_widget import CustomCollsableFrame, build_collapsable_header LABEL_WIDTH = 120 SPACING = 10 def _get_plus_glyph(): return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg") def _get_search_glyph(): return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_search.svg") class PropertyWindowExample(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = main_window_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def _build_transform(self): """Build the widgets of the "Calculations" group""" with ui.ZStack(): with ui.VStack(): ui.Spacer(height=5) with ui.HStack(): ui.Spacer() ui.Image(name="transform", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=24, height=24) ui.Spacer(width=30) ui.Spacer() with CustomCollsableFrame("TRANSFORMS").collapsable_frame: with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=2) self._build_vector_widget("Position", 70) self._build_vector_widget("Rotation", 70) with ui.ZStack(): self._build_vector_widget("Scale", 85) with ui.HStack(): ui.Spacer(width=42) ui.Image(name="link", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20) def _build_path(self): CustomCollsableFrame("PATH", collapsed=True) def _build_light_properties(self): """Build the widgets of the "Parameters" group""" with CustomCollsableFrame("LIGHT PROPERTIES").collapsable_frame: with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=2) self._build_combobox("Type", ["Sphere Light", "Disk Light", "Rect Light"]) self.color_gradient_data, self.tint_gradient_data, self.grey_gradient_data = self._build_color_widget("Color") self._build_color_temperature() self.diffuse_button_data = self._build_gradient_float_slider("Diffuse Multiplier") self.exposture_button_data = self._build_gradient_float_slider("Exposture") self.intensity_button_data = self._build_gradient_float_slider("Intensity", default_value=3000, min=0, max=6000) self._build_checkbox("Normalize Power", False) self._build_combobox("Purpose", ["Default", "Customized"]) self.radius_button_data = self._build_gradient_float_slider("Radius") self._build_shaping() self.specular_button_data = self._build_gradient_float_slider("Specular Multiplier") self._build_checkbox("Treat As Point") def _build_line_dot(self, line_width, height): with ui.HStack(): ui.Spacer(width=10) with ui.VStack(width=line_width): ui.Spacer(height=height) ui.Line(name="group_line", alignment=ui.Alignment.TOP) with ui.VStack(width=6): ui.Spacer(height=height-2) ui.Circle(name="group_circle", width=6, height=6, alignment=ui.Alignment.BOTTOM) def _build_shaping(self): """Build the widgets of the "SHAPING" group""" with ui.ZStack(): with ui.HStack(): ui.Spacer(width=3) self._build_line_dot(10, 17) with ui.HStack(): ui.Spacer(width=13) with ui.VStack(): ui.Spacer(height=17) ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0) ui.Spacer(height=80) with ui.CollapsableFrame(" SHAPING", name="group", build_header_fn=build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): self.angle_button_data = self._build_gradient_float_slider("Cone Angle") self.softness_button_data = self._build_gradient_float_slider("Cone Softness") self.focus_button_data = self._build_gradient_float_slider("Focus") self.focus_color_data, self.focus_tint_data, self.focus_grey_data = self._build_color_widget("Focus Tint") def _build_vector_widget(self, widget_name, space): with ui.HStack(): ui.Label(widget_name, name="attribute_name", width=0) ui.Spacer(width=space) # The custom compound widget ColorWidget(1.0, 1.0, 1.0, draw_colorpicker=False) ui.Spacer(width=10) def _build_color_temperature(self): with ui.ZStack(): with ui.HStack(): ui.Spacer(width=10) with ui.VStack(): ui.Spacer(height=8) ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0) with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): self._build_line_dot(10, 8) ui.Label("Enable Color Temperature", name="attribute_name", width=0) ui.Spacer() ui.Image(name="on_off", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20) rect_changed, rect_default = self.__build_value_changed_widget() self.temperature_button_data = self._build_gradient_float_slider(" Color Temperature", default_value=6500.0) self.temperature_slider_data = self._build_slider_handle(cls_temperature_gradient) with ui.HStack(): ui.Spacer(width=10) ui.Line(name="group_line", alignment=ui.Alignment.TOP) def _build_color_widget(self, widget_name): with ui.ZStack(): with ui.HStack(): ui.Spacer(width=10) with ui.VStack(): ui.Spacer(height=8) ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0) with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): self._build_line_dot(40, 9) ui.Label(widget_name, name="attribute_name", width=0) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) ui.Spacer(width=10) color_data = self._build_slider_handle(cls_color_gradient) tint_data = self._build_slider_handle(cls_tint_gradient) grey_data = self._build_slider_handle(cls_grey_gradient) with ui.HStack(): ui.Spacer(width=10) ui.Line(name="group_line", alignment=ui.Alignment.TOP) return color_data, tint_data, grey_data def _build_slider_handle(self, colors): handle_Style = {"background_color": colors[0], "border_width": 2, "border_color": cl_combobox_background} def set_color(placer, handle, offset): # first clamp the value max = placer.computed_width - handle.computed_width if offset < 0: placer.offset_x = 0 elif offset > max: placer.offset_x = max color = get_gradient_color(placer.offset_x.value, max, colors) handle_Style.update({"background_color": color}) handle.style = handle_Style with ui.HStack(): ui.Spacer(width=18) with ui.ZStack(): with ui.VStack(): ui.Spacer(height=3) byte_provider = build_gradient_image(colors, 8, "gradient_slider") with ui.HStack(): handle_placer = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=0) with handle_placer: handle = ui.Circle(width=15, height=15, style=handle_Style) handle_placer.set_offset_x_changed_fn(lambda offset: set_color(handle_placer, handle, offset.value)) ui.Spacer(width=22) return byte_provider def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(name="main_frame"): with ui.VStack(height=0, spacing=SPACING): self._build_head() self._build_transform() self._build_path() self._build_light_properties() ui.Spacer(height=30) def _build_head(self): with ui.ZStack(): ui.Image(name="header_frame", height=150, fill_policy=ui.FillPolicy.STRETCH) with ui.HStack(): ui.Spacer(width=12) with ui.VStack(spacing=8): self._build_tabs() ui.Spacer(height=1) self._build_selection_widget() self._build_stage_path_widget() self._build_search_field() ui.Spacer(width=12) def _build_tabs(self): with ui.HStack(height=35): ui.Label("DETAILS", width=ui.Percent(17), name="details") with ui.ZStack(): ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35) with ui.HStack(): ui.Spacer(width=15) ui.Label("LAYERS | ", name="layers", width=0) ui.Label(f"{_get_plus_glyph()}", width=0) ui.Spacer() ui.Image(name="pin", width=20) def _build_selection_widget(self): with ui.HStack(height=20): add_button = ui.Button(f"{_get_plus_glyph()} Add", width=60, name="add") ui.Spacer(width=14) ui.StringField(name="add").model.set_value("(2 models selected)") ui.Spacer(width=8) ui.Image(name="expansion", width=20) def _build_stage_path_widget(self): with ui.HStack(height=20): ui.Spacer(width=3) ui.Label("Stage Path", name="header_attribute_name", width=70) ui.StringField(name="path").model.set_value("/World/environment/tree") def _build_search_field(self): with ui.HStack(): ui.Spacer(width=2) # would add name="search" style, but there is a bug to use glyph together with style # make sure the test passes for now ui.StringField(height=23).model.set_value(f"{_get_search_glyph()} Search") def _build_checkbox(self, label_name, default_value=True): def _restore_default(rect_changed, rect_default): image.name = "checked" if default_value else "unchecked" rect_changed.visible = False rect_default.visible = True def _on_value_changed(image, rect_changed, rect_default): image.name = "unchecked" if image.name == "checked" else "checked" if (default_value and image.name == "unchecked") or (not default_value and image.name == "checked"): rect_changed.visible = True rect_default.visible = False else: rect_changed.visible = False rect_default.visible = True with ui.HStack(): ui.Label(label_name, name=f"attribute_bool", width=self.label_width, height=20) name = "checked" if default_value else "unchecked" image =ui.Image(name=name, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=18, width=18) ui.Spacer() rect_changed, rect_default = self.__build_value_changed_widget() image.set_mouse_pressed_fn(lambda x, y, b, m: _on_value_changed(image, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(rect_changed, rect_default)) def __build_value_changed_widget(self): with ui.VStack(width=20): ui.Spacer(height=3) rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False) ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=3) rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True) return rect_changed, rect_default def _build_gradient_float_slider(self, label_name, default_value=0, min=0, max=1): def _on_value_changed(model, rect_changed, rect_defaul): if model.as_float == default_value: rect_changed.visible = False rect_defaul.visible = True else: rect_changed.visible = True rect_defaul.visible = False def _restore_default(slider): slider.model.set_value(default_value) with ui.HStack(): ui.Label(label_name, name=f"attribute_name", width=self.label_width) with ui.ZStack(): button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient") with ui.VStack(): ui.Spacer(height=1.5) with ui.HStack(): slider = ui.FloatSlider(name="float_slider", height=0, min=min, max=max) slider.model.set_value(default_value) ui.Spacer(width=1.5) ui.Spacer(width=4) rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider)) return button_background_gradient def _build_combobox(self, label_name, options): def _on_value_changed(model, rect_changed, rect_defaul): index = model.get_item_value_model().get_value_as_int() if index == 0: rect_changed.visible = False rect_defaul.visible = True else: rect_changed.visible = True rect_defaul.visible = False def _restore_default(combo_box): combo_box.model.get_item_value_model().set_value(0) with ui.HStack(): ui.Label(label_name, name=f"attribute_name", width=self.label_width) with ui.ZStack(): ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35) with ui.HStack(): ui.Spacer(width=10) with ui.VStack(): ui.Spacer(height=10) option_list = list(options) combo_box = ui.ComboBox(0, *option_list, name="dropdown_menu") with ui.VStack(width=0): ui.Spacer(height=10) rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes combo_box.model.add_item_changed_fn(lambda m, i: _on_value_changed(m, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(combo_box))
17,220
Python
45.923706
146
0.573403