file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.helper.file_utils/omni/kit/helper/file_utils/tests/test_event_queue.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app from unittest.mock import Mock from omni.kit.test.async_unittest import AsyncTestCase from omni.kit.helper.file_utils import asset_types from .. import ( FILE_OPENED_EVENT, FILE_SAVED_EVENT, FileEventModel, get_instance, get_latest_urls_from_event_queue, get_last_url_opened, get_last_url_saved ) class TestOpenedQueue(AsyncTestCase): """Testing Opened Queue""" async def setUp(self): pass async def tearDown(self): get_instance().clear_event_queue() async def test_get_latest_urls_opened_succeeds(self): """Test saving and retrieving url's from the saved queue""" test_events = [ (FILE_OPENED_EVENT, "omniverse://ov-test/stage.usd", "tag-1"), (FILE_OPENED_EVENT, "omniverse://ov-test/image.jpg", None), (FILE_SAVED_EVENT, "omniverse://ov-baz/folder/", "tag-1"), (FILE_SAVED_EVENT, "omniverse://ov-foo/last_image.png", None), (FILE_OPENED_EVENT, "omniverse://ov-bar/last_material.mdl", "tag-1"), (FILE_OPENED_EVENT, "omniverse://ov-baz/last_url.usd", "tag-2"), ] under_test = get_instance() under_test.clear_event_queue() # Add test urls to queue via event stream event_stream = omni.kit.app.get_app().get_message_bus_event_stream() for event_type, url, tag in test_events: file_event = FileEventModel(url=url, is_folder=url.endswith('/'), tag=tag) event_stream.push(event_type, payload=file_event.dict()) for _ in range(10): await omni.kit.app.get_app().next_update_async() self.assertEqual(len(test_events), len(under_test._event_queue)) self.assertEqual(4, len(get_latest_urls_from_event_queue(num_latest=10, event_type=FILE_OPENED_EVENT))) self.assertEqual(2, len(get_latest_urls_from_event_queue(num_latest=10, event_type=FILE_SAVED_EVENT))) self.assertEqual(3, len(get_latest_urls_from_event_queue(num_latest=10, tag="tag-1"))) self.assertEqual(1, len(get_latest_urls_from_event_queue(num_latest=10, asset_type=asset_types.ASSET_TYPE_USD, tag="tag-1"))) self.assertTrue("last_url" in get_last_url_opened()) self.assertTrue("last_material" in get_last_url_opened(asset_type=asset_types.ASSET_TYPE_MATERIAL)) self.assertTrue("last_image" in get_last_url_saved(asset_type=asset_types.ASSET_TYPE_IMAGE)) # Confirm queue was properly saved into user settings expected = test_events[::-1] # LIFO list matches the order of the event queue self._event_queue = under_test._load_queue_from_settings() # Reload queue from settings self.assertEqual(len(under_test.event_queue), len(expected)) for i, entry in enumerate(under_test.event_queue.items()): file_event = entry[1] test_url = expected[i] self.assertEqual(file_event.url, test_url[1]) self.assertEqual(file_event.tag, test_url[2]) self.assertEqual(file_event.is_folder, test_url[1].endswith('/'))
3,506
Python
47.708333
133
0.669994
omniverse-code/kit/exts/omni.kit.helper.file_utils/omni/kit/helper/file_utils/tests/test_asset_types.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .. import asset_types class TestAssetTypes(omni.kit.test.AsyncTestCase): """Testing FilePickerModel.*asset_type""" async def setUp(self): self.test_filenames = [ ("test.settings.usd", asset_types.ASSET_TYPE_USD_SETTINGS), ("test.settings.usda", asset_types.ASSET_TYPE_USD_SETTINGS), ("test.settings.usdc", asset_types.ASSET_TYPE_USD_SETTINGS), ("test.settings.usdz", asset_types.ASSET_TYPE_USD_SETTINGS), ("test.fbx", asset_types.ASSET_TYPE_FBX), ("test.obj", asset_types.ASSET_TYPE_OBJ), ("test.mdl", asset_types.ASSET_TYPE_MATERIAL), ("test.mtlx", asset_types.ASSET_TYPE_MATERIAL), ("test.bmp", asset_types.ASSET_TYPE_IMAGE), ("test.gif", asset_types.ASSET_TYPE_IMAGE), ("test.jpg", asset_types.ASSET_TYPE_IMAGE), ("test.jpeg", asset_types.ASSET_TYPE_IMAGE), ("test.png", asset_types.ASSET_TYPE_IMAGE), ("test.tga", asset_types.ASSET_TYPE_IMAGE), ("test.tif", asset_types.ASSET_TYPE_IMAGE), ("test.tiff", asset_types.ASSET_TYPE_IMAGE), ("test.hdr", asset_types.ASSET_TYPE_IMAGE), ("test.dds", asset_types.ASSET_TYPE_IMAGE), ("test.exr", asset_types.ASSET_TYPE_IMAGE), ("test.psd", asset_types.ASSET_TYPE_IMAGE), ("test.ies", asset_types.ASSET_TYPE_IMAGE), ("test.wav", asset_types.ASSET_TYPE_SOUND), ("test.wav", asset_types.ASSET_TYPE_SOUND), ("test.wave", asset_types.ASSET_TYPE_SOUND), ("test.ogg", asset_types.ASSET_TYPE_SOUND), ("test.oga", asset_types.ASSET_TYPE_SOUND), ("test.flac", asset_types.ASSET_TYPE_SOUND), ("test.fla", asset_types.ASSET_TYPE_SOUND), ("test.mp3", asset_types.ASSET_TYPE_SOUND), ("test.m4a", asset_types.ASSET_TYPE_SOUND), ("test.spx", asset_types.ASSET_TYPE_SOUND), ("test.opus", asset_types.ASSET_TYPE_SOUND), ("test.adpcm", asset_types.ASSET_TYPE_SOUND), ("test.py", asset_types.ASSET_TYPE_SCRIPT), ("test.nvdb", asset_types.ASSET_TYPE_VOLUME), ("test.vdb", asset_types.ASSET_TYPE_VOLUME), ("test.svg", asset_types.ASSET_TYPE_ICON), (".thumbs", asset_types.ASSET_TYPE_HIDDEN), ("test.usd", asset_types.ASSET_TYPE_USD), ("test.usda", asset_types.ASSET_TYPE_USD), ("test.usdc", asset_types.ASSET_TYPE_USD), ("test.usdz", asset_types.ASSET_TYPE_USD), ("test.live", asset_types.ASSET_TYPE_USD), ] async def tearDown(self): pass async def test_is_asset_type(self): """Testing asset_types.is_asset_type returns expected result""" for test_filename in self.test_filenames: filename, expected = test_filename self.assertTrue(asset_types.is_asset_type(filename, expected)) async def test_get_asset_type(self): """Testing asset_types.get_asset_type returns expected result""" for test_filename in self.test_filenames: filename, expected = test_filename self.assertEqual(asset_types.get_asset_type(filename), expected) # Test unknown file type self.assertEqual(asset_types.get_asset_type("test.unknown"), asset_types.ASSET_TYPE_UNKNOWN) async def test_get_icon(self): """Testing asset_types.get_icon returns expected icon for asset type""" for test_filename in self.test_filenames: filename, asset_type = test_filename if asset_type not in [asset_types.ASSET_TYPE_ICON, asset_types.ASSET_TYPE_HIDDEN]: expected = asset_types._known_asset_types[asset_type].glyph self.assertEqual(asset_types.get_icon(filename), expected) async def test_get_thumbnail(self): """Testing FilePickerModel.get_thumbnail returns correct thumbnail for asset type""" for test_filename in self.test_filenames: filename, asset_type = test_filename if asset_type not in [asset_types.ASSET_TYPE_ICON, asset_types.ASSET_TYPE_HIDDEN]: expected = asset_types._known_asset_types[asset_type].thumbnail self.assertEqual(asset_types.get_thumbnail(filename), expected) async def test_register_file_extensions(self): """Testing FilePickerModel.register_file_extensions""" # Add to existing type asset_types.register_file_extensions("usd", [".test", "testz"]) self.assertTrue(asset_types.is_asset_type("file.testz", "usd")) # Register new type test_type = "test" asset_types.register_file_extensions(test_type, [".test", "testz"]) self.assertTrue(asset_types.is_asset_type("file.test", test_type)) self.assertTrue(asset_types.is_asset_type("file.testz", test_type))
5,417
Python
49.635514
100
0.625623
omniverse-code/kit/exts/omni.kit.helper.file_utils/docs/index.rst
omni.kit.helper.file_utils ########################## .. toctree:: :maxdepth: 1 CHANGELOG
98
reStructuredText
11.374999
26
0.479592
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/style.py
__all__ = ["ActionsWindowStyle"] from omni.ui import color as cl from pathlib import Path CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("icons") VIEW_ROW_HEIGHT = 28 """Style colors""" # https://confluence.nvidia.com/pages/viewpage.action?pageId=1218553472&preview=/1218553472/1359943485/image2022-6-7_13-20-4.png cl.actions_column_header_background = cl.shade(cl("#323434")) cl.actions_text = cl.shade(cl("#848484")) cl.actions_background = cl.shade(cl("#1F2123")) cl.actions_background_hovered = cl.shade(cl("#2A2B2C")) cl.actions_background_selected = cl.shade(cl("#77878A")) cl.actions_item_icon_expand_background = cl.shade(cl('#9E9E9E')) cl.actions_row_background = cl.shade(cl('#444444')) ACTIONS_WINDOW_STYLE = { "ActionsView": { "background_color": cl.actions_background, "scrollbar_size": 10, "background_selected_color": 0x109D905C, # Same in stage window "secondary_selected_color": 0xFFB0703B, # column resize "secondary_color": cl.actions_text, # column splitter }, "ActionsView:selected": { "background_color": cl.actions_background_selected, }, "ActionsView.Row.Background": {"background_color": cl.actions_row_background}, "ActionsView.Header.Background": {"background_color": cl.actions_column_header_background}, "ActionsView.Header.Text": {"color": cl.actions_text, "margin": 4}, "ActionsView.Item.Text": {"color": cl.actions_text, "margin": 4}, "ActionsView.Item.Text:selected": {"color": cl.actions_background}, "ActionsView.Item.Icon.Background": {"background_color": cl.actions_item_icon_expand_background, "border_radius": 2}, "ActionsView.Item.Icon.Background:selected": {"background_color": cl.actions_background}, "ActionsView.Item.Icon.Text": {"color": cl.actions_background}, "ActionsView.Item.Icon.Text:selected": {"color": cl.actions_text}, } HIGHLIGHT_LABEL_STYLE = { "HStack": {"margin": 4}, "Label": {"color": cl.actions_text}, "Label:selected": {"color": cl.actions_background}, }
2,104
Python
43.787233
128
0.696293
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/extension.py
__all__ = ["ActionsExtension"] from functools import partial import carb.settings import omni.ext import omni.ui as ui import omni.kit.ui from omni.kit.actions.core import get_action_registry from .window import ActionsWindow SETTING_SHOW_STARTUP = "/exts/omni.kit.actions.window/showStartup" class ActionsExtension(omni.ext.IExt): WINDOW_NAME = "Actions" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): self._actions_window = None ui.Workspace.set_show_window_fn( ActionsExtension.WINDOW_NAME, partial(self.show_window, ActionsExtension.MENU_PATH), ) show_startup = carb.settings.get_settings().get(SETTING_SHOW_STARTUP) editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item(ActionsExtension.MENU_PATH, self.show_window, toggle=True, value=show_startup) if show_startup: ui.Workspace.show_window(ActionsExtension.WINDOW_NAME) def on_shutdown(self): if self._actions_window: self._actions_window.destroy() self._actions_window = None ui.Workspace.set_show_window_fn(ActionsExtension.WINDOW_NAME, None) def show_window(self, menu_path: str, visible: bool): if visible: self._actions_window = ActionsWindow(ActionsExtension.WINDOW_NAME) self._actions_window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._actions_window: self._actions_window.visible = False def _set_menu(self, checked: bool): """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(ActionsExtension.MENU_PATH, checked) def _visiblity_changed_fn(self, visible): self._set_menu(visible)
1,887
Python
32.122806
124
0.660307
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/__init__.py
__all__ = [ "ActionsExtension", "AbstractActionItem", "ActionExtItem", "AbstractActionsModel", "ColumnRegistry", "ActionsView", "AbstractColumnDelegate", "StringColumnDelegate", "ActionsDelegate", "ActionsPicker", "ACTIONS_WINDOW_STYLE", ] from .extension import * from .model.abstract_actions_model import AbstractActionItem, ActionExtItem, AbstractActionsModel from .column_registry import ColumnRegistry from .widget.actions_view import ActionsView from .delegate.abstract_column_delegate import AbstractColumnDelegate from .delegate.string_column_delegate import StringColumnDelegate from .delegate.actions_delegate import ActionsDelegate from .picker import ActionsPicker from .style import ACTIONS_WINDOW_STYLE
761
Python
32.130433
97
0.780552
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/picker.py
__all__ = ["ActionColumnDelegate", "ActionsPicker"] import omni.ui as ui from typing import List, Callable from omni.kit.actions.core import Action from .window import ActionsWindow from .model.actions_item import AbstractActionItem, ActionDetailItem from .delegate.string_column_delegate import StringColumnDelegate class ActionColumnDelegate(StringColumnDelegate): """ A simple delegate to display a action in column. Kwargs: get_value_fn (Callable[[ui.AbstractItem], str]): Callback function to get item display string. Default using item.id width (ui.Length): Column width. Default ui.Fraction(1). """ def get_value(self, item: ActionDetailItem): if self._get_value_fn: return self._get_value_fn(item) else: if isinstance(item, ActionDetailItem): # Show action display name instead action id return item.action.display_name else: return item.id class ActionsPicker(ActionsWindow): def __init__(self, width=0, height=600, on_selected_fn: Callable[[Action],None]=None, expand_all: bool=True, focus_search: bool=True ): super().__init__("###ACTION_PICKER", width=width, height=height) self.flags = ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_POPUP self.__on_selected_fn = on_selected_fn self.__expand_all = expand_all self.__focus_search = focus_search def _register_column_delegates(self): self._column_registry.register_delegate(ActionColumnDelegate("Action", width=200)) def _build_ui(self): super()._build_ui() self._actions_view.set_selection_changed_fn(self._on_selection_changed) if self.__expand_all: self._actions_view.set_expanded(None, True, True) if self.__focus_search and self._search_field: self._search_field._search_field.focus_keyboard() def _on_selection_changed(self, selections: List[AbstractActionItem]): for item in selections: if isinstance(item, ActionDetailItem): if self.__on_selected_fn: self.__on_selected_fn(item.action) def _on_search_action(self, action: Action, word: str) -> bool: # In pick mode, only display extension id and display name # So we only search in these two fields if word.lower() in action.extension_id.lower() \ or word.lower() in action.display_name.lower(): return True return False
2,623
Python
38.164179
127
0.64125
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/column_registry.py
__all__ = ["ColumnRegistry"] from typing import Optional, Dict import carb from .delegate.abstract_column_delegate import AbstractColumnDelegate class ColumnRegistry: """ Registry for action columns. """ def __init__(self): self._max_column_id = -1 self._delegates: Dict[int, AbstractColumnDelegate] = {} @property def max_column_id(self) -> int: """ Max column id registered. """ return self._max_column_id def register_delegate(self, delegate: AbstractColumnDelegate, column_id: int=-1, overwrite_if_exists: bool=True) -> bool: """ Register a delegate for a column. Args: delegate (AbstractColumnDelegate): Delegate to show a column. Kwargs: column_id (int): Column id. Default -1 means auto generation. overwrite_if_exists (bool): Overwrite exising delegate if True. Otherwise False. """ if column_id < 0: column_id = self._max_column_id + 1 if column_id in self._delegates: if not overwrite_if_exists: carb.log_warn(f"A delegate already registered for column {column_id}!") return False self._delegates[column_id] = delegate self._max_column_id = column_id return True def unregister_delegate(self, column_id: int) -> bool: """ Unregister a delegate for a column. Args: column_id (int): Column id to unregister. """ if column_id in self._delegates: self._delegates.pop(column_id) if column_id == self._max_column_id: self._max_column_id -= 1 def get_delegate(self, column_id: int) -> Optional[AbstractColumnDelegate]: """ Retrieve a delegate for a column. Args: column_id (int): Column id. """ if column_id in self._delegates: return self._delegates[column_id] else: return None
2,034
Python
29.833333
126
0.576205
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/window.py
__all__ = ["ActionsWindow"] from .model.actions_model import ActionsModel, ActionDetailItem from .column_registry import ColumnRegistry from .widget.actions_view import ActionsView from .delegate.actions_delegate import ActionsDelegate from .delegate.string_column_delegate import StringColumnDelegate from .style import ACTIONS_WINDOW_STYLE import omni.ui as ui from omni.kit.actions.core import Action from typing import List, Optional class ActionsWindow(ui.Window): """ Window to show registered actions. """ def __init__(self, title: str, width=1200, height=600): self._search_field = None super().__init__(title, width=width, height=height) self.frame.set_style(ACTIONS_WINDOW_STYLE) self.frame.set_build_fn(self._build_ui) def destroy(self): self.visible = False if self._search_field: self._search_field.destroy() self._actions_view = None def _register_column_delegates(self): self._column_registry.register_delegate(StringColumnDelegate("Action", width=200)) self._column_registry.register_delegate( StringColumnDelegate( "Display Name", get_value_fn=lambda item: item.action.display_name if isinstance(item, ActionDetailItem) else "", width=300 ) ) self._column_registry.register_delegate( StringColumnDelegate( "Tag", get_value_fn=lambda item: item.action.tag if isinstance(item, ActionDetailItem) else "", width=160, ) ) self._column_registry.register_delegate( StringColumnDelegate( "Icon Url", lambda item: item.action.icon_url if isinstance(item, ActionDetailItem) else "", width=120, ) ) self._column_registry.register_delegate( StringColumnDelegate( "Description", lambda item: item.action.description if isinstance(item, ActionDetailItem) else "", width=200, ) ) def _build_ui(self): self._column_registry = ColumnRegistry() self._register_column_delegates() self._actions_model = ActionsModel(self._column_registry, on_search_action_fn=self._on_search_action) self._actions_delegate = ActionsDelegate(self._actions_model, self._column_registry) with self.frame: with ui.VStack(spacing=4): try: from omni.kit.widget.searchfield import SearchField self._search_field = SearchField( on_search_fn=self._on_search, subscribe_edit_changed=True, style=ACTIONS_WINDOW_STYLE, show_tokens=False, ) except ImportError: self._search_field = None with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="ActionsView", ): self._actions_view = ActionsView(self._actions_model, self._actions_delegate) def _on_search(self, search_words: Optional[List[str]]) -> None: self._actions_model.search(search_words) # Auto expand on searching self._actions_view.set_expanded(None, True, True) def _on_search_action(self, action: Action, word: str) -> bool: if word.lower() in action.extension_id.lower() \ or word.lower() in action.id.lower() \ or word.lower() in action.display_name.lower() \ or word.lower() in action.description.lower() \ or word.lower() in action.tag.lower() \ or word.lower() in action.icon_url.lower(): return True return False
4,048
Python
37.932692
113
0.589427
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/widget/actions_view.py
__all__ = ["ActionsView"] import omni.ui as ui from ..model.abstract_actions_model import AbstractActionsModel from ..delegate.actions_delegate import ActionsDelegate class ActionsView(ui.TreeView): def __init__(self, model: AbstractActionsModel, delegate: ActionsDelegate): super().__init__( model, delegate=delegate, root_visible=False, header_visible=True, columns_resizable=True, style_type_name_override="ActionsView" ) self.column_widths = delegate.column_widths
571
Python
30.777776
79
0.646235
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/delegate/actions_delegate.py
__all__ = ["ActionsDelegate"] from typing import List import omni.ui as ui from typing import Optional from .abstract_column_delegate import AbstractColumnDelegate from ..model.abstract_actions_model import AbstractActionsModel from ..column_registry import ColumnRegistry from ..style import ICON_PATH, VIEW_ROW_HEIGHT class ActionsDelegate(ui.AbstractItemDelegate): """ General action delegate to show action item in treeview. Args: column_registry (ColumnRegistry): Registry to get column delegate. """ def __init__(self, model: AbstractActionsModel, column_registry: ColumnRegistry): self._model = model self._column_registry = column_registry self.__context_menu: Optional[ui.Menu] = None self.__execute_menuitem: Optional[ui.MenuItem] = None super().__init__() @property def column_widths(self) -> List[ui.Length]: """ Column widths for treeview. """ widths = [] for i in range(self._column_registry.max_column_id): delegate = self._column_registry.get_delegate(i) if delegate: widths.append(delegate.width) return widths def build_branch(self, model: ui.AbstractItemModel, item: ui.AbstractItem, column_id: int=0, level: int = 0, expanded: bool = False): """ Build branch for column. Refer to ui.AbstractItemDelegate.build_branch for detail. """ if column_id == 0: with ui.HStack(width=20 * (level + 1), height=0): if model.can_item_have_children(item): with ui.ZStack(): with ui.VStack(height=VIEW_ROW_HEIGHT): ui.Spacer() ui.Rectangle(height=26, style_type_name_override="ActionsView.Row.Background") ui.Spacer() with ui.VStack(): ui.Spacer() self.__build_expand_icon(expanded) super().build_branch(model, item, column_id, level, expanded) ui.Spacer() else: ui.Spacer() def build_widget(self, model: ui.AbstractItemModel, item: ui.AbstractItem, column_id: int=0, level: int=0, expanded: bool=False): """ Build widget for column. Refer to ui.AbstractItemDelegate.build_widget for detail. """ delegate = self._column_registry.get_delegate(column_id) if delegate: widget = delegate.build_widget(model, item, level, expanded) if widget: widget.set_mouse_pressed_fn(lambda x, t, b, f, i=item, d=delegate: self.on_mouse_pressed(b, i, d)) widget.set_mouse_double_clicked_fn(lambda x, y, b, f, i=item, d=delegate: self.on_mouse_double_click(b, i, d)) def build_header(self, column_id): """ Build header for column. Refer to ui.AbstractItemDelegate.build_header for detail. """ delegate = self._column_registry.get_delegate(column_id) if delegate: delegate.build_header() def on_mouse_double_click(self, button: int, item: ui.AbstractItem, column_delegate: AbstractColumnDelegate): if button == 0: self._model.execute(item) def on_mouse_pressed(self, button: int, item: ui.AbstractItem, column_delegate: AbstractColumnDelegate): if button == 1: if self.__context_menu is None: self.__context_menu = ui.Menu(f"ACTION CONTEXT MENU##{hash(self)}") with self.__context_menu: self.__execute_menuitem = ui.MenuItem("Execute") self.__execute_menuitem.set_triggered_fn(lambda i=item: self._model.execute(item)) self.__context_menu.show() def __build_expand_icon(self, expanded: bool): # Draw the +/- icon with ui.HStack(): ui.Spacer() image_name = "Minus" if expanded else "Plus" ui.Image( f"{ICON_PATH}/{image_name}.svg", width=10, height=10, style_type_name_override="TreeView.Item" ) ui.Spacer(width=5)
4,241
Python
40.588235
137
0.581938
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/delegate/string_column_delegate.py
__all__ = ["StringColumnDelegate"] from .abstract_column_delegate import AbstractColumnDelegate from ..model.actions_item import ActionExtItem, AbstractActionItem from ..model.abstract_actions_model import AbstractActionsModel from ..style import HIGHLIGHT_LABEL_STYLE import omni.ui as ui from omni.kit.widget.highlight_label import HighlightLabel from typing import Callable class StringColumnDelegate(AbstractColumnDelegate): """ A simple delegate to display a string in column. Kwargs: get_value_fn (Callable[[ui.AbstractItem], str]): Callback function to get item display string. Default using item.id width (ui.Length): Column width. Default ui.Fraction(1). """ def __init__(self, name: str, get_value_fn: Callable[[AbstractActionItem], str]=None, width: ui.Length=ui.Fraction(1)): self._get_value_fn = get_value_fn super().__init__(name, width=width) def build_widget(self, model: AbstractActionsModel, item: AbstractActionItem, level: int, expand: bool): if isinstance(item, ActionExtItem): container = ui.ZStack() with container: with ui.VStack(): ui.Spacer() ui.Rectangle(height=26, style_type_name_override="ActionsView.Row.Background") ui.Spacer() HighlightLabel(self.get_value(item), highlight=item.highlight, style=HIGHLIGHT_LABEL_STYLE, alignment=ui.Alignment.LEFT_TOP) return container if isinstance(item, ActionExtItem) or isinstance(item, AbstractActionItem): label = HighlightLabel(self.get_value(item), highlight=item.highlight, style=HIGHLIGHT_LABEL_STYLE) return label.widget else: return None def get_value(self, item: AbstractActionItem): if self._get_value_fn: return self._get_value_fn(item) else: return item.id
1,932
Python
42.931817
140
0.668219
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/delegate/abstract_column_delegate.py
__all__ = ["AbstractColumnDelegate"] import omni.ui as ui import abc class AbstractColumnDelegate: """ Represent a column delegate in actions Treeview. Args: name (str): Column name. width (ui.Length): Column width. Default ui.Fraction(1). """ def __init__(self, name: str, width: ui.Length=ui.Fraction(1)): self._name = name if isinstance(width, int) or isinstance(width, float): width = ui.Pixel(width) self._width = width @property def width(self) -> ui.Length: """ Column width. """ return self._width def execute(self, item: ui.AbstractItem): """ Execute model item. Args: item (ui.AbstractItem): Item to show. """ pass @abc.abstractmethod def build_widget(self, model: ui.AbstractItemModel, item: ui.AbstractItem, level: int, expand: bool) -> ui.Widget: """ Build a custom column widget in TreeView. Return created widget. Args: model (ui.AbstractItemModel): Actions model. item (ui.AbstractItem): Item to show. level (int): Level in treeview. expand (bool): Iten expand or not. """ return None def build_header(self): """ Build header widget in TreeView, default ui.Label(name) """ with ui.ZStack(): ui.Rectangle(style_type_name_override="ActionsView.Header.Background") ui.Label(self._name, style_type_name_override="ActionsView.Header.Text")
1,593
Python
26.482758
118
0.576899
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/tests/__init__.py
from .test_actions_window import *
35
Python
16.999992
34
0.771429
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/tests/test_actions_window.py
from ast import Import import omni.kit.test import omni.kit.app from omni.ui.tests.test_base import OmniUiTest from omni.kit.actions.core import get_action_registry import omni.ui as ui import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 from pathlib import Path CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") ACTION_SHOW_WINDOW = "Show Actions Window" ACTION_HIDE_WINDOW = "Hide Actions Window" class TestActionsWindow(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._ext_id = "omni.kit.actions.window.tests" self.__register_test_actions() window = ui.Workspace.get_window("Actions") await self.docked_test_window(window=window, width=1280, height=400, block_devices=False) async def tearDown(self): # Deregister all the test actions. self._action_registry.deregister_action(self._ext_id, ACTION_SHOW_WINDOW) self._action_registry.deregister_action(self._ext_id, ACTION_HIDE_WINDOW) self._action_registry = None async def test_1_general_window(self): # When startup, no actions loaded result_name = "test_action_window_general" try: from omni.kit.widget.searchfield import SearchField result_name += "_with_search" # Wait for serach icon loaded for i in range(5): await omni.kit.app.get_app().next_update_async() except ImportError: pass await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"{result_name}.png") async def test_2_search(self): try: from omni.kit.widget.searchfield import SearchField # Actions reloaded, we can see register actions now # Focus on search bar await ui_test.emulate_mouse_move_and_click(Vec2(50, 17)) # Search "Show" await ui_test.emulate_char_press("Show\n") await ui_test.emulate_mouse_move_and_click(Vec2(0, 0)) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_action_window_search.png") except ImportError: pass async def test_3_search_clean(self): try: from omni.kit.widget.searchfield import SearchField # Focus on search bar await ui_test.emulate_mouse_move_and_click(Vec2(50, 17)) # Clean search await ui_test.emulate_mouse_move_and_click(Vec2(1263, 17)) await ui_test.emulate_mouse_move_and_click(Vec2(0, 0)) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_action_window_search_clean.png") except ImportError: pass def __register_test_actions(self): self._action_registry = get_action_registry() self._action_registry.register_action( self._ext_id, ACTION_SHOW_WINDOW, lambda: None, display_name=ACTION_SHOW_WINDOW, description=ACTION_SHOW_WINDOW, tag="Actions", ) self._action_registry.register_action( self._ext_id, ACTION_HIDE_WINDOW, lambda: None, display_name=ACTION_HIDE_WINDOW, description=ACTION_HIDE_WINDOW, tag="Actions", )
3,530
Python
36.563829
128
0.630312
omniverse-code/kit/exts/omni.kit.actions.window/docs/CHANGELOG.rst
********** CHANGELOG ********** This document records all notable changes to ``omni.kit.actions.window`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [1.1.0] - 2022-10-17 ### Changed - OM-65822: Also search for Action display name without case sensitive - Update UI to use same style as Hotkeys window ## [1.0.4] - 2022-09-20 ### Added - Add args for auto expand and focus search for ActionsPicker ## [1.0.3] - 2022-09-02 ### Changed - Export more APIs for hotkeys window ### Added - Add ActionsPicker ## [1.0.2] - 2022-09-01 ### Changed - Default not show window when startup ## [1.0.1] - 2022-08-23 ### Added - Execute action from list - Auto expand on searching ## [1.0.0] - 2022-07-06 - First version
750
reStructuredText
21.088235
83
0.673333
omniverse-code/kit/exts/omni.kit.actions.window/docs/index.rst
omni.kit.actions.window ########################### Window to show actions. .. toctree:: :maxdepth: 1 CHANGELOG
122
reStructuredText
10.181817
27
0.52459
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/xform_op_utils.py
from pxr import Usd, Tf, Sdf, Gf, UsdGeom import carb from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload import omni.kit XFROM_OP_PREFIX = "xformOp:" INVERSE_PREFIX = "!invert!" INVERSE_XFORM_OP_PREFIX = "!invert!xformOp:" RESET_XFORM_STACK = UsdGeom.XformOpTypes.resetXformStack XFROM_OP_TYPE_NAME = [ "translate", "scale", "rotateX", "rotateY", "rotateZ", "rotateXYZ", "rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "orient", "transform", ] XFROM_OP_TYPE = [ UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.TypeScale, UsdGeom.XformOp.TypeRotateX, UsdGeom.XformOp.TypeRotateY, UsdGeom.XformOp.TypeRotateZ, UsdGeom.XformOp.TypeRotateXYZ, UsdGeom.XformOp.TypeRotateXZY, UsdGeom.XformOp.TypeRotateYXZ, UsdGeom.XformOp.TypeRotateYZX, UsdGeom.XformOp.TypeRotateZXY, UsdGeom.XformOp.TypeRotateZYX, UsdGeom.XformOp.TypeOrient, UsdGeom.XformOp.TypeTransform, ] def is_inverse_op(op_name: str): return op_name.startswith(INVERSE_XFORM_OP_PREFIX) def is_reset_xform_stack_op(op_name: str): return op_name == RESET_XFORM_STACK def get_op_type_name(op_name: str): test_name = op_name if is_inverse_op(op_name): test_name = op_name.split(INVERSE_PREFIX, 1)[1] if test_name.startswith(XFROM_OP_PREFIX): names = test_name.split(":") if len(names) >= 2 and names[1] in XFROM_OP_TYPE_NAME: return names[1] return None def get_op_type(op_name: str): op_type_name = get_op_type_name(op_name) return XFROM_OP_TYPE[XFROM_OP_TYPE_NAME.index(op_type_name)] def get_op_name_suffix(op_name: str): test_name = op_name if is_inverse_op(op_name): test_name = op_name.split(INVERSE_PREFIX, 1)[1] if test_name.startswith(XFROM_OP_PREFIX): names = test_name.split(":", 2) if len(names) >= 3: return names[2] return None def is_pivot_op(op_name: str): op_suffix = get_op_name_suffix(op_name) if op_suffix != None: if op_suffix == "pivot": return True return False def is_valid_op_name(op_name: str): if is_reset_xform_stack_op(op_name): return True if get_op_type_name(op_name) is not None: return True return False def get_op_attr_name(op_name: str): if not is_valid_op_name(op_name): return None if is_reset_xform_stack_op(op_name): return None if is_inverse_op(op_name): return op_name.split(INVERSE_PREFIX, 1)[1] return op_name def get_inverse_op_Name(ori_op_name, desired_invert): if is_reset_xform_stack_op(ori_op_name): return ori_op_name if desired_invert and not is_inverse_op(ori_op_name): return INVERSE_PREFIX + ori_op_name if not desired_invert and is_inverse_op(ori_op_name): return ori_op_name.split(INVERSE_PREFIX, 1)[1] return ori_op_name def get_op_precision(attr_type_name: Sdf.ValueTypeName): if attr_type_name in [Sdf.ValueTypeNames.Float3, Sdf.ValueTypeNames.Quatf, Sdf.ValueTypeNames.Float]: return UsdGeom.XformOp.PrecisionFloat if attr_type_name in [ Sdf.ValueTypeNames.Double3, Sdf.ValueTypeNames.Quatd, Sdf.ValueTypeNames.Double, Sdf.ValueTypeNames.Matrix4d, ]: return UsdGeom.XformOp.PrecisionDouble if attr_type_name in [Sdf.ValueTypeNames.Half3, Sdf.ValueTypeNames.Quath, Sdf.ValueTypeNames.Half]: return UsdGeom.XformOp.PrecisionHalf return UsdGeom.XformOp.PrecisionDouble def _add_trs_op( payload: PrimSelectionPayload ): settings = carb.settings.get_settings() # Retrieve the default precision default_xform_op_precision = settings.get("/persistent/app/primCreation/DefaultXformOpPrecision") if default_xform_op_precision is None: settings.set_default_string( "/persistent/app/primCreation/DefaultXformOpPrecision", "Double" ) default_xform_op_precision = "Double" _precision = UsdGeom.XformOp.PrecisionDouble if default_xform_op_precision == "Double": _precision = UsdGeom.XformOp.PrecisionDouble elif default_xform_op_precision == "Float": _precision = UsdGeom.XformOp.PrecisionFloat elif default_xform_op_precision == "Half": _precision = UsdGeom.XformOp.PrecisionHalf # Retrieve the default rotation order default_rotation_order = settings.get("/persistent/app/primCreation/DefaultRotationOrder") if default_rotation_order is None: settings.set_default_string("/persistent/app/primCreation/DefaultRotationOrder", "XYZ") default_rotation_order = "XYZ" omni.kit.commands.execute("AddXformOp", payload=payload, precision=_precision, rotation_order = default_rotation_order, add_translate_op = True, add_rotateXYZ_op = True, add_orient_op=False, add_scale_op = True, add_transform_op = False, add_pivot_op = False)
4,957
Python
31.194805
148
0.680048
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_model.py
from typing import Callable import weakref import carb import omni.timeline import omni.ui as ui import omni.usd from pxr import Usd, Sdf, Tf, Gf from omni.kit.property.usd.usd_attribute_model import ( FloatModel, UsdBase, UsdAttributeModel, GfVecAttributeModel, ) # TODO: will add controlstate class VecAttributeModel(ui.AbstractItemModel): def __init__(self, default_value, begin_edit_callback: Callable[[None], None] = None, end_edit_callback: Callable[[Gf.Vec3d], None] = None): super().__init__() # We want to parse the values of this model to look for math operations, # so its items need to use string models instead of float models class StringModel(ui.SimpleStringModel): def __init__(self, parent, index): super().__init__() self._parent = weakref.ref(parent) self.index = index def begin_edit(self): parent = self._parent() parent.begin_edit(self) def end_edit(self): parent = self._parent() parent.end_edit(self) class VectorItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model dimension = 3 self._items = [VectorItem(StringModel(self, i)) for i in range(dimension)] self._default_value = default_value self._begin_edit_callback = begin_edit_callback self._end_edit_callback = end_edit_callback for item in self._items: item.model.set_value(self._default_value) self._root_model = ui.SimpleStringModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._root_model return item.model def _on_value_changed(self, item): pass def begin_edit(self, item): index = item.index if self._begin_edit_callback: self._begin_edit_callback(index) def end_edit(self, model): text = model.get_value_as_string() index = model.index for item in self._items: item.model.set_value(self._default_value) if self._end_edit_callback: self._end_edit_callback(text, index)
2,443
Python
29.936708
144
0.598854
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_widget.py
import traceback import carb import omni.usd import omni.ui as ui from functools import lru_cache from pxr import UsdGeom, Tf, Usd, Sdf from pxr import Trace from collections import defaultdict from typing import Any, DefaultDict, Dict, List, Sequence, Set, Tuple from .transform_builder import TransformWidgets from omni.kit.property.usd import ADDITIONAL_CHANGED_PATH_EVENT_TYPE from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget, get_group_properties_clipboard, set_group_properties_clipboard from omni.kit.property.usd.usd_attribute_model import GfVecAttributeSingleChannelModel from omni.kit.window.property.templates import GroupHeaderContextMenuEvent, GroupHeaderContextMenu from omni.kit.widget.settings import get_style from .xform_op_utils import _add_trs_op @lru_cache() def _get_plus_glyph(): return ui.get_custom_glyph_code("${glyphs}/menu_context.svg") class TransformAttributeWidget(UsdPropertiesWidget): def __init__(self, title: str, collapsed: bool): super().__init__(title="Transform", collapsed=False) self._transform_widget = TransformWidgets(self) self._listener = None self._models = defaultdict(list) self._offset_mode = False self._link_scale = False def on_new_payload(self, payload): if not super().on_new_payload(payload): return False stage = self._payload.get_stage() if not stage or not len(self._payload): return False for path in self._payload: prim = stage.GetPrimAtPath(path) if not prim.IsA(UsdGeom.Xformable): return False return True def clean(self): """ See PropertyWidget.clean """ if self._transform_widget: self._transform_widget._clear_widgets() self._transform_widget = None super().clean() def build_items(self): self.reset() if len(self._payload) == 0: return last_prim = self._get_prim(self._payload[-1]) if not last_prim: return stage = last_prim.GetStage() if not stage: return self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage) self._bus_sub = self._message_bus.create_subscription_to_pop_by_type(ADDITIONAL_CHANGED_PATH_EVENT_TYPE, self._on_bus_event) # for prim_path in self._payload: if self._payload is not None: if self._offset_mode: self._models = self._transform_widget.build_transform_offset_frame(self._payload, self._collapsable_frame, stage) else: self._models, all_empty_xformop = self._transform_widget.build_transform_frame(self._payload, self._collapsable_frame, stage) if len(self._transform_widget._widgets) > 0: self._any_item_visible = True else: # OM-51604 When no xformOpOrder element nor xformOp attributes, a special widget and button for it label_style = {"font_size":18} with ui.VStack(spacing=8): if len(self._payload) == 1: ui.Label("This prim has no transforms", style=label_style, alignment=ui.Alignment.CENTER) ui.Button(f'{_get_plus_glyph()} Add Transforms', clicked_fn=self._on_add_transform) elif all_empty_xformop == False: ui.Label("The selected prims have no common transforms to display", style=label_style, alignment=ui.Alignment.CENTER) else: ui.Label("None of the selected prims has transforms", style=label_style, alignment=ui.Alignment.CENTER) ui.Button(f'{_get_plus_glyph()} Add Transforms', clicked_fn=self._on_add_transform) if self._models is None: self._models = defaultdict(list) # Register the Copy/Paste/Reset All content context menu self._build_header_context_menu('Tranform') @Trace.TraceFunction def _on_usd_changed(self, notice, stage): if stage != self._payload.get_stage(): return for path in notice.GetChangedInfoOnlyPaths(): # if anyone changes the xformOpOrder of the current prim rebuild the collapsable frame if str(path).split(".")[-1] == "xformOpOrder" and path.GetPrimPath() in self._payload: super().request_rebuild() return super()._on_usd_changed(notice, stage) def _build_frame_header(self, collapsed, text: str, id: str = None): """Custom header for CollapsableFrame""" if id is None: id = text if collapsed: alignment = ui.Alignment.RIGHT_CENTER width = 5 height = 7 else: alignment = ui.Alignment.CENTER_BOTTOM width = 7 height = 5 header_stack = ui.HStack(spacing=8) with header_stack: with ui.VStack(width=0): ui.Spacer() ui.Triangle( style_type_name_override="CollapsableFrame.Header", width=width, height=height, alignment=alignment ) ui.Spacer() ui.Label(text, style_type_name_override="CollapsableFrame.Header", width = ui.Fraction(1)) button_style = { "Button.Image": { "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER, }, } if self._offset_mode: defaultStyle = get_style() label_style = defaultStyle.get("CollapsableFrame.Header", {}) label_style.update({"color": 0xFFFFC734}) ui.Label("Offset", style=label_style, width = ui.Fraction(1)) ui.Spacer(width = ui.Fraction(5)) button_style["Button.Image"]["image_url"] = "${glyphs}/offset_active_dark.svg" else: ui.Spacer(width = ui.Fraction(6)) button_style["Button.Image"]["image_url"] = "${glyphs}/offset_dark.svg" with ui.ZStack(content_clipping = True, width=25, height=25): ui.Button("", style = button_style, clicked_fn = self._toggle_offset_mode, identifier = "offset_mode_toggle", tooltip = "Toggle offset mode") def show_attribute_context_menu(b): if b != 1: return event = GroupHeaderContextMenuEvent(group_id=id, payload=[]) GroupHeaderContextMenu.on_mouse_event(event) header_stack.set_mouse_pressed_fn(lambda x, y, b, _: show_attribute_context_menu(b)) def _toggle_offset_mode(self): self._offset_mode = not self._offset_mode self.request_rebuild() def _toggle_link_scale(self): self._link_scale = not self._link_scale self.request_rebuild() def _on_add_transform(self): _add_trs_op(self._payload) self.request_rebuild() def _build_header_context_menu(self, group_id: str): #------Copy All Context Menu-------- def can_copy(object): # Only support single selection copy return len(self._payload) == 1 def on_copy(object): prim = self._get_prim(self._payload[-1]) xformOpOrderAttr = prim.GetAttribute("xformOpOrder") if not xformOpOrderAttr: return xformOpOrder = xformOpOrderAttr.Get() visited_models = set() properties_to_copy: Dict[Sdf.Path, Any] = dict() for models in self._models.values(): for model in models: if model in visited_models: continue visited_models.add(model) # Skip "Mixed" if model.is_ambiguous(): continue paths = model.get_property_paths() if paths: # No need to copy single channel model. Each vector attribute also has a GfVecAttributeModel if isinstance(model, GfVecAttributeSingleChannelModel): continue properties_to_copy[paths[-1]] = model.get_value() if properties_to_copy: properties_to_copy[Sdf.Path(xformOpOrderAttr.GetName())] = xformOpOrder set_group_properties_clipboard(properties_to_copy) menu = { "name": f'Copy All Property Values in Transform', "show_fn": lambda object: True, "enabled_fn": can_copy, "onclick_fn": on_copy, } self._group_menu_entries.append(self._register_header_context_menu_entry(menu, 'Transform')) #------Paste All Context Menu-------- def can_paste(object): # Only support single selection copy properties_to_paste = get_group_properties_clipboard() if not properties_to_paste: return False # Can't paste if the copied content doesn't have xformOpOrder key sourceXformOpOrderValue = properties_to_paste[Sdf.Path("xformOpOrder")] if sourceXformOpOrderValue is None: return False prim = self._get_prim(self._payload[-1]) if not prim: return False xformOpOrderAttr = prim.GetAttribute("xformOpOrder") # Can't paste if the target prim doesn't have xformOpOrder if not xformOpOrderAttr: return False targetXformOpOrderValue = xformOpOrderAttr.Get() # Can't paste if the copied content and target prim's xformOpOrder doesn't match if not targetXformOpOrderValue or sourceXformOpOrderValue != targetXformOpOrderValue: return False return True def on_paste(object): properties_to_copy = get_group_properties_clipboard() if not properties_to_copy: return unique_model_prim_paths: Set[Sdf.Path] = set() for prop_path in self._models: unique_model_prim_paths.add(prop_path.GetPrimPath()) with omni.kit.undo.group(): try: for path, value in properties_to_copy.items(): for prim_path in unique_model_prim_paths: paste_to_model_path = prim_path.AppendProperty(path.name) models = self._models.get(paste_to_model_path, []) for model in models: # No need to paste single channel model. Each vector attribute also has a GfVecAttributeModel if isinstance(model, GfVecAttributeSingleChannelModel): continue else: model.set_value(value) except Exception as e: carb.log_error(f"on_paste error:{traceback.format_exc()}") menu = { "name": f'Paste All Property Values to Transform', "show_fn": lambda object: True, "enabled_fn": can_paste, "onclick_fn": on_paste, } self._group_menu_entries.append(self._register_header_context_menu_entry(menu, 'Transform')) #------Reset All Context Menu------ def can_reset(object): for models in self._models.values(): for model in models: if model.is_different_from_default(): return True return False def on_reset(object): for models in self._models.values(): for model in models: model.set_default() menu = { "name": f'Reset All Property Values in Transform', "show_fn": lambda object: True, "enabled_fn": can_reset, "onclick_fn": on_reset, } self._group_menu_entries.append(self._register_header_context_menu_entry(menu, 'Transform'))
12,429
Python
39.357143
145
0.561107
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_builder.py
from queue import Empty from re import T from typing import Any import weakref import asyncio import os, functools, sys from abc import ABC, abstractmethod from enum import Enum from functools import partial import carb import omni.ui as ui import omni.ext import omni.usd import omni.timeline import omni.kit.commands import carb.settings from omni.hydra.scene_api import * from pxr import Gf, Tf, Vt, Usd, Sdf, UsdGeom from pathlib import Path from collections import defaultdict from omni.kit.property.usd.usd_attribute_model import ( FloatModel, UsdBase, UsdAttributeModel, GfVecAttributeModel, GfVecAttributeSingleChannelModel, GfMatrixAttributeModel, GfQuatAttributeModel, GfQuatEulerAttributeModel, ) from .transform_model import VecAttributeModel from omni.kit.widget.highlight_label import HighlightLabel from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder from omni.kit.context_menu import * from .transform_commands import * from . import xform_op_utils # Settings constants from omni.kit.window.toolbar TRANSFORM_OP_SETTING = "/app/transform/operation" TRANSFORM_OP_MOVE = "move" TRANSFORM_OP_ROTATE = "rotate" TRANSFORM_OP_SCALE = "scale" TRANSFORM_MOVE_MODE_SETTING = "/app/transform/moveMode" TRANSFORM_ROTATE_MODE_SETTING = "/app/transform/rotateMode" TRANSFORM_MODE_GLOBAL = "global" TRANSFORM_MODE_LOCAL = "local" LABEL_PADDING = 128 ICON_PATH = "" quat_view_button_style = { "Button:hovered": {"background_color": 0xFF575757}, "Button": {"background_color": 0xFF333333, "padding": 0, "stack_direction": ui.Direction.RIGHT_TO_LEFT}, "Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "Button.Tooltip": {"color": 0xFF9E9E9E}, "Button.Image": {"color": 0xFFFFCC99, "alignment": ui.Alignment.CENTER}, } euler_view_button_style = { "Button:hovered": {"background_color": 0xFF23211F}, "Button": {"background_color": 0xFF23211F, "padding": 0, "stack_direction": ui.Direction.RIGHT_TO_LEFT}, "Button.Label": {"color": 0xFFA07D4F, "alignment": ui.Alignment.LEFT_CENTER}, "Button.Tooltip": {"color": 0xFF9E9E9E}, "Button.Image": {"color": 0xFFFFCC99, "alignment": ui.Alignment.CENTER}, } class USDXformOpWidget: def __init__( self, prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs=None, ): self._prim_paths = prim_paths self._collapsable_frame = collapsable_frame self._stage = stage self._attr_path = attr_path self._op_name = op_name self._is_valid_op = is_valid_op self._op_order_attr_path = op_order_attr_path self._op_order_index = op_order_index self._model = None self._right_click_menu = None self._label_kwargs = label_kwargs if label_kwargs is not None else {} self.rebuild() def __del__(self): self._prim_paths = None self._collapsable_frame = None self._stage = None self._attr_path = None self._op_name = None self._is_valid_op = False self._op_order_attr_path = None self._op_order_index = -1 if self._model is not None: if isinstance(self._model, list): for model in self._model: model.clean() else: self._model.clean() self._model = None self._right_click_menu = None def rebuild(self): pass def _create_inverse_widgets(self): # Not create inverse widgets for non-op attribute. if self._op_name is None: return is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) if is_inverse_op: ui.Label("¯¹") ''' I don't think this is used def _inverse_op(self): if self._op_order_attr_path is not None and self._op_order_index > -1: order_attr = self._stage.GetObjectAtPath(self._op_order_attr_path) if order_attr: with Sdf.ChangeBlock(): op_order = order_attr.Get() if self._op_order_index < len(op_order): op_name = op_order.__getitem__(self._op_order_index) if op_name == self._op_name: is_inverse_op = xform_op_utils.is_inverse_op(op_name) inverse_op_name = xform_op_utils.get_inverse_op_Name(op_name, not is_inverse_op) self._op_name = inverse_op_name op_order.__setitem__(self._op_order_index, inverse_op_name) order_attr.Set(op_order) # self._window().rebuild_window() self._collapsable_frame.rebuild() ''' def _add_key(self): if self._attr_path is None or self._stage is None: return attr = self._stage.GetObjectAtPath(self._attr_path) if attr: timeline = omni.timeline.get_timeline_interface() current_time = timeline.get_current_time() current_time_code = Usd.TimeCode( omni.usd.get_frame_time_code(current_time, self._stage.GetTimeCodesPerSecond()) ) if omni.usd.attr_has_timesample_on_key(attr, current_time_code): return if attr: omni.usd.copy_timesamples_from_weaker_layer(self._stage, attr) curr_value = attr.Get(current_time_code) if not curr_value: type_name = attr.GetTypeName() value_type = type(type_name.defaultValue) curr_value = value_type(attr_default_value) new_target = self._stage.GetEditTargetForLocalLayer(self._stage.GetEditTarget().GetLayer()) with Usd.EditContext(self._stage, new_target): attr.Set(curr_value, current_time_code) def _delete_op_only(self): if self._op_order_attr_path is not None and self._op_order_index > -1: omni.kit.commands.execute( "RemoveXformOp", op_order_attr_path=self._op_order_attr_path, op_name=self._op_name, op_order_index=self._op_order_index, ) def _delete_op_and_attribute(self): if self._op_order_attr_path is not None and self._op_order_index > -1: omni.kit.commands.execute( "RemoveXformOpAndAttrbute", op_order_attr_path=self._op_order_attr_path, op_name=self._op_name, op_order_index=self._op_order_index, ) omni.kit.window.property.get_window()._window.frame.rebuild() def _delete_non_op_attribute(self): if self._stage is not None and self._op_name is None and self._attr_path is not None: omni.kit.commands.execute("RemoveProperty", prop_path=self._attr_path.pathString) omni.kit.window.property.get_window()._window.frame.rebuild() def _add_non_op_attribute_to_op(self): if self._stage is not None and self._op_name is None and self._attr_path is not None: omni.kit.commands.execute("EnableXformOp", op_attr_path=self._attr_path) # This is to toggle the value widgets for quaternion or euler angle def _on_display_orient_as_rotate(self): self._display_orient_as_rotate = not self._display_orient_as_rotate if self._settings: self._settings.set("/persistent/app/uiSettings/DisplayOrientAsRotate", self._display_orient_as_rotate) if self._display_orient_as_rotate is True: self._quat_view.visible = False self._euler_view.visible = True else: self._quat_view.visible = True self._euler_view.visible = False # The orient label(button) has a different style for two modes def _toggle_orient_button_style(self, button): # About to switch to raw mode if self._display_orient_as_rotate is True: button.set_style(euler_view_button_style) else: button.set_style(quat_view_button_style) def _on_orient_button_clicked(self, mouse_button, widget): if mouse_button != 0: return self._on_display_orient_as_rotate() self._toggle_orient_button_style(widget) def _show_right_click_menu(self, button): if button != 1: return if self._right_click_menu is None: self._right_click_menu = ui.Menu("Right Menu") self._right_click_menu.clear() with self._right_click_menu: # ResetXformStack if xform_op_utils.is_reset_xform_stack_op(self._op_name): text = "Disable" if self._is_valid_op else "Disable Invalid Op" ui.MenuItem(text, triggered_fn=lambda: self._delete_op_only()) # valid/invalid Op elif self._op_name is not None and self._attr_path is not None: # ui.MenuItem("Inverse", triggered_fn=lambda: self._inverse_op()) text_op_only = "Disable" if self._is_valid_op else "Disable Invalid Op" text_op_attr = "Delete" if self._is_valid_op else "Delete Invalid Op" ui.MenuItem(text_op_only, triggered_fn=lambda: self._delete_op_only()) ui.MenuItem(text_op_attr, triggered_fn=lambda: self._delete_op_and_attribute()) # non-op attribute elif self._op_name is None and self._attr_path is not None: ui.MenuItem("Delete", triggered_fn=lambda: self._delete_non_op_attribute()) ui.MenuItem("Enable", triggered_fn=lambda: self._add_non_op_attribute_to_op()) # no-attribute op elif self._op_name is not None and self._attr_path is None: ui.MenuItem("Disable Invalid Op", triggered_fn=lambda: self._delete_op_only()) self._right_click_menu.show() def _create_multi_float_drag_matrix_with_labels(self, model, comp_count, min, max, step, labels): # RECT_WIDTH = 13 SPACING = 4 with ui.ZStack(): with ui.HStack(): ui.Spacer(width=RECT_WIDTH) value_widget = ui.MultiFloatDragField( model, name="multivalue", min=min, max=max, step=step, h_spacing=RECT_WIDTH + SPACING, v_spacing=2 ) with ui.HStack(): for i in range(comp_count): if i != 0: ui.Spacer(width=SPACING) label = labels[i] with ui.ZStack(width=RECT_WIDTH + 1): ui.Rectangle(name="vector_label", style={"background_color": label[1]}) ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER) ui.Spacer() mixed_overlay = [] with ui.VStack(): for i in range(comp_count): with ui.HStack(): for i in range(comp_count): ui.Spacer(width=RECT_WIDTH) mixed_overlay.append(UsdPropertiesWidgetBuilder._create_mixed_text_overlay()) UsdPropertiesWidgetBuilder._create_control_state(model, value_widget, mixed_overlay) class TransformWatchModel(ui.AbstractValueModel): def __init__(self, component_index, stage): super(TransformWatchModel, self).__init__() self._usd_context = omni.usd.get_context() self._component_index = component_index self._value = 0.0 self._selection = self._usd_context.get_selection() self._prim_paths = self._selection.get_selected_prim_paths() self._on_usd_changed() self.usd_watcher = omni.usd.get_watcher() self._subscription = self.usd_watcher.subscribe_to_change_info_path( self._prim_paths[0], self._on_usd_changed ) def clean(self): """Should be called when the extension is unloaded or reloaded""" self._usd_context = None self._selection = None self._prim_paths = None self._subscription.unsubscribe() self._subscription = None def _on_usd_changed(self, path=None): #pragma no cover wgs_coords = get_wgs84_coords("", self._prim_paths[0]) if len(wgs_coords) > 0: self.set_value(wgs_coords[self._component_index]) def get_value_as_float(self) -> float: ''' Returns the value as a float ''' return self._value or 0.0 def get_value_as_string(self) -> str: ''' Returns the float value as a string ''' if self._value is None: return "" # General format. This prints the number as a fixed-point # number, unless the number is too large, in which case it # switches to 'e' exponent notation. return "{0:g}".format(self._value) def set_value(self, new_value: Any) -> None: ''' Attempts to cast new_value to a float and set it to the internal value ''' try: value = float(new_value) except ValueError: value = 0.0 if value != self._value: self._value = value self._value_changed() class USDXformOpTranslateWidget(USDXformOpWidget): @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Translate" if suffix: label_name = label_name + ":" + suffix return label_name def rebuild(self): attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:translate"): carb.log_warn(f"Object {self._path} is not an xformOp:translate attribute ") return is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) suffix = xform_op_utils.get_op_name_suffix(attr_name) if is_inverse_op and suffix == "pivot": return label_name = self.display_name(attr_name) # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) self._model = [] for i in range(3): self._model.append( GfVecAttributeSingleChannelModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], i, False, metadata, False, ) ) vec_model = GfVecAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], 3, type_name.type, False, metadata, ) if len(self._prim_paths) == 1: setattr(vec_model,'transform_widget', self) label = None with ui.HStack(): with ui.HStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: with ui.ZStack(): label_tooltip = label_tooltip + "\nRight click it to disable or delete it." # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) else: label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) ui.Spacer(width=2) self._create_inverse_widgets() with ui.HStack(): range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) kwargs = {"min": range_min, "max": range_max, "step": 1.0} UsdPropertiesWidgetBuilder._create_float_drag_per_channel_with_labels_and_control( models = self._model, metadata = metadata, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], kwargs = kwargs ) #The vec_model is useful when we set the key for all three components together self._model.append(vec_model) UsdPropertiesWidgetBuilder._create_attribute_context_menu(label, vec_model) wgs_coord = get_wgs84_coords("", self._prim_paths[0].pathString) if len(wgs_coord) > 0: #pragma no cover OM-112507 with ui.HStack(): with ui.HStack(width=LABEL_PADDING): label = ui.Label("WGS84", name="title", tooltip=label_tooltip) ui.Spacer(width=2) with ui.HStack(): with ui.VStack(): all_axis = ["Lat", "Lon", "Alt"] colors = {"Lat": 0xFF5555AA, "Lon": 0xFF76A371, "Alt": 0xFFA07D4F} component_index = 0 for axis in all_axis: with ui.HStack(): with ui.HStack(width=LABEL_PADDING): label = ui.Label("", name="title", tooltip=label_tooltip) with ui.ZStack(width=20): ui.Rectangle( width=20, height=20, style={ "background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(axis, name="wgs84_label", alignment=ui.Alignment.CENTER) # NOTE: Updating the WGS84 values does not update the transform translation, # so make the input fields read-only for now. # See https://nvidia-omniverse.atlassian.net/browse/OM-64348 ui.FloatDrag(TransformWatchModel(component_index, self._stage), enabled=False) component_index = component_index + 1 super().rebuild() class USDXformOpRotateWidget(USDXformOpWidget): ROTATE_AXIS_ORDER_MAP = { "xformOp:rotateXYZ": ["X", "Y", "Z"], "xformOp:rotateXZY": ["X", "Z", "Y"], "xformOp:rotateYXZ": ["Y", "X", "Z"], "xformOp:rotateYZX": ["Y", "Z", "X"], "xformOp:rotateZXY": ["Z", "X", "Y"], "xformOp:rotateZYX": ["Z", "Y", "X"], } ROTATE_ORDERS = ["XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"] @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Rotate" if suffix: label_name = label_name + ":" + suffix return label_name def __init__(self, prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs=None): self._rotate_order_drop_down_menu = None super().__init__(prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs) def __del__(self): super().__del__() self._rotate_order_drop_down_menu = None def get_rotation_order_index(order): return USDXformOpRotateWidget.ROTATE_ORDERS.index(order) def _change_rotation_order(self, desired_order_index): attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:rotate"): carb.log_warn(f"Object {self._path} is not an xformOp:rotate attribute ") return is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) suffix = xform_op_utils.get_op_name_suffix(attr_name) current_order_index = 5 rotate_names = attr.SplitName() if len(rotate_names) > 1: rotate_order = rotate_names[1].split("rotate", 1)[1] current_order_index = USDXformOpRotateWidget.get_rotation_order_index(rotate_order) if current_order_index == desired_order_index: return # desired_order = "XYZ" desired_order = USDXformOpRotateWidget.ROTATE_ORDERS[desired_order_index] desired_attr_name = "xformOp:rotate" + desired_order if suffix is not None: desired_attr_name += ":" + suffix desired_op_name = desired_attr_name if not is_inverse_op else "!invert!" + desired_attr_name omni.kit.commands.execute( "ChangeRotationOp", src_op_attr_path=self._attr_path, op_name=self._op_name, dst_op_attr_name=desired_attr_name, is_inverse_op=is_inverse_op, auto_target_layer = True ) # after we finish the rotation change "close" the rotation drop-down menu if self._rotate_order_drop_down_menu: self._rotate_order_drop_down_menu.visible = False # A callback to generate a drop-down-menu-like popup window i.e. self._rotate_order_drop_down_menu # it is used to select & update the rotation order, e.g. XYZ, XZY, ZYX etc. def _on_mouse_click(self,button,parent, order): #only suitable for mouse left click if button != 0: return #Use a popup window to act as a drop-down menu self._rotate_order_drop_down_menu = ui.Window("RotationOrder", width=60, height=130, position_x=parent.screen_position_x, position_y=parent.screen_position_y+parent.computed_height,flags = ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR) rotate_check_box_style = { "": {"background_color": 0x0, "image_url": f"{ICON_PATH}/radio_off.svg", "image_width":32, "image_height":32}, ":checked": {"image_url": f"{ICON_PATH}/radio_on.svg"} } with self._rotate_order_drop_down_menu.frame: collection = ui.RadioCollection() with ui.VStack(): for index in range(len(USDXformOpRotateWidget.ROTATE_ORDERS)): rotate_order = USDXformOpRotateWidget.ROTATE_ORDERS[index] #OM-94393 let the radio button decide the height and style with ui.HStack(mouse_pressed_fn=(lambda x, y, b, m, index=index: self._change_rotation_order(index)), height=0): ui.RadioButton(style=rotate_check_box_style, radio_collection=collection, aligment=ui.Alignment.LEFT, height=20) ui.Label(rotate_order) if rotate_order == order: collection.model.set_value(index) def rebuild(self): attr = self._stage.GetObjectAtPath(self._attr_path) # if attr.GetResolveInfo().ValueIsBlocked(): # return attr_name = attr.GetName() if not attr_name.startswith("xformOp:rotate"): carb.log_warn(f"Object {self._path} is not an xformOp:rotate attribute ") return # is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) label_name = self.display_name(attr_name) rotate_names = attr.SplitName() rotate_order = "ZYX" if len(rotate_names) > 1: rotate_order = rotate_names[1].split("rotate", 1)[1] # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) self._model = [] for i in range(3): self._model.append( GfVecAttributeSingleChannelModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], i, False, metadata, False, ) ) vec_model = GfVecAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], 3, type_name.type, False, metadata, ) if len(self._prim_paths) == 1: setattr(vec_model,'transform_widget', self) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) label = None with ui.HStack(): if len(self._prim_paths) == 1: with ui.ZStack(width=LABEL_PADDING): label_tooltip = label_tooltip + "\nRight click it to disable or delete it. \nLeft click it to change the rotate order, default is XYZ." # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) # We use a label + a triangle to hack a combo box that are closer to the design label_h_stack = ui.HStack(width=LABEL_PADDING) label_h_stack.set_mouse_pressed_fn(lambda x, y, b, m, order=rotate_order, parent_widget=label_h_stack: self._on_mouse_click(b,parent_widget,order)) with label_h_stack: label = HighlightLabel( label_name, name="title", tooltip=label_tooltip, width = 35, **self._label_kwargs, ) self._create_inverse_widgets() ui.Spacer(width=5) # use this triangle to simulate a combo box with ui.VStack(): ui.Spacer(height=10) ui.Triangle(name="default",width=8,height=6,style={"background_color":0xFF9E9E9E},alignment=ui.Alignment.CENTER_BOTTOM) else: with ui.HStack(width=LABEL_PADDING): label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) ui.Spacer() self._create_inverse_widgets() with ui.HStack(): range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) kwargs = {"min": range_min, "max": range_max, "step": 1.0} UsdPropertiesWidgetBuilder._create_float_drag_per_channel_with_labels_and_control( models = self._model, metadata = metadata, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], kwargs = kwargs ) #The vec_model is useful when we set the key for all three components together self._model.append(vec_model) UsdPropertiesWidgetBuilder._create_attribute_context_menu(label, vec_model) #this class is used for rotateX, rotateY, rotateZ, but it's not working properly, and produce error when displayed. # https://omniverse-jirasw.nvidia.com/browse/OMFP-2491 #disabling coverage for this code class USDXformOpRotateScalarWidget(USDXformOpWidget): # pragma: no cover @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Rotate" if suffix: label_name = label_name + ":" + suffix return label_name def rebuild(self): attr = self._stage.GetObjectAtPath(self._attr_path) # if attr.GetResolveInfo().ValueIsBlocked(): # return attr_name = attr.GetName() if not attr_name.startswith("xformOp:rotate"): carb.log_warn(f"Object {self._path} is not an xformOp:rotate attribute ") return # is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) label_name = self.display_name(attr_name) rotate_names = attr.SplitName() rotate_order = "X" if len(rotate_names) > 1: rotate_order = rotate_names[1].split("rotate", 1)[1] # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) self._model = UsdAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], False, metadata ) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: with ui.ZStack(): label_tooltip = label_tooltip + "\nRight click it to disable or delete it. " # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) else: HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) self._create_inverse_widgets() ui.Spacer(width=2) stack_names = {"X":"rotate_scalar_stack_x", "Y":"rotate_scalar_stack_y", "Z":"rotate_scalar_stack_z"} rotate_scalar_stack = ui.HStack(identifier = stack_names[rotate_order]) with rotate_scalar_stack: colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F} with ui.ZStack(): with ui.HStack(): range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) widget_kwargs = {"model": self._model, "step": 1} if range_min < range_max: widget_kwargs["min"] = range_min widget_kwargs["max"] = range_max UsdPropertiesWidgetBuilder._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs) UsdPropertiesWidgetBuilder._create_control_state(self._model) with ui.HStack(): with ui.ZStack(width=14): ui.Rectangle( name="vector_label", style={ "background_color": colors[rotate_order], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(rotate_order, name="vector_label", alignment=ui.Alignment.CENTER) class USDXformOpScaleWidget(USDXformOpWidget): @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Scale" if suffix: label_name = label_name + ":" + suffix return label_name def __init__( self, prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, parent_widget, label_kwargs=None ): self._parent_widget = parent_widget super().__init__( prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs ) def rebuild(self): # The scale widget uses a modified version of the single channel model that supports # scaling each component of the vector uniformly. # If link_channels is False, the single channel model behaves as usual. class GfVecLinkableModel(GfVecAttributeSingleChannelModel): def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], channel_index: int, self_refresh: bool, metadata: dict, change_on_edit_end=False, link_channels=False, **kwargs ): self._link_channels = link_channels super().__init__(stage, attribute_paths, channel_index, self_refresh, metadata, change_on_edit_end, **kwargs) def set_value(self, value): if self._link_channels: vec_value = copy.copy(self._value) for i in range(3): vec_value[i] = value if UsdBase.set_value(self, vec_value, -1): self._value_changed() else: super().set_value(value) def set_default(self, comp=-1): if self._link_channels: value = self._default_value[self._channel_index] vec_value = copy.copy(self._value) for i in range(3): vec_value[i] = value if UsdBase.set_value(self, vec_value, -1): self._value_changed() else: super().set_default(comp) attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:scale"): carb.log_warn(f"Object {self._path} is not an xformOp:scale attribute ") return # is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) label_name = self.display_name(attr_name) # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) self._model = [] for i in range(3): self._model.append( GfVecLinkableModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], i, False, metadata, False, self._parent_widget._link_scale ) ) vec_model = GfVecAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], 3, type_name.type, False, metadata, ) if len(self._prim_paths) == 1: setattr(vec_model,'transform_widget', self) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) label = None with ui.HStack(): with ui.HStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: with ui.ZStack(): label_tooltip = label_tooltip + "\nRight click it for more options." # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) else: label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) self._create_inverse_widgets() if self._parent_widget._link_scale: button_style = { "color": 0xFF34B5FF, "background_color": 0x0, "Button.Image": {"image_url": f"{ICON_PATH}/link_on.svg"}, ":hovered": {"color": 0xFFACDCF9} } else: button_style = { "color": 0x66FFFFFF, "background_color": 0x0, "Button.Image": {"image_url": f"{ICON_PATH}/link_off.svg"}, ":hovered": {"color": 0xFFFFFFFF} } with ui.ZStack(content_clipping = True, width=25, height=25): ui.Button("", style = button_style, clicked_fn = self._parent_widget._toggle_link_scale, identifier = "toggle_link_scale", tooltip = "Toggle link scale") ui.Spacer(width=70) scale_stack = ui.HStack(identifier = "scale_t_stack") with scale_stack: range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) kwargs = {"min": range_min, "max": range_max, "step": 1.0} UsdPropertiesWidgetBuilder._create_float_drag_per_channel_with_labels_and_control( models = self._model, metadata = metadata, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], kwargs = kwargs ) #The vec_model is useful when we set the key for all three components together self._model.append(vec_model) UsdPropertiesWidgetBuilder._create_attribute_context_menu(label, vec_model) class USDXformOpOrientWidget(USDXformOpWidget): @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Orient" if suffix: label_name = label_name + ":" + suffix return label_name def __init__( self, prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs=None, ): self._settings = carb.settings.get_settings() if self._settings: if self._settings.get("/persistent/app/uiSettings/DisplayOrientAsRotate") is None: self._settings.set_default_bool("/persistent/app/uiSettings/DisplayOrientAsRotate", True) self._display_orient_as_rotate = self._settings.get_as_bool( "/persistent/app/uiSettings/DisplayOrientAsRotate" ) super().__init__( prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs, ) def _build_orient_widgets(self, attr, attr_name, type_name, label_name, label_tooltip, metadata): self._model = GfQuatAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], type_name.type, False, metadata ) with ui.HStack(): kwargs = {"min": -1, "max": 1, "step": 0.01} value_widget, mixed_overlay = UsdPropertiesWidgetBuilder._create_multi_float_drag_with_labels( self._model, comp_count=4, labels=[("W", 0xFFAA5555), ("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], **kwargs, ) value_widget.identifier = f"orient_{attr_name}" UsdPropertiesWidgetBuilder._create_control_state(self._model, value_widget, mixed_overlay) def _build_euler_widgets(self, attr, attr_name, type_name, label_name, label_tooltip, metadata): self._euler_model = GfQuatEulerAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], type_name.type, False, metadata ) with ui.HStack(): kwargs = {"min": -360, "max": 360, "step": 1} value_widget, mixed_overlay = UsdPropertiesWidgetBuilder._create_multi_float_drag_with_labels( self._euler_model, comp_count=3, labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], **kwargs, ) value_widget.identifier = f"euler_{attr_name}" UsdPropertiesWidgetBuilder._create_control_state(self._euler_model, value_widget, mixed_overlay) def _build_header(self, attr, attr_name, type_name, label_name, label_tooltip, metadata): with ui.ZStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: label_tooltip = label_tooltip + "\nDisplay Orient As Euler Angles. \nRight click to disable or delete it. \nLeft click to switch between Orient & Euler Angles." # A black rect background indicates the Orient is not original data format _rect = ui.Rectangle( style={ "Rectangle:hovered": {"background_color": 0xFF444444}, "Rectangle": {"background_color": 0xFF333333}, }, tooltip=label_tooltip, ) # _rect = ui.Rectangle(tooltip=label_tooltip) _rect.set_mouse_pressed_fn(lambda x, y, b, m: self._show_right_click_menu(b)) # TODO: Replace this hack when OM-24290 is fixed with ui.ZStack(): _button = ui.Button( label_name, name="title", width=50, tooltip=label_tooltip if len(self._prim_paths) > 1 else "", style=euler_view_button_style if self._display_orient_as_rotate else quat_view_button_style, ) _button.set_mouse_pressed_fn( lambda x, y, b, m, widget=_button: self._on_orient_button_clicked(b, widget) ) self._create_inverse_widgets() with ui.HStack(): ui.Spacer(width=35) ui.Image(f"{ICON_PATH}/orient_button.svg", width=10, alignment=ui.Alignment.CENTER) def rebuild(self): # attr & attr_name attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:orient"): carb.log_warn(f"Object {self._path} is not an xformOp:orient attribute ") return # metadata metadata = attr.GetAllMetadata() # type_name type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) # label_name label_name = self.display_name(attr_name) # label_tooltip label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) with ui.HStack(): self._build_header(attr, attr_name, type_name, label_name, label_tooltip, metadata) # Create two views, Quaternion view & Euler Angle view # self._display_orient_as_rotate True: Euler Angle view, False: Quaternion view with ui.ZStack(): # Quaternion view is default on self._quat_view = ui.Frame(visible=False if self._display_orient_as_rotate else True) with self._quat_view: self._build_orient_widgets(attr, attr_name, type_name, label_name, label_tooltip, metadata) # Euler view is default off self._euler_view = ui.Frame(visible=True if self._display_orient_as_rotate else False) with self._euler_view: self._build_euler_widgets(attr, attr_name, type_name, label_name, label_tooltip, metadata) class USDXformOpTransformWidget(USDXformOpWidget): @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Transform" if suffix: label_name = label_name + ":" + suffix return label_name def rebuild(self): attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:transform"): carb.log_warn(f"Object {self._path} is not an xformOp:transform attribute ") return # is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) label_name = self.display_name(attr_name) # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) self._model = GfMatrixAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], 4, type_name.type, False, metadata, ) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: with ui.ZStack(): label_tooltip = label_tooltip + "\nRight click it to disable or delete it." # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) else: HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) self._create_inverse_widgets() ui.Spacer(width=2) with ui.HStack(): range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) # TODO: make step default to 1.0 before the adaptive stepping solution is available step = 1.0 self._create_multi_float_drag_matrix_with_labels( self._model, 4, range_min, range_max, step, [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFAA5555)], ) wgs_coord = get_wgs84_coords("", self._prim_paths[0].pathString) if len(wgs_coord) > 0: #pragma no cover OM-112507 with ui.HStack(): with ui.HStack(width=LABEL_PADDING): label = ui.Label("WGS84", name="title", tooltip=label_tooltip) ui.Spacer(width=2) with ui.HStack(): with ui.VStack(): all_axis = ["Lat", "Lon", "Alt"] colors = {"Lat": 0xFF5555AA, "Lon": 0xFF76A371, "Alt": 0xFFA07D4F} component_index = 0 for axis in all_axis: with ui.HStack(): with ui.HStack(width=LABEL_PADDING): label = ui.Label("", name="title", tooltip=label_tooltip) with ui.ZStack(width=20): ui.Rectangle( width=20, height=20, style={ "background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(axis, name="wgs84_label", alignment=ui.Alignment.CENTER) # NOTE: Updating the WGS84 values does not update the transform translation, # so make the input fields read-only for now. # See https://nvidia-omniverse.atlassian.net/browse/OM-64348 ui.FloatDrag(TransformWatchModel(component_index, self._stage), enabled=False) component_index = component_index + 1 class USDResetXformStackWidget(USDXformOpWidget): def rebuild(self): is_reset_xform_stack_op = xform_op_utils.is_reset_xform_stack_op(self._op_name) if not is_reset_xform_stack_op: return label_name = "ResetXformStack" label_tooltip = "Invalid all above xformOp and parent transform. Calulate world transform from the op below." self._model = None with ui.HStack(): with ui.HStack(width=LABEL_PADDING): ui.Label( label_name, name="title", tooltip=label_tooltip, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) ui.Spacer(width=5) with ui.HStack(): with ui.VStack(): ui.Spacer() color = 0xFF888888 if self._is_valid_op else 0xFF444444 ui.Line( name="ResetXformStack", height=2, style={"color": color, "border_width": 0.5, "alignment": ui.Alignment.BOTTOM}, alignment=ui.Alignment.BOTTOM, ) ui.Spacer() class USDNoAttributeOpWidget(USDXformOpWidget): def rebuild(self): if self._op_name is None: return label_name = self._op_name self._model = None is_valid_op_name = xform_op_utils.is_valid_op_name(self._op_name) op_attr_name = xform_op_utils.get_op_attr_name(self._op_name) label_error = ( f"Could not find attribute {op_attr_name} for this xformOp." if is_valid_op_name else "Invalid xformOp name!" ) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): ui.Label(label_name, name="title", mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b))) ui.Spacer(width=5) with ui.HStack(): ui.Label(label_error, name="title") class OperationTypes(Enum): ADD = 0 MULTIPLY = 1 INVALID = 2 class TransformWidgets: def __init__(self, parent_widget): self._settings = carb.settings.get_settings() self._clear_widgets() self._parent_widget = parent_widget self._offset_index = -1 self._old_transform = "" self._active_fields = 0 self._dragging = False self._tab_swap = 0 def __del__(self): self._clear_widgets() def _clear_widgets(self): self._stage = None self._widgets = [] self._models = defaultdict(list) def _create_xform_op_widget( self, prim_paths, collapsable_frame, stage, attr, op_name=None, is_valid_op=False, op_order_attr=None, op_order_index=-1, ): op_order_path = op_order_attr.GetPath() if op_order_attr is not None and op_order_attr else None if xform_op_utils.is_reset_xform_stack_op(op_name): return USDResetXformStackWidget( prim_paths, collapsable_frame, stage, None, op_name, is_valid_op, op_order_path, op_order_index ) if not attr: return USDNoAttributeOpWidget( prim_paths, collapsable_frame, stage, None, op_name, is_valid_op, op_order_path, op_order_index ) attr_name = attr.GetName() def match(label): return self._parent_widget._filter.matches(label) highlight = self._parent_widget._filter.name label_kwargs = {"highlight": highlight} if attr_name.startswith("xformOp:translate") and match(USDXformOpTranslateWidget.display_name(attr_name)): return USDXformOpTranslateWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) elif attr_name.startswith("xformOp:rotate") and match(USDXformOpRotateWidget.display_name(attr_name)): op_type_name = xform_op_utils.get_op_type_name(attr_name) if len(op_type_name.split("rotate", 1)[1]) == 3: return USDXformOpRotateWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) elif len(op_type_name.split("rotate", 1)[1]) == 1: return USDXformOpRotateScalarWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) elif attr_name.startswith("xformOp:orient") and match(USDXformOpOrientWidget.display_name(attr_name)): return USDXformOpOrientWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) elif attr_name.startswith("xformOp:scale") and match(USDXformOpScaleWidget.display_name(attr_name)): return USDXformOpScaleWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, self._parent_widget, label_kwargs, ) elif attr_name.startswith("xformOp:transform") and match(USDXformOpTransformWidget.display_name(attr_name)): return USDXformOpTransformWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) return None def _get_common_xformop(self, prim_paths): def _get_xformop_order(stage, prim_path): prim = stage.GetPrimAtPath(prim_path) if not prim: return [] order_attr = prim.GetAttribute("xformOpOrder") if not order_attr: return [] xform_op_order = order_attr.Get() if not xform_op_order: return [] return xform_op_order common_xformOp_order = [ \ "xformOp:translate","xformOp:scale","xformOp:rotateX", \ "xformOp:rotateY","xformOp:rotateZ","xformOp:rotateXYZ", \ "xformOp:rotateXZY","xformOp:rotateYXZ","xformOp:rotateYZX", \ "xformOp:rotateZXY","xformOp:rotateZYX","xformOp:orient","xformOp:transform" ] all_empty_xformOp = True for prim_path in prim_paths: xformOp_order = _get_xformop_order(self._stage, prim_path) common_xformOp_order = list(set(common_xformOp_order) & set(xformOp_order)) all_empty_xformOp &= (len(xformOp_order) == 0) return common_xformOp_order, all_empty_xformOp def _create_multi_string_with_labels(self, ui_widget, model, labels, comp_count): # This is similar to the multi_float_drag function above, but without USD backing and using a given single # field (draggable float and string, for offset mode we need to do some string parsing to look for math operations) RECT_WIDTH = 13 SPACING = 4 value_widget = [] with ui.ZStack(): with ui.HStack(): ui.Spacer(width=RECT_WIDTH) items = model.get_item_children(self) for i in range(comp_count): if i !=0: ui.Spacer(width=RECT_WIDTH) field = model.get_item_value_model(items[i], i) value_widget.append(ui_widget(field)) with ui.HStack(): for i in range(comp_count): if i != 0: ui.Spacer(width=SPACING) label = labels[i] with ui.ZStack(width=RECT_WIDTH + 1): ui.Rectangle(name="vector_label", style={"background_color": label[1]}) ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER) ui.Spacer() return value_widget # Two sets of fields are generated, FloatDrags are visible dragging and StringFields are visible during keyboard input # These functions ensure the correct fields are visible and active when single clicking, double clicking, and tab selecting def _on_double_click(self, transform): self._dragging = False float_widget = self._get_widget(transform)[0] string_widget = self._get_widget(transform)[1] for widget in float_widget: widget.visible = False for widget in string_widget: widget.visible = True async def focus(field): await omni.kit.app.get_app().next_update_async() field.focus_keyboard() string_widget[self._offset_index].focus_keyboard() asyncio.ensure_future(focus(string_widget[self._offset_index])) if self._tab_swap == 1: self._active_fields -= 1 def _on_press(self): self._dragging = True self._tab_swap = 0 if self._active_fields < 0: self._active_fields = 0 def _start_field_edit(self, index, transform): self._offset_index = index self._active_fields += 1 self._old_transform = transform self._settings.set(TRANSFORM_OP_SETTING, transform) float_widget = self._get_widget(transform)[0] if float_widget[index].visible == True and self._dragging == False: self._tab_swap += 1 self._on_double_click(transform) def _swapping(self, transform): if transform == self._old_transform: return False else: return True async def _end_string_edit(self, transform): self._active_fields -= 1 if self._swapping(transform): if self._get_widget(transform)[0][0].visible == False: for widget in self._get_widget(transform)[1]: widget.visible = False for widget in self._get_widget(transform)[0]: widget.visible = True # Swap back to FloatDrag fields if the user clicks off await asyncio.sleep(.3) if self._active_fields < 1: if self._get_widget(transform)[0][0].visible == False: for widget in self._get_widget(transform)[1]: widget.visible = False for widget in self._get_widget(transform)[0]: widget.visible = True def _get_widget(self, transform): if transform == TRANSFORM_OP_MOVE: return self._float_translate_widget, self._string_translate_widget elif transform == TRANSFORM_OP_ROTATE: return self._float_rotate_widget, self._string_rotate_widget else: return self._float_scale_widget, self._string_scale_widget def _get_offset_data(self, text: str): # See if input looks like "[op] [number]", for the four supported operations try: text = text.replace(" ", "") if len(text) > 0: operator = text[0] value = float(text[1:]) if operator == '*': return OperationTypes.MULTIPLY, value elif operator == '/': return OperationTypes.MULTIPLY, 1.0 / value elif operator == '+': return OperationTypes.ADD, value elif operator == '-': return OperationTypes.ADD, -value except ValueError: pass # If we didn't find an operation, see if the input is just a number try: value = float(text) return OperationTypes.ADD, value except ValueError: return OperationTypes.INVALID, 0.0 def _on_translate_offset(self, offset_text: str, index: int, stage: Usd.Stage, prim_paths: List[Sdf.Path]): operation, offset_value = self._get_offset_data(offset_text) if operation is OperationTypes.INVALID: carb.log_warn("Unrecognized input provided to offset field. No operation will be applied.") elif stage: with omni.kit.undo.group(): for path in prim_paths: prim = stage.GetPrimAtPath(path) prim_world_xform = omni.usd.get_world_transform_matrix(prim) success, scale_orient_mat, scale, rotation_mat, translation, persp_mat = prim_world_xform.Factor() scale_mat = Gf.Matrix4d().SetScale(scale) local = self._settings.get(TRANSFORM_MOVE_MODE_SETTING) is None or \ self._settings.get_as_string(TRANSFORM_MOVE_MODE_SETTING) != TRANSFORM_MODE_GLOBAL if operation is OperationTypes.ADD: if local: offset_vec = Gf.Vec3d([offset_value if i == index else 0 for i in range(3)]) offset_mat = Gf.Matrix4d().SetTranslate(offset_vec) translation_mat = Gf.Matrix4d().SetTranslate(translation) translation = (offset_mat * rotation_mat * translation_mat).ExtractTranslation() else: translation[index] += offset_value elif operation is OperationTypes.MULTIPLY: if local: offset_vec = Gf.Vec3d([offset_value if i == index else 1 for i in range(3)]) offset_mat = Gf.Matrix4d().SetScale(offset_vec) translation_mat = Gf.Matrix4d().SetTranslate(translation) # Rotate translation into local frame, apply the scale there, rotate back out translation = (translation_mat * rotation_mat.GetTranspose() * offset_mat * rotation_mat).ExtractTranslation() else: translation[index] *= offset_value translation_mat = Gf.Matrix4d().SetTranslate(translation) prim_world_xform = scale_orient_mat * scale_mat * scale_orient_mat.GetTranspose() * rotation_mat * translation_mat parent_world_xform = omni.usd.get_world_transform_matrix(prim.GetParent()) prim_local_xform = prim_world_xform * parent_world_xform.GetInverse() omni.kit.commands.execute("TransformPrimCommand", path = path, new_transform_matrix = prim_local_xform) asyncio.ensure_future(self._end_string_edit(TRANSFORM_OP_MOVE)) def _on_rotate_offset(self, offset_text: str, index: int, stage: Usd.Stage, prim_paths: List[Sdf.Path]): operation, offset_value = self._get_offset_data(offset_text) if operation is OperationTypes.INVALID: carb.log_warn("Unrecognized input provided to offset field. No operation will be applied.") elif stage: with omni.kit.undo.group(): for path in prim_paths: prim = stage.GetPrimAtPath(path) prim_world_xform = omni.usd.get_world_transform_matrix(prim) success, scale_orient_mat, scale, rotation_mat, translation, persp_mat = prim_world_xform.Factor() scale_mat = Gf.Matrix4d().SetScale(scale) local = self._settings.get(TRANSFORM_ROTATE_MODE_SETTING) is None or \ self._settings.get_as_string(TRANSFORM_ROTATE_MODE_SETTING) != TRANSFORM_MODE_GLOBAL if operation is OperationTypes.ADD: axis = Gf.Vec3d([1 if i == index else 0 for i in range(3)]) offset_r = Gf.Rotation(axis, offset_value) offset_mat = Gf.Matrix4d().SetRotate(offset_r.GetQuat()) if local: rotation_mat = offset_mat * rotation_mat else: rotation_mat = rotation_mat * offset_mat translation_mat = Gf.Matrix4d().SetTranslate(translation) prim_world_xform = scale_orient_mat * scale_mat * scale_orient_mat.GetTranspose() * rotation_mat * translation_mat parent_world_xform = omni.usd.get_world_transform_matrix(prim.GetParent()) prim_local_xform = prim_world_xform * parent_world_xform.GetInverse() omni.kit.commands.execute("TransformPrimCommand", path = path, new_transform_matrix = prim_local_xform) elif operation is OperationTypes.MULTIPLY: # rotation-multiply is unlike the other offsets because it we need to know the component of the # current rotation about a particular axis in order to scale it, but a rotation's component along # one axis can be different depending on the representation (e.g. different euler angle orderings). # Rather than deal with that, we'll just look for the prim's current rotation values # and scale the specified component. scale, rotation, order, translation = omni.usd.get_local_transform_SRT(prim) rotation[index] *= offset_value omni.kit.commands.execute("TransformPrimSRTCommand", path = path, new_rotation_euler = rotation) asyncio.ensure_future(self._end_string_edit(TRANSFORM_OP_ROTATE)) def _on_scale_offset(self, offset_text: str, index: int, stage: Usd.Stage, prim_paths: List[Sdf.Path]): operation, offset_value = self._get_offset_data(offset_text) if operation is OperationTypes.INVALID: carb.log_warn("Unrecognized input provided to offset field. No operation will be applied.") elif stage: with omni.kit.undo.group(): for path in prim_paths: prim = stage.GetPrimAtPath(path) prim_world_xform = omni.usd.get_world_transform_matrix(prim) success, scale_orient_mat, scale, rotation_mat, translation, persp_mat = prim_world_xform.Factor() if operation is OperationTypes.ADD: if self._parent_widget._link_scale: scale = ((scale[index] + offset_value) / scale[index]) * scale else: scale[index] += offset_value elif operation is OperationTypes.MULTIPLY: if self._parent_widget._link_scale: scale = offset_value * scale else: scale[index] *= offset_value scale_mat = Gf.Matrix4d().SetScale(scale) translation_mat = Gf.Matrix4d().SetTranslate(translation) prim_world_xform = scale_orient_mat * scale_mat * scale_orient_mat.GetTranspose() * rotation_mat * translation_mat parent_world_xform = omni.usd.get_world_transform_matrix(prim.GetParent()) prim_local_xform = prim_world_xform * parent_world_xform.GetInverse() omni.kit.commands.execute("TransformPrimCommand", path = path, new_transform_matrix = prim_local_xform) asyncio.ensure_future(self._end_string_edit(TRANSFORM_OP_SCALE)) def build_transform_frame(self, prim_paths, collapsable_frame, stage): self._clear_widgets() # Transform Frame if stage is None or len(prim_paths) <= 0 or prim_paths is None: return None, False prim_path = prim_paths[0] prim = stage.GetPrimAtPath(prim_path) if not prim or not prim.IsA(UsdGeom.Xformable): return None, False self._stage = stage xform = UsdGeom.Xformable(prim) # if xformOpOrder is absent or an empty array don't return # we may still have xformOp that are not listed in the xformOpOrder order_attr = prim.GetAttribute("xformOpOrder") if not order_attr: xform_op_order = [] xform_op_order = order_attr.Get() if xform_op_order is None: xform_op_order = [] # when select more than two prim, get common xformop to show if len(prim_paths) > 1: common_xformop, all_empty_xformop = self._get_common_xformop(prim_paths) for index, op_name in enumerate(common_xformop): attr_name = xform_op_utils.get_op_attr_name(op_name) attr = Usd.Attribute() if attr_name is not None: attr = prim.GetAttribute(attr_name) widget = self._create_xform_op_widget( prim_paths, collapsable_frame, stage, attr, op_name, True, order_attr, index ) if widget is not None: self._widgets.append(widget) model = widget._model #if it is a list the last one is the vector model if isinstance(model, list): for m in model: if m is not None: for sdf_path in m.get_attribute_paths(): self._models[sdf_path].append(m) elif model is not None: for sdf_path in model.get_attribute_paths(): self._models[sdf_path].append(model) if isinstance(widget, USDXformOpOrientWidget): if widget._euler_model is not None: for sdf_path in widget._euler_model.get_attribute_paths(): self._models[sdf_path].append(widget._euler_model) return self._models, all_empty_xformop attr_xform_op_order = xform.GetXformOpOrderAttr() xform_ops = xform.GetOrderedXformOps() has_reset_xform_stack = xform.GetResetXformStack() reset_index = -1 if has_reset_xform_stack: for i in range(len(xform_op_order) - 1, -1, -1): if xform_op_utils.is_reset_xform_stack_op(xform_op_order.__getitem__(i)): reset_index = i break attr_xform_ops = [] for index, op_name in enumerate(xform_op_order): attr_name = xform_op_utils.get_op_attr_name(op_name) if attr_name is not None: attr = prim.GetAttribute(attr_name) if attr: attr_xform_ops.append(attr) attrs_all = [attr for attr in prim.GetAttributes() if not attr.IsHidden()] attr_not_in_order_xform_ops = list( attr for attr in attrs_all if (attr.GetName().startswith("xformOp:") and not attr in attr_xform_ops) ) if len(xform_op_order) + len(attr_not_in_order_xform_ops) > 0: with ui.VStack(spacing=8, name="frame_v_stack"): ui.Spacer(height=0) for index, op_name in enumerate(xform_op_order): is_valid_op = index >= reset_index and xform_op_utils.is_valid_op_name(op_name) attr_name = xform_op_utils.get_op_attr_name(op_name) attr = Usd.Attribute() if attr_name is not None: attr = prim.GetAttribute(attr_name) widget = self._create_xform_op_widget( prim_paths, collapsable_frame, stage, attr, op_name, is_valid_op, order_attr, index ) if widget is not None: self._widgets.append(widget) # self._models.append(widget._model) model = widget._model if isinstance(model, list): for m in model: if m is not None: for sdf_path in m.get_attribute_paths(): self._models[sdf_path].append(m) elif model is not None: for sdf_path in model.get_attribute_paths(): self._models[sdf_path].append(model) if isinstance(widget, USDXformOpOrientWidget): if widget._euler_model is not None: for sdf_path in widget._euler_model.get_attribute_paths(): self._models[sdf_path].append(widget._euler_model) if len(attr_not_in_order_xform_ops) > 0: ui.Separator() for attr in attr_not_in_order_xform_ops: widget = self._create_xform_op_widget(prim_paths, collapsable_frame, stage, attr) if widget is not None: self._widgets.append(widget) ui.Spacer(height=0) return self._models, False def build_transform_offset_frame(self, prim_paths, collapsable_frame, stage): self._clear_widgets() translate_model = VecAttributeModel( default_value = "0.0", begin_edit_callback = functools.partial(self._start_field_edit, transform=TRANSFORM_OP_MOVE), end_edit_callback = functools.partial(self._on_translate_offset, stage=stage, prim_paths=prim_paths) ) rotate_model = VecAttributeModel( default_value = "0.0", begin_edit_callback = functools.partial(self._start_field_edit, transform=TRANSFORM_OP_ROTATE), end_edit_callback = functools.partial(self._on_rotate_offset, stage=stage, prim_paths=prim_paths) ) scale_model = VecAttributeModel( default_value = "0.0", begin_edit_callback = functools.partial(self._start_field_edit, transform=TRANSFORM_OP_SCALE), end_edit_callback = functools.partial(self._on_scale_offset, stage=stage, prim_paths=prim_paths) ) def match(label): return self._parent_widget._filter.matches(label) highlight = self._parent_widget._filter.name label_kwargs = {"highlight": highlight} HEIGHT_SPACE = 8 with ui.VStack(): if match("Translate"): self._parent_widget._any_item_visible = True ui.Spacer(height = HEIGHT_SPACE) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): HighlightLabel("Translate", name="title", **label_kwargs) ui.Spacer(width=2) translate_stack = ui.HStack(identifier = "translate_stack") with translate_stack: with ui.ZStack(): kwargs = {"step": 1.0} self._string_translate_widget = self._create_multi_string_with_labels( ui_widget = ui.StringField, model = translate_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) for widget in self._string_translate_widget: widget.visible = False self._float_translate_widget = self._create_multi_string_with_labels( ui_widget = ui.FloatDrag, model = translate_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) translate_stack.set_mouse_double_clicked_fn(lambda x, y, b, m: self._on_double_click(TRANSFORM_OP_MOVE)) translate_stack.set_mouse_pressed_fn(lambda x, y, b, m: self._on_press()) if match("Rotate"): self._parent_widget._any_item_visible = True ui.Spacer(height = HEIGHT_SPACE) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): HighlightLabel("Rotate", name="title", **label_kwargs) ui.Spacer(width=2) rotate_stack = ui.HStack(identifier = "rotate_stack") with rotate_stack: with ui.ZStack(): kwargs = {"step": 1.0} self._string_rotate_widget = self._create_multi_string_with_labels( ui_widget = ui.StringField, model = rotate_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) for widget in self._string_rotate_widget: widget.visible = False self._float_rotate_widget = self._create_multi_string_with_labels( ui_widget = ui.FloatDrag, model = rotate_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) rotate_stack.set_mouse_double_clicked_fn(lambda x, y, b, m: self._on_double_click(TRANSFORM_OP_ROTATE)) rotate_stack.set_mouse_pressed_fn(lambda x, y, b, m: self._on_press()) if match("Scale"): self._parent_widget._any_item_visible = True ui.Spacer(height = HEIGHT_SPACE) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): HighlightLabel("Scale", name="title", **label_kwargs) if self._parent_widget._link_scale: button_style = { "color": 0xFF34B5FF, "background_color": 0x0, "Button.Image": {"image_url": f"{ICON_PATH}/link_on.svg"}, ":hovered": {"color": 0xFFACDCF9} } else: button_style = { "color": 0x66FFFFFF, "background_color": 0x0, "Button.Image": {"image_url": f"{ICON_PATH}/link_off.svg"}, ":hovered": {"color": 0xFFFFFFFF} } with ui.ZStack(content_clipping = True, width=25, height=25): ui.Button("", style = button_style, clicked_fn = self._parent_widget._toggle_link_scale, identifier = "toggle_link_offset_scale", tooltip = "Toggle link scale") ui.Spacer(width=70) scale_stack = ui.HStack(identifier = "scale_stack") with scale_stack: with ui.ZStack(): kwargs = {"step": 1.0} self._string_scale_widget = self._create_multi_string_with_labels( ui_widget = ui.StringField, model = scale_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) for widget in self._string_scale_widget: widget.visible = False self._float_scale_widget = self._create_multi_string_with_labels( ui_widget = ui.FloatDrag, model = scale_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) scale_stack.set_mouse_double_clicked_fn(lambda x, y, b, m: self._on_double_click(TRANSFORM_OP_SCALE)) scale_stack.set_mouse_pressed_fn(lambda x, y, b, m: self._on_press()) return None
83,413
Python
46.71968
309
0.534593
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/__init__.py
from .transform_properties import *
36
Python
17.499991
35
0.805556
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_properties.py
import os import carb import omni.ext from pxr import Sdf, UsdLux, UsdGeom, Gf from pathlib import Path from functools import partial from .transform_widget import TransformAttributeWidget from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload from . import transform_builder import omni.ui as ui from .transform_commands import * from . import xform_op_utils TEST_DATA_PATH = "" g_ext = None class TransformPropertyExtension(omni.ext.IExt): def __init__(self): self._registered = False super().__init__() def on_startup(self, ext_id): manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) transform_builder.ICON_PATH = Path(extension_path).joinpath("data").joinpath("icons") global TEST_DATA_PATH TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("test_data") self._register_widget() self._register_context_menu() from omni.kit.property.usd import PrimPathWidget self._add_button_menu = [] context_menu = omni.kit.context_menu.get_instance() if context_menu is None: carb.log_error("context_menu is disabled!") return None self._settings = carb.settings.get_settings() self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Translate, Rotate, Scale", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=True, add_rotateXYZ_op=True, add_orient_op=False, add_scale_op=True, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Translate, Orient, Scale", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=True, add_rotateXYZ_op=False, add_orient_op=True, add_scale_op=True, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Transform", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=False, add_orient_op=False, add_scale_op=False, add_transform_op=True) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Pivot", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=False, add_orient_op=False, add_scale_op=False, add_transform_op=False, add_pivot=True) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Translate", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=True, add_rotateXYZ_op=False, add_orient_op=False, add_scale_op=False, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Rotate", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=True, add_orient_op=False, add_scale_op=False, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Orient", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=False, add_orient_op=True, add_scale_op=False, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Scale", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=False, add_orient_op=False, add_scale_op=True, add_transform_op=False) ) ) # set ext global g_ext g_ext = self def on_shutdown(self): # pragma: no cover if self._registered: self._unregister_widget() # release menu item(s) from omni.kit.property.usd import PrimPathWidget for item in self._add_button_menu: PrimPathWidget.remove_button_menu_entry(item) # release context menu items self._unregister_context_menu() #clear global g_ext g_ext = None def _add_xform_op( self, payload: PrimSelectionPayload, add_translate_op: bool, add_rotateXYZ_op: bool, add_orient_op: bool, add_scale_op: bool, add_transform_op: bool, add_pivot = False ): # Retrieve the default precision default_xform_op_precision = self._settings.get("/persistent/app/primCreation/DefaultXformOpPrecision") if default_xform_op_precision is None: self._settings.set_default_string( "/persistent/app/primCreation/DefaultXformOpPrecision", "Double" ) default_xform_op_precision = "Double" _precision = None if default_xform_op_precision == "Double": _precision = UsdGeom.XformOp.PrecisionDouble elif default_xform_op_precision == "Float": _precision = UsdGeom.XformOp.PrecisionFloat elif default_xform_op_precision == "Half": _precision = UsdGeom.XformOp.PrecisionHalf # No operation is carried out if precision is not properly set if _precision is None: carb.log_error("The default xform op precision is not properly set! Please set it in the Edit/Preferences/Stage window!") return # Retrieve the default rotation order default_rotation_order = self._settings.get("/persistent/app/primCreation/DefaultRotationOrder") if default_rotation_order is None: self._settings.set_default_string("persistent/app/primCreation/DefaultRotationOrder", "XYZ") default_rotation_order = "XYZ" omni.kit.commands.execute("AddXformOp", payload=payload, precision=_precision, rotation_order = default_rotation_order, add_translate_op = add_translate_op, add_rotateXYZ_op = add_rotateXYZ_op, add_orient_op=add_orient_op, add_scale_op = add_scale_op, add_transform_op = add_transform_op, add_pivot_op = add_pivot) import omni.kit.window.property as p p.get_window()._window.frame.rebuild() def _register_widget(self): import omni.kit.window.property as p from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget, MultiSchemaPropertiesWidget w = p.get_window() if w: w.register_widget("prim", "transform", TransformAttributeWidget(title="Transform", collapsed=False)) self._registered = True def _unregister_widget(self): import omni.kit.window.property as p w = p.get_window() if w: w.unregister_widget("prim", "transform") self._registered = False #Context menu to Disable/Delete/Enable transform widgets def _register_context_menu(self): import omni.kit.context_menu menu_sep = { "name": "", } self._separator_menu = omni.kit.context_menu.add_menu(menu_sep, "attribute", "omni.kit.property.usd") # Disable Menu def _can_show_disable(object): model = object.get("model", None) if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: if xform_op_utils.is_reset_xform_stack_op(builder_widget._op_name): return True elif builder_widget._op_name is not None and builder_widget._attr_path is not None: return True #This must be a Disalbe Invalid Op menu, a bug if not the case elif builder_widget._op_name is not None and builder_widget._attr_path is None: return True return False def _on_disable(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: builder_widget._delete_op_only() menu_disable = { "name": "Disable", "show_fn": _can_show_disable, "onclick_fn": _on_disable } self._on_disable_menu = omni.kit.context_menu.add_menu(menu_disable, "attribute", "omni.kit.property.usd") #Delete Menu def _can_show_delete(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: if xform_op_utils.is_reset_xform_stack_op(builder_widget._op_name): return False elif builder_widget._attr_path is not None: return True return False def _on_delete(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: if builder_widget._op_name is not None: builder_widget._delete_op_and_attribute() else: builder_widget._delete_non_op_attribute() menu_delete = { "name": "Delete", "show_fn": _can_show_delete, "onclick_fn": _on_delete } self._on_delete_menu = omni.kit.context_menu.add_menu(menu_delete, "attribute", "omni.kit.property.usd") #Enable Menu def _can_show_enable(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: if builder_widget._op_name is None and builder_widget._attr_path is not None: return True return False def _on_enable(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: builder_widget._add_non_op_attribute_to_op() menu_enable = { "name": "Enable", "show_fn": _can_show_enable, "onclick_fn": _on_enable } self._on_enable_menu = omni.kit.context_menu.add_menu(menu_enable, "attribute", "omni.kit.property.usd") def _unregister_context_menu(self): self._separator_menu = None self._on_disable_menu = None self._on_delete_menu = None self._on_enable_menu = None
12,530
Python
41.767918
165
0.575499
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_commands.py
import carb import omni.kit.commands import omni.usd from omni.kit.usd_undo import * from pxr import Gf, Vt, Sdf, Usd, UsdGeom, UsdUtils from . import xform_op_utils class EnableXformOpCommand(omni.kit.commands.Command): """ Add and attritube's corresponding XformOp to xformOpOrder **Command**. Args: op_attr_path (str): path of the xformOp attribute. Example: We might want to add xformOp:translate to the xformOpOrder token array Provided that xformOp:translate attribute exists and xformOp:translate is no in xformOpOrder """ def __init__(self, op_attr_path: str, enable=True): self._op_attr_path = Sdf.Path(op_attr_path) self._usd_context = omni.usd.get_context() self._prev_xform_ops = None self._layer_op_order_map = {} def do(self): stage = self._usd_context.get_stage() if stage: op_attr = stage.GetObjectAtPath(self._op_attr_path) if not op_attr: return precision = xform_op_utils.get_op_precision(op_attr.GetTypeName()) op_name = op_attr.GetName() op_type = xform_op_utils.get_op_type(op_name) if op_type is None: return prim = op_attr.GetPrim() if not prim.IsA(UsdGeom.Xformable): return op_suffix = xform_op_utils.get_op_name_suffix(op_name) if op_suffix == None: op_suffix = "" xform = UsdGeom.Xformable(prim) self._prev_xform_ops = xform.GetOrderedXformOps() new_target = stage.GetEditTargetForLocalLayer(stage.GetEditTarget().GetLayer()) with Usd.EditContext(stage, new_target): with Sdf.ChangeBlock(): added_op = xform.AddXformOp(opType=op_type, precision = precision, opSuffix=op_suffix) #for pivot, we should add its inverse op as well # if xform_op_utils.is_pivot_op(op_name): pivot_op = added_op #Assume that !invert!xformOp:translate:pivot is always a trailing op xform.AddTranslateOp(precision = precision, opSuffix="pivot", isInverseOp=True) #Move the pivot op infront of the transform op as a special case xform_ops = xform.GetOrderedXformOps() new_xform_ops = [] found_transform_op = False for op in xform_ops: #wrap the transform op with pivot op if op.GetOpType() == UsdGeom.XformOp.TypeTransform: new_xform_ops.append(pivot_op) new_xform_ops.append(op) found_transform_op = True continue # skip the pivot op if we insert it in front of transform op if found_transform_op and op.GetOpType() == UsdGeom.XformOp.TypeTranslate \ and xform_op_utils.is_pivot_op(str(op.GetOpName())) \ and not xform_op_utils.is_inverse_op(str(op.GetOpName())): continue new_xform_ops.append(op) xform.SetXformOpOrder(new_xform_ops, xform.GetResetXformStack()) def undo(self): stage = self._usd_context.get_stage() op_attr = stage.GetObjectAtPath(self._op_attr_path) if not op_attr: return prim = op_attr.GetPrim() if not prim.IsA(UsdGeom.Xformable): return xform = UsdGeom.Xformable(prim) with Sdf.ChangeBlock(): new_target = stage.GetEditTargetForLocalLayer(stage.GetEditTarget().GetLayer()) with Usd.EditContext(stage, new_target): xform.SetXformOpOrder(self._prev_xform_ops) class ChangeRotationOpCommand(omni.kit.commands.Command): """ Change the Rotation XformOp **Command**. Args: src_op_attr_path (str): path of the source xformOp attribute. dst_op_attr_name (str): path of the destination xformOp attribute is_inverse_op (bool): if it is an inverse op, add an !invert! in the xformOpOrder Example: We may want to change from xformOp:rotateZYX to xformOp:rotateXYZ. It will 1) update the xformOpOrder 2) delete xformOp:rotateZYX attribute 3) create xformOp:rotateXYZ attribute 4) copy the xformOp:rotateZYX to xfomOp:rotateXYZ """ def __init__(self, src_op_attr_path: str, op_name: str, dst_op_attr_name: str, is_inverse_op: bool, auto_target_layer: bool = True): self._src_op_attr_path = Sdf.Path(src_op_attr_path) self._op_name = op_name self._dst_op_attr_name = dst_op_attr_name self._is_inverse_op = is_inverse_op self._auto_target_layer = auto_target_layer self._usd_context = omni.usd.get_context() self._usd_undos = dict() def _get_undo(self, layer): if layer is not None: undo = self._usd_undos.get(layer) if undo is not None: return undo self._usd_undos[layer] = UsdLayerUndo(layer) return self._usd_undos[layer] def _change_rotation_op(self): stage = self._usd_context.get_stage() src_op_attr = stage.GetObjectAtPath(self._src_op_attr_path) if src_op_attr == None or not src_op_attr.IsValid(): return src_op_attr_name = src_op_attr.GetName() if src_op_attr_name is None or self._dst_op_attr_name is None or src_op_attr_name == self._dst_op_attr_name: return prim = src_op_attr.GetPrim() if not prim: return op_order_attr = prim.GetAttribute("xformOpOrder") if not op_order_attr: return with Sdf.ChangeBlock(): current_authoring_layer = stage.GetEditTarget().GetLayer() # change xforpOpOrder layer_info, layer = omni.usd.get_attribute_effective_defaultvalue_layer_info(stage, op_order_attr) auto_target_session_layer = omni.usd.get_prop_auto_target_session_layer(stage, op_order_attr.GetPath()) if self._auto_target_layer else None if (layer_info == omni.usd.Value_On_Layer.ON_CURRENT_LAYER or layer_info == omni.usd.Value_On_Layer.ON_WEAKER_LAYER or (layer_info == omni.usd.Value_On_Layer.ON_STRONGER_LAYER and auto_target_session_layer is not None and self._auto_target_layer == True ) ): if self._op_name: order = op_order_attr.Get() old_op_name = self._op_name new_op_name = self._dst_op_attr_name = ( self._dst_op_attr_name if not self._is_inverse_op else "!invert!" + self._dst_op_attr_name ) for i in range(len(order)): if order.__getitem__(i) == old_op_name: order.__setitem__(i, new_op_name) break if auto_target_session_layer: undo = self._get_undo(auto_target_session_layer) undo.reserve(op_order_attr.GetPath()) with Usd.EditContext(stage, auto_target_session_layer): op_order_attr.Set(order) else: undo = self._get_undo(current_authoring_layer) undo.reserve(op_order_attr.GetPath()) op_order_attr.Set(order) # copy to new attribute old_dst_op_attr = prim.GetAttribute(self._dst_op_attr_name) # the dst_op_attr may already exist if old_dst_op_attr: layer_info, layer = omni.usd.get_attribute_effective_value_layer_info(stage, old_dst_op_attr) auto_target_session_layer = omni.usd.get_prop_auto_target_session_layer(stage, old_dst_op_attr.GetPath()) if self._auto_target_layer else None value_on_session_OK = layer_info == omni.usd.Value_On_Layer.ON_STRONGER_LAYER and self._auto_target_layer == True and auto_target_session_layer is not None value_update_OK = (layer_info == omni.usd.Value_On_Layer.ON_CURRENT_LAYER or layer_info == omni.usd.Value_On_Layer.ON_WEAKER_LAYER or value_on_session_OK) if value_update_OK: if auto_target_session_layer is not None: undo = self._get_undo(auto_target_session_layer) undo.reserve(old_dst_op_attr.GetPath()) with Usd.EditContext(stage, auto_target_session_layer): src_op_attr.FlattenTo(prim, self._dst_op_attr_name) else: undo = self._get_undo(current_authoring_layer) undo.reserve(old_dst_op_attr.GetPath()) src_op_attr.FlattenTo(prim, self._dst_op_attr_name) source_auto_target_sessiolayer = omni.usd.get_prop_auto_target_session_layer(stage, self._src_op_attr_path) if self._auto_target_layer else None if source_auto_target_sessiolayer is not None: undo = self._get_undo(source_auto_target_sessiolayer) undo.reserve(self._src_op_attr_path) with Usd.EditContext(stage, source_auto_target_sessiolayer): prim.RemoveProperty(src_op_attr_name) else: undo = self._get_undo(current_authoring_layer) undo.reserve(self._src_op_attr_path) prim.RemoveProperty(src_op_attr_name) else: carb.log_warn(f"{self._dst_op_attr_name} has value authoring in stronger layer, cannot overwrite it! ") else: dst_op_attr_path = prim.GetPath().AppendProperty(self._dst_op_attr_name) if dst_op_attr_path: auto_target_session_layer = omni.usd.get_prop_auto_target_session_layer(stage, old_dst_op_attr.GetPath()) if self._auto_target_layer else None if auto_target_session_layer is not None: undo = self._get_undo(auto_target_session_layer) undo.reserve(dst_op_attr_path) with Usd.EditContext(stage, auto_target_session_layer): src_op_attr.FlattenTo(prim, self._dst_op_attr_name) else: undo = self._get_undo(current_authoring_layer) undo.reserve(dst_op_attr_path) src_op_attr.FlattenTo(prim, self._dst_op_attr_name) source_auto_target_sessiolayer = omni.usd.get_prop_auto_target_session_layer(stage, self._src_op_attr_path) if self._auto_target_layer else None if source_auto_target_sessiolayer is not None: undo = self._get_undo(source_auto_target_sessiolayer) undo.reserve(self._src_op_attr_path) with Usd.EditContext(stage, source_auto_target_sessiolayer): prim.RemoveProperty(src_op_attr_name) else: undo = self._get_undo(current_authoring_layer) undo.reserve(self._src_op_attr_path) prim.RemoveProperty(src_op_attr_name) else: carb.log_error(f"Invalid dst_op_attr_name {self._dst_op_attr_name}. Note this is the attribute name.") else: carb.log_warn("xformOpOrder has value authoring a stronger persistent layer, cannot authoring rotate order! ") def do(self): stage = self._usd_context.get_stage() if not stage: return self._change_rotation_op() def undo(self): for undo in self._usd_undos.values(): undo.undo() class RemoveXformOpCommand(omni.kit.commands.Command): """ Remove XformOp Only **Command**. Args: op_order_attr_path (str): path of the xformOpOrder attribute. op_name (str): name of the xformOp to be removed Example: We might want to remove xformOp:translate from the xformOpOrder token array But we still keep the xformOp:translate attribute itself """ def __init__(self, op_order_attr_path: str, op_name: str, op_order_index: int): self._op_order_attr_path = Sdf.Path(op_order_attr_path) self._op_order_index = op_order_index self._op_name = op_name self._usd_context = omni.usd.get_context() self._usd_undo = None def do(self): stage = self._usd_context.get_stage() if not stage: return usd_undo = UsdLayerUndo(stage.GetEditTarget().GetLayer()) usd_undo.reserve(self._op_order_attr_path) order_attr = stage.GetObjectAtPath(self._op_order_attr_path) if order_attr: with Sdf.ChangeBlock(): op_order = order_attr.Get() if self._op_order_index < len(op_order): op_name = op_order.__getitem__(self._op_order_index) # when remove pivot op also need to remove invert pivot op is_pivot_op = xform_op_utils.is_pivot_op(op_name) inv_op_name = xform_op_utils.get_inverse_op_Name(op_name, True) if is_pivot_op else None if op_name == self._op_name: new_order = [] for i in range(len(op_order)): if i != self._op_order_index: if is_pivot_op and inv_op_name == op_order.__getitem__(i): continue new_order.append(op_order.__getitem__(i)) order_attr.Set(new_order) self._usd_undo = usd_undo def undo(self): if self._usd_undo is None: return self._usd_undo.undo() class RemoveXformOpAndAttrbuteCommand(omni.kit.commands.Command): """ Remove XformOp And Attribute **Command**. Args: op_order_attr_path (str): path of the xformOpOrder attribute. op_name (str): name of the xformOp to be removed Example: We might want to remove xformOp:translate from the xformOpOrder token array But we still keep the xformOp:translate attribute itself """ def __init__(self, op_order_attr_path: str, op_name: str, op_order_index: int): self._op_order_attr_path = Sdf.Path(op_order_attr_path) # the xformOpOrder attribute path self._op_name = op_name # xformOpName self._op_order_index = op_order_index self._usd_context = omni.usd.get_context() self._usd_undo = None def do(self): stage = omni.usd.get_context().get_stage() if stage: usd_undo = UsdLayerUndo(stage.GetEditTarget().GetLayer()) self._usd_undo = usd_undo order_attr = stage.GetObjectAtPath(self._op_order_attr_path) if order_attr: with Sdf.ChangeBlock(): op_order = order_attr.Get() if self._op_order_index < len(op_order): op_name = op_order.__getitem__(self._op_order_index) if op_name == self._op_name: # if it is an pivot op to remove, we'd also remove it's companion inverse pivot op is_pivot_op = xform_op_utils.is_pivot_op(op_name) inverse_pivot_op_name = xform_op_utils.get_inverse_op_Name(op_name, True) if is_pivot_op else None attr_name = xform_op_utils.get_op_attr_name(op_name) can_delete_attr = True new_order = [] for i in range(len(op_order)): #exclude the op if i != self._op_order_index: #if it is a pivot also exclude the inverse op if is_pivot_op and op_order.__getitem__(i) == inverse_pivot_op_name: continue other_op_name = op_order.__getitem__(i) new_order.append(other_op_name) if attr_name == xform_op_utils.get_op_attr_name(other_op_name): can_delete_attr = False new_token_order = Vt.TokenArray(new_order) usd_undo.reserve(self._op_order_attr_path) order_attr.Set(new_order) if can_delete_attr: prim = order_attr.GetPrim() if prim: usd_undo.reserve(prim.GetPath().AppendProperty(attr_name)) prim.RemoveProperty(attr_name) def undo(self): if self._usd_undo is None: return self._usd_undo.undo() class AddXformOpCommand(omni.kit.commands.Command): """ Add and attritube's corresponding XformOp to xformOpOrder **Command**. Args: op_attr_path (str): path of the xformOp attribute. Example: We might want to add xformOp:translate to the xformOpOrder token array Provided that xformOp:translate attribute exists and xformOp:translate is no in xformOpOrder """ def __init__(self, payload, precision, rotation_order, add_translate_op, add_rotateXYZ_op, add_orient_op, add_scale_op, add_transform_op, add_pivot_op): self._payload = payload self._precision = precision self._rotation_op_name = "xformOp:rotate" + rotation_order self._add_translate_op = add_translate_op self._add_rotate_op = add_rotateXYZ_op self._add_orient_op=add_orient_op self._add_scale_op = add_scale_op self._add_transform_op = add_transform_op self._add_pivot_op = add_pivot_op self._usd_undo = None self._prv_xform_op_order = {} self._translate_attr_added = {} self._rotate_attr_added = {} self._orient_attr_added = {} self._scale_attr_added = {} self._transform_attr_added = {} self._pivot_attr_added = {} def do(self): stage = self._payload.get_stage() if not stage: return # check precision first and return if self._precision != UsdGeom.XformOp.PrecisionHalf and self._precision != UsdGeom.XformOp.PrecisionDouble and self._precision != UsdGeom.XformOp.PrecisionFloat: carb.log_error("Illegal value precision setting! Precision setting can be UsdGeom.XformOp.PrecisionDouble OR UsdGeom.XformOp.PrecisionFloat OR UsdGeom.XformOp.PrecisionHalf.") return for path in self._payload: if path: selected_prim = stage.GetPrimAtPath(path) selected_xformable = UsdGeom.Xformable(selected_prim) # if not xform, skip if not selected_xformable: carb.log_error(f"Illegal prim {path}: this is not an UsdGeom.Xformable prim.") continue path_string = path.pathString translate_attr = selected_prim.GetAttribute("xformOp:translate") rotate_attr = selected_prim.GetAttribute(self._rotation_op_name) scale_attr = selected_prim.GetAttribute("xformOp:scale") orient_attr = selected_prim.GetAttribute("xformOp:orient") transform_attr = selected_prim.GetAttribute("xformOp:transform") pivot_attr = selected_prim.GetAttribute("xformOp:translate:pivot") translate_attr_exist = True if translate_attr.IsValid() else False rotate_attr_exist = True if rotate_attr.IsValid() else False scale_attr_exist = True if scale_attr.IsValid() else False orient_attr_exist = True if orient_attr.IsValid() else False transform_attr_exist = True if transform_attr.IsValid() else False pivot_attr_exist = True if pivot_attr.IsValid() else False translate_attr_type = xform_op_utils.get_op_precision(translate_attr.GetTypeName()) if translate_attr_exist else None rotate_attr_type = xform_op_utils.get_op_precision(rotate_attr.GetTypeName()) if rotate_attr_exist else None scale_attr_type = xform_op_utils.get_op_precision(scale_attr.GetTypeName()) if scale_attr_exist else None orient_attr_type = xform_op_utils.get_op_precision(orient_attr.GetTypeName()) if orient_attr_exist else None pivot_attr_type = xform_op_utils.get_op_precision(pivot_attr.GetTypeName()) if pivot_attr_exist else None def does_match_precision(self, attr_type): if attr_type and self._precision != attr_type: return False return True xform_op_order_attr = selected_xformable.GetXformOpOrderAttr() translate_op_exist = rotate_op_exist = scale_op_exist = orient_op_exist = transform_op_exist = pivot_op_exist = False self._translate_attr_added[path_string] = self._rotate_attr_added[path_string] = False self._orient_attr_added[path_string] = self._scale_attr_added[path_string] = self._transform_attr_added[path_string] = False self._pivot_attr_added[path_string] = False with Sdf.ChangeBlock(): #In a rare case, there is no xformOpOrder attribute if not xform_op_order_attr: xform_op_order_attr = selected_xformable.CreateXformOpOrderAttr() xform_op_order = xform_op_order_attr.Get() ordered_xform_op = selected_xformable.GetOrderedXformOps() for op in ordered_xform_op: if op.GetOpName() == 'xformOp:translate': translate_op_exist = True elif op.GetOpName() == self._rotation_op_name: rotate_op_exist = True elif op.GetOpName() == 'xformOp:scale': scale_op_exist = True elif op.GetOpName() == 'xformOp:orient': orient_op_exist = True elif op.GetOpName() == 'xformOp:transform': transform_op_exist = True elif op.GetOpType() == UsdGeom.XformOp.TypeTranslate and "pivot" in op.SplitName(): pivot_op_exist = True self._prv_xform_op_order[path_string] = xform_op_order #Translate Op if self._add_translate_op == True: if translate_attr_exist and translate_op_exist: carb.log_warn(f"The translate Op in prim {path} already exist!") # There is already translate attribute exist elif translate_op_exist == False: if does_match_precision(self, translate_attr_type): selected_xformable.AddTranslateOp(precision = self._precision) if translate_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(0, 0, 0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3,False).Set(Gf.Vec3f(0, 0, 0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Half3,False).Set(Gf.Vec3h(0, 0, 0)) self._translate_attr_added[path_string] = True else: carb.log_error("Illegal translate value precision setting!") #Rotate Op if self._add_rotate_op == True: if rotate_attr_exist and rotate_op_exist: carb.log_warn(f"The rotate Op in prim {path} already exist!") # There is already translate attribute exist elif rotate_op_exist == False: if does_match_precision(self, rotate_attr_type): rotation_op_type = xform_op_utils.get_op_type(self._rotation_op_name) if rotation_op_type: selected_xformable.AddXformOp(rotation_op_type,precision = self._precision) if rotate_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute(self._rotation_op_name, Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(0, 0, 0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute(self._rotation_op_name, Sdf.ValueTypeNames.Float3,False).Set(Gf.Vec3f(0, 0, 0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute(self._rotation_op_name, Sdf.ValueTypeNames.Half3,False).Set(Gf.Vec3h(0, 0, 0)) self._rotate_attr_added[path_string] = True else: carb.log_error("Illegal rotate value precision setting!") #Orient Op if self._add_orient_op == True: if orient_attr_exist and orient_op_exist: carb.log_warn(f"The orient Op in prim {path} already exist!") # There is already translate attribute exist elif orient_op_exist == False: if does_match_precision(self, orient_attr_type): selected_xformable.AddOrientOp(precision = self._precision) if orient_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd,False).Set(Gf.Quatd(1.0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatf,False).Set(Gf.Quatf(1.0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quath,False).Set(Gf.Quath(1.0)) self._orient_attr_added[path_string] = True else: carb.log_error("Illegal orient value precision setting!") #Scale Op if self._add_scale_op == True: if scale_attr_exist and scale_op_exist: carb.log_warn(f"The scale Op in prim {path} already exist!") # There is already translate attribute exist elif scale_op_exist == False: if does_match_precision(self, scale_attr_type): selected_xformable.AddScaleOp(precision = self._precision) if scale_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(1.0, 1.0, 1.0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3,False).Set(Gf.Vec3f(1.0, 1.0, 1.0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Half3,False).Set(Gf.Vec3h(1.0, 1.0, 1.0)) self._scale_attr_added[path_string] = True else: carb.log_error("Illegal scale value precision setting!") #Transform Op if self._add_transform_op == True: if transform_attr_exist and transform_op_exist: carb.log_warn(f"The transform Op in prim {path} already exist!") # There is already transform attribute exist elif transform_op_exist == False: #'Matrix transformations can only be encoded in double precision. Overriding precision to double.' #transform has to be double selected_xformable.AddTransformOp(UsdGeom.XformOp.PrecisionDouble) if transform_attr_exist == False: # there is only Matrix4d type selected_prim.CreateAttribute("xformOp:transform", Sdf.ValueTypeNames.Matrix4d,False).Set(Gf.Matrix4d(1.0)) self._transform_attr_added[path_string] = True #refresh to make sure pivot is inserted in the right place ordered_xform_op = selected_xformable.GetOrderedXformOps() #Pivot Op if self._add_pivot_op == True: if pivot_attr_exist and pivot_op_exist: carb.log_warn(f"The pivot Op in the prim {path} already exist!") elif pivot_op_exist == False: if does_match_precision(self, pivot_attr_type): # Parse the xformOpOrder to find out the rotateion-related & scale-related op's index # there might be multiple rotation & scale op to consider xform_op_size = len(ordered_xform_op) rotate_or_transform_start_index = rotate_or_transform_end_index = scale_start_index = scale_end_index = xform_op_size for index in range(xform_op_size): op = ordered_xform_op[index] op_type = op.GetOpType() # Suffixed op doesn't count if op_type > UsdGeom.XformOp.TypeInvalid and \ len(op.GetOpName().split(":"))>2: continue if op_type >= UsdGeom.XformOp.TypeRotateX \ and op_type <= UsdGeom.XformOp.TypeTransform: rotate_or_transform_end_index = index if rotate_or_transform_start_index == xform_op_size: rotate_or_transform_start_index = index elif op_type == UsdGeom.XformOp.TypeScale: scale_end_index = index if scale_start_index == xform_op_size: scale_start_index = index if rotate_or_transform_start_index == xform_op_size and scale_start_index == xform_op_size: carb.log_warn("There is no rotate, orient, transform or scale Op for this prim. No rotation Pivot is added.") return #Add the pivot op and invert pivot op and then reorder it pivot_op = selected_xformable.AddTranslateOp(precision = self._precision, opSuffix="pivot") inv_pivot_op = selected_xformable.AddTranslateOp(precision = self._precision, opSuffix="pivot", isInverseOp=True) #pivot and inv pivot to wrap the rotate & scale op. pivot heading inv pivot trailing pivot_index = min(rotate_or_transform_start_index, scale_start_index) inv_pivot_index = max(rotate_or_transform_end_index, scale_end_index) inv_pivot_index = inv_pivot_index + 1 #insert after # if the inverse pivot op is at the tail, just append it if inv_pivot_index >= len(ordered_xform_op): ordered_xform_op.append(inv_pivot_op) else: ordered_xform_op.insert(inv_pivot_index, inv_pivot_op) #It is important to insert pivot_op after inv_pivot_op ordered_xform_op.insert(pivot_index, pivot_op) selected_xformable.SetXformOpOrder(ordered_xform_op, selected_xformable.GetResetXformStack()) #Create xformOp:translate:pivot attribute if pivot_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute("xformOp:translate:pivot", Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(0.0, 0.0, 0.0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute("xformOp:translate:pivot", Sdf.ValueTypeNames.Float3,False).Set(Gf.Vec3f(0.0, 0.0, 0.0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute("xformOp:translate:pivot", Sdf.ValueTypeNames.Half3,False).Set(Gf.Vec3h(0.0, 0.0, 0.0)) self._pivot_attr_added[path_string] = True else: carb.log_error("Illegal pivot value precision setting!") def undo(self): stage = self._payload.get_stage() if not stage: return for path in self._payload: if path: selected_prim = stage.GetPrimAtPath(path) selected_xformable = UsdGeom.Xformable(selected_prim) path_string = path.pathString with Sdf.ChangeBlock(): xform_op_order_attr = selected_xformable.GetXformOpOrderAttr() if xform_op_order_attr: xform_op_order_attr.Set(self._prv_xform_op_order[path_string]) if self._translate_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:translate") self._translate_attr_added[path_string] = False if self._rotate_attr_added[path_string]: selected_prim.RemoveProperty(self._rotation_op_name) self._rotate_attr_added[path_string] = False if self._orient_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:orient") self._orient_attr_added[path_string] = False if self._scale_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:scale") self._scale_attr_added[path_string] = False if self._transform_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:transform") self._transform_attr_added[path_string] = False if self._pivot_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:translate:pivot") self._pivot_attr_added[path_string] = False omni.kit.commands.register_all_commands_in_module(__name__)
37,809
Python
55.181278
187
0.525536
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_builder.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import weakref import omni.kit.app import omni.kit.test import omni.kit.commands import omni.ui as ui from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading, select_prims from omni.ui.tests.test_base import OmniUiTest from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload from pathlib import Path from pxr import UsdGeom, Sdf from ..scripts.transform_builder import TransformWidgets, TransformWatchModel, USDXformOpWidget from ..scripts.transform_widget import TransformAttributeWidget from ..scripts.transform_properties import g_ext class TestTransformBuilder(OmniUiTest): xform_op_names = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:orient", "xformOp:scale", "xformOp:translate:pivot", "xformOp:transform"] # Before running each test async def setUp(self): await super().setUp() extension_root_folder = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) self._usd_path = extension_root_folder.joinpath("data/test_data/test_map") # After running each test async def tearDown(self): await super().tearDown() def get_index_op_code(self, xform : UsdGeom.Xformable, op_name): xform_ops = xform.GetOrderedXformOps() for i, op in enumerate(xform_ops): if op.GetOpName() == op_name: return i return -1 async def test_builder_widgets(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() prim_path = '/World/Capsule' prim = stage.GetPrimAtPath(prim_path) xform = UsdGeom.Xformable(prim) transformWidget = TransformAttributeWidget("Test", True) await select_prims([prim_path]) collapsable_frame = ui.Frame(height=0, style={"Frame": {"padding": 0}}) # widget delete test widgets = [] op_order_attr = prim.GetAttribute('XformOpOrder') for op_name in self.xform_op_names: #valid means disabled or not widget = transformWidget._transform_widget._create_xform_op_widget( [Sdf.Path(prim_path)], collapsable_frame, stage, prim.GetAttribute(op_name), op_name, True, op_order_attr, self.get_index_op_code(xform, op_name) ) widgets.append(widget) await ui_test.human_delay(3) transformWidget = None widgets = [] transformWidget = TransformAttributeWidget("Test2", True) collapsable_frame = ui.Frame(height=0, style={"Frame": {"padding": 0}}) widgets = [] op_order_attr = prim.GetAttribute('XformOpOrder') for op_name in self.xform_op_names: #valid means disabled or not widget = transformWidget._transform_widget._create_xform_op_widget( [Sdf.Path(prim_path)], collapsable_frame, stage, prim.GetAttribute(op_name), op_name, False, op_order_attr, self.get_index_op_code(xform, op_name) ) widgets.append(widget) await ui_test.human_delay(3) transformWidget = None widgets = [] #watch model watch_model = TransformWatchModel(0, stage) await ui_test.human_delay(3) watch_model.set_value(0.3) self.assertTrue(watch_model.get_value_as_float() == 0.3) self.assertTrue(watch_model.get_value_as_string() == "0.3") watch_model.clean() watch_model = None # USD Xform Op Widget for op_name in self.xform_op_names: #valid means disabled or not widget = USDXformOpWidget( [Sdf.Path(prim_path)], collapsable_frame, stage, prim.GetAttribute(op_name).GetPath(), op_name, True, op_order_attr, self.get_index_op_code(xform, op_name)) #widget._inverse_op() widget._add_key() widget._show_right_click_menu(button=1) async def test_add_buttons(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() prim_paths =["/World/Capsule", "/World/Sphere", "/World/Cube", "/World/Cylinder", "/World/Cone"] for prim_path in prim_paths: await select_prims([prim_path]) prim = stage.GetObjectAtPath(prim_path) payload = PrimSelectionPayload( weakref.ref(stage), [prim.GetPath()]) for button_menu in g_ext._add_button_menu: if button_menu.onclick_fn: button_menu.onclick_fn(payload) await ui_test.human_delay(2)
5,548
Python
37.534722
146
0.637167
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_transform.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading from omni.ui.tests.test_base import OmniUiTest from pxr import Kind, Sdf, Gf, UsdGeom from pathlib import Path import carb from carb.input import KeyboardInput def equal_eps(a, b, esp = 0.0001): return abs(a - b) < esp def equal_scale_eps(t, s): m = Gf.Vec3d(0.0) m[0] = t.GetRow(0).GetLength() m[1] = t.GetRow(1).GetLength() m[2] = t.GetRow(2).GetLength() #print (m) return equal_eps(m[0], s[0]) and equal_eps(m[1], s[1]) and equal_eps(m[2], s[2]) class TestTransformWidget(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() extension_root_folder = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) self._golden_img_dir = extension_root_folder.joinpath("data/test_data/golden_img") self._usd_path = extension_root_folder.joinpath("data/test_data/test_map") from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() # After running each test async def tearDown(self): await super().tearDown() async def test_transform_property_srt(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_srt.png") async def test_transform_property_srt_filter(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) try: self._w._searchfield._search_field.model.as_string = "tr" self._w._searchfield._set_in_searching(True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_srt_filter.png") finally: self._w._searchfield._search_field.model.as_string = "" self._w._searchfield._set_in_searching(False) async def test_transform_property_sqt(self): usd_context = omni.usd.get_context() # golden image expects the UI to be switched to "orient as rotate" settings = carb.settings.get_settings() doar_path = "/persistent/app/uiSettings/DisplayOrientAsRotate" doar_val = settings.get_as_bool(doar_path) settings.set(doar_path, True) try: await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Capsule"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) finally: carb.settings.get_settings().set(doar_path, doar_val) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_sqt.png") async def test_transform_property_sqt2(self): usd_context = omni.usd.get_context() # golden image expects the UI to be switched to "orient as rotate" settings = carb.settings.get_settings() doar_path = "/persistent/app/uiSettings/DisplayOrientAsRotate" doar_val = settings.get_as_bool(doar_path) settings.set(doar_path, True) try: await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM, block_devices=False) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Capsule"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) #now find a button for orient and click it to swap to test swapping widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Button[*].text=='Orient'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) finally: await self.capture_and_compare(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_sqt2.png") # add another test to click it back widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Button[*].text=='Orient'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_sqt3.png") carb.settings.get_settings().set(doar_path, doar_val) async def test_transform_property_matrix(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cylinder"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_matrix.png") async def test_transform_property_pivot(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=280, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cone"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_pivot.png") async def test_transform_property_disabled_translate_op(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=260, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Sphere"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_disabled_translate_op.png") async def test_transform_property_euler_to_quat_sync(self): usd_context = omni.usd.get_context() usd_context.new_stage() settings = carb.settings.get_settings() doar_path = "/persistent/app/uiSettings/DisplayOrientAsRotate" doar_val = settings.get_as_bool(doar_path) carb.settings.get_settings().set(doar_path, True) try: await self.docked_test_window( window=self._w._window, width=640, height=480, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) # we actually want mouse and keyboard to be active omni.appwindow.get_default_app_window().set_input_blocking_state(carb.input.DeviceType.MOUSE, False) omni.appwindow.get_default_app_window().set_input_blocking_state(carb.input.DeviceType.KEYBOARD, False) await ui_test.wait_n_updates(10) path = "/Cube" cube_geom = UsdGeom.Cube.Define(usd_context.get_stage(), path) cube_geom.AddOrientOp().Set(Gf.Quatf(1.0)) usd_context.get_selection().set_selected_prim_paths([path], False) await ui_test.find("Property").focus() transform_euler = ui_test.find("Property//Frame/**/*.identifier=='euler_xformOp:orient'") # change Y axis to 180 digit by digit as a user would do await transform_euler.double_click(human_delay_speed=10) for s in "180": await ui_test.emulate_char_press(s) await ui_test.wait_n_updates(10) await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.ENTER) finally: await self.finalize_test_no_image() carb.settings.get_settings().set(doar_path, doar_val) orient = Gf.Quatf(1.0) for op in cube_geom.GetOrderedXformOps(): if op.GetOpType() == UsdGeom.XformOp.TypeOrient: orient = op.Get() self.assertTrue(orient.imaginary[1] != 0) async def test_transform_property_multi(self): usd_context = omni.usd.get_context() # golden image expects the UI to be switched to "orient as rotate" try: await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Capsule", "/World/Cube", "/World/Cylinder"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) finally: await self.capture_and_compare(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_multi.png") # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Capsule", "/World/Cube"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) #text of mixed is moving and it's causing very unstable result for testing, so increasing threshold to be 2. await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_multi2.png", threshold=2) async def test_transform_scale(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) prim = stage.GetPrimAtPath("/World/Cube") # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='scale_t_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 2.0, 1.0))) # Apply another offset, then check the prim's translation await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("*2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 4.0, 1.0))) # Click and drag field, the check the prim's translation drag_vector = stack.center drag_vector.x = drag_vector.x + 30 await ui_test.human_delay(30) await ui_test.emulate_mouse_drag_and_drop(stack.center, drag_vector) await ui_test.wait_n_updates(2) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 7.0, 1.0))) await self.finalize_test_no_image() await ui_test.wait_n_updates(20) async def test_transform_toggle_scale(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) prim = stage.GetPrimAtPath("/World/Cube") # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) button = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Button[*].identifier=='toggle_link_scale'") # We should be able to find the mode toggle button, # but until we're in offset mode we should not have any offset fields self.assertIsNotNone(button) #enable toggle mode await button.click(pos=button.position+ui_test.Vec2(button.widget.computed_content_width/2, 5)) await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='scale_t_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(2.0, 2.0, 2.0))) await self.finalize_test_no_image() await ui_test.wait_n_updates(20) async def test_transform_reset_stack(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=280, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath("/World/Cube") # Get the XformCommonAPI xform_api = UsdGeom.XformCommonAPI(prim) #Set the ResetXformStack. UI should responds accordingly xform_api.SetResetXformStack(True) usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_reset.png") async def test_transform_rotate_scalar(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube_2"], True) prim = stage.GetPrimAtPath("/World/Cube_2") # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) # Now we're in offset mode. x_stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='rotate_scalar_stack_x'") self.assertIsNotNone(x_stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. rotate_attr = prim.GetAttribute("xformOp:rotateX") self.assertIsNotNone(rotate_attr) self.assertTrue(rotate_attr.Get() == -30.0) # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await x_stack.click() await x_stack.double_click() await ui_test.human_delay(10) for _ in range(5): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("20") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) self.assertTrue(rotate_attr.Get() == 20.0) y_stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='rotate_scalar_stack_y'") self.assertIsNotNone(y_stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. rotate_attr = prim.GetAttribute("xformOp:rotateY") self.assertIsNotNone(rotate_attr) self.assertTrue(rotate_attr.Get() == 0.0) # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await y_stack.click() await y_stack.double_click() await ui_test.human_delay(10) for _ in range(5): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("30") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) self.assertTrue(rotate_attr.Get() == 30.0) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_eps(transform.ExtractRotation().GetAngle(), 35.92772)) #test transform await self.finalize_test_no_image() await ui_test.wait_n_updates(20) ''' #this test doesn't work because the kit has a way to enter xformOp:translate to trigger #build widget, where test won't be able to do this. OM-112507 #https://nvidia.slack.com/archives/CURCH7KU2/p1697658671468429?thread_ts=1697204512.040859&cid=CURCH7KU2 async def test_transform_property_wgs84(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=640, height=480, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("wgs84/deutschebahn-rails.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/RootGeoReference/World/CurveXform26Geo"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) try: self._w._searchfield._search_field.model.as_string = "tr" self._w._searchfield._set_in_searching(True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_wgs84.png") finally: self._w._searchfield._search_field.model.as_string = "" self._w._searchfield._set_in_searching(False) '''
26,141
Python
43.84048
140
0.642669
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/__init__.py
from .test_transform import * from .test_offset import * from .test_transform_context_menu import * from .test_commands import * from .test_builder import *
157
Python
25.333329
42
0.764331
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_offset.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. ## from carb.input import KeyboardInput import omni.kit.test import omni.kit.ui_test as ui_test import omni.ui as ui import omni.usd from omni.ui.tests.test_base import OmniUiTest from pxr import Gf def equal_eps(a, b, esp = 0.0001): return abs(a - b) < esp class TestTransformOffset(OmniUiTest): async def setUp(self): await super().setUp() from omni.kit.property.transform.scripts.transform_properties import TEST_DATA_PATH self._usd_path = TEST_DATA_PATH.absolute() from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() async def tearDown(self): await super().tearDown() async def test_offset_mode_rotate(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("offset_test.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) prim = stage.GetPrimAtPath(f"{stage.GetDefaultPrim().GetPath()}/Cube") self.assertTrue(prim.IsValid()) # Select the prim. usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) button = ui_test.find("Property//Frame/**/Button[*].identifier=='offset_mode_toggle'") # We should be able to find the mode toggle button, # but until we're in offset mode we should not have any offset fields self.assertIsNotNone(button) await button.click() await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='rotate_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("10") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_eps(transform.ExtractRotation().GetAngle(), 10.0)) # Apply another offset, then check the prim's translation await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("*2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_eps(transform.ExtractRotation().GetAngle(), 20.0)) # Click and drag field, the check the prim's translation drag_vector = stack.center drag_vector.x = drag_vector.x + 100 await ui_test.human_delay(30) await ui_test.emulate_mouse_drag_and_drop(stack.center, drag_vector) await ui_test.wait_n_updates(2) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_eps(transform.ExtractRotation().GetAngle(), 21.0)) await self.finalize_test_no_image() # Finally, toggle offset mode again so subsequent tests will not start in offset mode await button.click() await ui_test.wait_n_updates(20) async def test_offset_mode_translate(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("offset_test.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) prim = stage.GetPrimAtPath(f"{stage.GetDefaultPrim().GetPath()}/Cube") self.assertTrue(prim.IsValid()) # Select the prim. usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) button = ui_test.find("Property//Frame/**/Button[*].identifier=='offset_mode_toggle'") stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='translate_stack'") # We should be able to find the mode toggle button, # but until we're in offset mode we should not have any offset fields self.assertIsNotNone(button) self.assertIsNone(stack) await button.click() await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='translate_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("100") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(transform.ExtractTranslation() == Gf.Vec3d(0.0, 100.0, 0.0)) # Apply another offset, then check the prim's translation await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("*2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(transform.ExtractTranslation() == Gf.Vec3d(0.0, 200.0, 0.0)) # Click and drag field, the check the prim's translation drag_vector = stack.center drag_vector.x = drag_vector.x + 100 await ui_test.human_delay(30) await ui_test.emulate_mouse_drag_and_drop(stack.center, drag_vector) await ui_test.wait_n_updates(2) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(transform.ExtractTranslation() == Gf.Vec3d(0.0, 201.0, 0.0)) await self.finalize_test_no_image() # Finally, toggle offset mode again so subsequent tests will not start in offset mode await button.click() await ui_test.wait_n_updates(20) async def test_offset_mode_scale(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("offset_test.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) prim = stage.GetPrimAtPath(f"{stage.GetDefaultPrim().GetPath()}/Cube") self.assertTrue(prim.IsValid()) # Select the prim. usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) button = ui_test.find("Property//Frame/**/Button[*].identifier=='offset_mode_toggle'") # We should be able to find the mode toggle button, # but until we're in offset mode we should not have any offset fields self.assertIsNotNone(button) await button.click() await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='scale_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) def equal_scale_eps(t, s): m = Gf.Vec3d(0.0) m[0] = t.GetRow(0).GetLength() m[1] = t.GetRow(1).GetLength() m[2] = t.GetRow(2).GetLength() #print (m) return equal_eps(m[0], s[0]) and equal_eps(m[1], s[1]) and equal_eps(m[2], s[2]) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 3.0, 1.0))) # Apply another offset, then check the prim's translation await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("*2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 6.0, 1.0))) # Click and drag field, the check the prim's translation drag_vector = stack.center drag_vector.x = drag_vector.x + 100 await ui_test.human_delay(30) await ui_test.emulate_mouse_drag_and_drop(stack.center, drag_vector) await ui_test.wait_n_updates(2) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 7.0, 1.0))) await self.finalize_test_no_image() # Finally, toggle offset mode again so subsequent tests will not start in offset mode await button.click() await ui_test.wait_n_updates(20)
12,486
Python
41.763698
107
0.653692
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_commands.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import weakref import omni.kit.app import omni.kit.commands import omni.kit.test from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from pxr import UsdGeom, Sdf, Gf from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload from ..scripts.xform_op_utils import get_op_type_name, _add_trs_op, get_op_name_suffix, get_op_precision, get_inverse_op_Name, RESET_XFORM_STACK, get_op_attr_name import carb import carb.settings class TestTransformCommands(OmniUiTest): xform_op_names = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:orient", "xformOp:scale", "xformOp:translate:pivot", "xformOp:transform"] prim_paths =["/World/Capsule", "/World/Cube", "/World/Cylinder", "/World/Cone"] # Before running each test async def setUp(self): await super().setUp() extension_root_folder = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) self._usd_path = extension_root_folder.joinpath("data/test_data/test_map") # After running each test async def tearDown(self): await super().tearDown() def include_op_code(self, xform : UsdGeom.Xformable, op_name): return self.get_index_op_code(xform, op_name) != -1 def get_index_op_code(self, xform : UsdGeom.Xformable, op_name): xform_ops = xform.GetOrderedXformOps() for i, op in enumerate(xform_ops): if op.GetOpName() == op_name: return i return -1 async def add_xform_ops_test(self, stage, prim_path, precision, undo_after=True): prim = stage.GetObjectAtPath(prim_path) xform = UsdGeom.Xformable(prim) usd_context = omni.usd.get_context() usd_context.get_selection().set_selected_prim_paths([prim_path], True) await ui_test.human_delay(3) ops_exists = [] attr_exists = [] for op_name in self.xform_op_names: ops_exists.append(self.include_op_code(xform, op_name)) attr_exists.append(stage.GetObjectAtPath(prim_path + "." + op_name) != None) payload = PrimSelectionPayload( weakref.ref(stage), [prim.GetPath()]) omni.kit.commands.execute('AddXformOp', payload=payload, precision=precision, rotation_order='XYZ', add_translate_op=True, add_rotateXYZ_op=True, add_orient_op=True, add_scale_op=True, add_transform_op=True, add_pivot_op=True) await ui_test.human_delay(3) xform_ops = xform.GetOrderedXformOps() for op_name in self.xform_op_names: #make sure rotation order XYZ ops_exists self.assertTrue(self.include_op_code(xform, op_name)) attr = stage.GetObjectAtPath(prim_path + "." + op_name) self.assertTrue(attr) if undo_after: #undo omni.kit.commands.execute("Undo") await ui_test.human_delay(3) for i, op_name in enumerate(self.xform_op_names): if not ops_exists[i]: self.assertTrue(not self.include_op_code(xform, op_name)) async def remove_xform_ops_test(self, stage, prim_path): prim = stage.GetObjectAtPath(prim_path) xform = UsdGeom.Xformable(prim) usd_context = omni.usd.get_context() usd_context.get_selection().set_selected_prim_paths([prim_path], True) await ui_test.human_delay(3) for op_name in self.xform_op_names: index = self.get_index_op_code(xform, op_name) omni.kit.commands.execute('RemoveXformOpAndAttrbute', op_order_attr_path=Sdf.Path(prim_path + '.xformOpOrder'), op_name=op_name, op_order_index=index) await ui_test.human_delay(3) self.assertTrue(not self.include_op_code(xform, op_name)) for op_name in self.xform_op_names: omni.kit.commands.execute("Undo") for op_name in self.xform_op_names: self.assertTrue(self.include_op_code(xform, op_name)) async def test_transform_add_remove_commands(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() precision_types = [UsdGeom.XformOp.PrecisionDouble, UsdGeom.XformOp.PrecisionFloat, UsdGeom.XformOp.PrecisionHalf] for prim_path in self.prim_paths: for precision in precision_types: await self.add_xform_ops_test(stage, prim_path, precision) for prim_path in self.prim_paths: for precision in precision_types: await self.add_xform_ops_test(stage, prim_path, precision, False) await self.remove_xform_ops_test(stage, prim_path) async def test_transform_add_remove_xformops_commands(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() #ops_exists = [] #for op_name in self.xform_op_names: # ops_exists.append(self.include_op_code(xform, op_name)) usd_context.get_selection().set_selected_prim_paths(["/World/Sphere"], True) await ui_test.human_delay(3) await self.add_xform_ops_test(stage, "/World/Sphere", UsdGeom.XformOp.PrecisionDouble, False) prim = stage.GetObjectAtPath("/World/Sphere") xform = UsdGeom.Xformable(prim) #disable all properties for op in self.xform_op_names: index = self.get_index_op_code(xform, op) omni.kit.commands.execute("RemoveXformOpCommand", op_order_attr_path="/World/Sphere.xformOpOrder", op_name=op, op_order_index=index) await ui_test.human_delay(3) self.assertTrue(not self.include_op_code(xform, op)) #enable all properties for op in self.xform_op_names: omni.kit.commands.execute("EnableXformOpCommand", op_attr_path="/World/Sphere." + op) await ui_test.human_delay(3) self.assertTrue(self.include_op_code(xform, op)) #undo omni.kit.commands.execute("Undo") await ui_test.human_delay(3) self.assertTrue(not self.include_op_code(xform, op)) #disable all properties for op in self.xform_op_names: omni.kit.commands.execute("EnableXformOpCommand", op_attr_path="/World/Sphere." + op) await ui_test.human_delay(3) self.assertTrue(self.include_op_code(xform, op)) index = self.get_index_op_code(xform, op) omni.kit.commands.execute("RemoveXformOpCommand", op_order_attr_path="/World/Sphere.xformOpOrder", op_name=op, op_order_index=index) await ui_test.human_delay(3) self.assertTrue(not self.include_op_code(xform, op)) #undo omni.kit.commands.execute("Undo") await ui_test.human_delay(3) self.assertTrue(self.include_op_code(xform, op)) async def test_chate_rotation_ops(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) await ui_test.human_delay(3) command_rotation_ops = ["rotateX", "rotateY", "rotateZ", "rotateXYZ", "rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "rotateXYZ"] rotation_ops = ["rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "rotateXYZ"] #FIXME: if you fix rotateX, rotateY, rotateZ UI issue, uncomment below #rotation_ops = ["rotateX", "rotateY", "rotateZ", "rotateXYZ", "rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "rotateXYZ"] sphere_prim = stage.GetObjectAtPath("/World/Sphere") sphere_xform = UsdGeom.Xformable(sphere_prim) current = "rotateXYZ" for rotation_op in command_rotation_ops: omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Sphere.xformOp:'+current), op_name='xformOp:' + current, dst_op_attr_name='xformOp:' + rotation_op, is_inverse_op=False, auto_target_layer=True) self.assertTrue(self.include_op_code(sphere_xform, "xformOp:" + rotation_op)) self.assertTrue(not self.include_op_code(sphere_xform, "xformOp:" + current)) current = rotation_op #change rotation ops cube_prim = stage.GetObjectAtPath("/World/Cube") cube_xform = UsdGeom.Xformable(cube_prim) current = "rotateXYZ" for rotation_op in rotation_ops: omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:'+current), op_name='xformOp:' + current, dst_op_attr_name='xformOp:' + rotation_op, is_inverse_op=False, auto_target_layer=True) await ui_test.human_delay(3) self.assertTrue(self.include_op_code(cube_xform, "xformOp:" + rotation_op)) self.assertTrue(not self.include_op_code(cube_xform, "xformOp:" + current)) current = rotation_op #first set current value first test_value = Gf.Vec3d(30, 60, 90) attr_name ='xformOp:' + current attr = cube_prim.GetAttribute(attr_name) attr.Set(test_value) for rotation_op in rotation_ops: #create dest attribute first #and set it dest_attr_name = 'xformOp:' + rotation_op cube_prim.CreateAttribute(dest_attr_name, Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(0, 0, 180)) omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:'+current), op_name='xformOp:' + current, dst_op_attr_name='xformOp:' + rotation_op, is_inverse_op=False, auto_target_layer=True) dest_attr = cube_prim.GetAttribute(dest_attr_name) # confirm the value is transferred diff = test_value - dest_attr.Get() self.assertTrue(diff.GetLength() < 0.1) # set new test value dest_attr.Set(test_value) current = rotation_op async def test_invalid_commands(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) await ui_test.human_delay(3) #rotation_ops = ["rotateX", "rotateY", "rotateZ", "rotateXYZ", "rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX"] rotation_ops = ["rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "rotateXYZ"] #change rotation ops cube_prim = stage.GetObjectAtPath("/World/Cube") cube_xform = UsdGeom.Xformable(cube_prim) current = "rotateXYZ" #now test failing cases below for rotation_op in rotation_ops: omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:'+current), op_name='xformOp:' + current, dst_op_attr_name='xformOp:' + rotation_op, is_inverse_op=True, auto_target_layer=False) omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:rotateXYZ'), op_name='xformOp:rotateXYZ', dst_op_attr_name='/World/Cube.xformOp:rotateZYX', is_inverse_op=False, auto_target_layer=True) omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:rotateZYX'), op_name='xformOp:rotateZYX', dst_op_attr_name='xformOp:rotateXYZ', is_inverse_op=True, auto_target_layer=True) omni.kit.commands.execute("EnableXformOpCommand", op_attr_path="/World/Sphere.testAttribute") omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/testAttribute.xformOp:rotateZYX'), op_name='xformOp:rotateG', dst_op_attr_name='xformOp:rotateL', is_inverse_op=False, auto_target_layer=False) payload = PrimSelectionPayload( weakref.ref(stage), [Sdf.Path("/World/Sphere")]) omni.kit.commands.execute('AddXformOp', payload=payload, precision=UsdGeom.XformOp.TypeInvalid, rotation_order='XYZ', add_translate_op=True, add_rotateXYZ_op=True, add_orient_op=True, add_scale_op=True, add_transform_op=True, add_pivot_op=True) async def test_xform_op_utils(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() usd_context.get_selection().set_selected_prim_paths(["/World/Sphere"], True) await ui_test.human_delay(3) self.assertTrue(get_op_type_name("Dummy") == None) # test _add_trs_op payload = PrimSelectionPayload( weakref.ref(stage), [Sdf.Path("/World/Sphere")]) settings = carb.settings.get_settings() default_xform_op_precision = settings.get("/persistent/app/primCreation/DefaultXformOpPrecision") default_rotation_order = settings.get("/persistent/app/primCreation/DefaultRotationOrder") # set to double settings.set("/persistent/app/primCreation/DefaultXformOpPrecision", "Double") _add_trs_op(payload) omni.kit.commands.execute('Undo') settings.set("/persistent/app/primCreation/DefaultXformOpPrecision", "Float") _add_trs_op(payload) omni.kit.commands.execute('Undo') settings.set("/persistent/app/primCreation/DefaultXformOpPrecision", "Half") _add_trs_op(payload) omni.kit.commands.execute('Undo') #fail test settings.destroy_item("/persistent/app/primCreation/DefaultXformOpPrecision") settings.destroy_item("/persistent/app/primCreation/DefaultRotationOrder") _add_trs_op(payload) omni.kit.commands.execute('Undo') #recover default settings.set("/persistent/app/primCreation/DefaultXformOpPrecision", default_xform_op_precision) settings.set("/persistent/app/primCreation/DefaultRotationOrder", default_rotation_order) #get_op_precision self.assertTrue(get_op_precision(Sdf.ValueTypeNames.Quatf) == UsdGeom.XformOp.PrecisionFloat) self.assertTrue(get_op_precision(Sdf.ValueTypeNames.Matrix4d) == UsdGeom.XformOp.PrecisionDouble) self.assertTrue(get_op_precision(Sdf.ValueTypeNames.Half3) == UsdGeom.XformOp.PrecisionHalf) self.assertTrue(get_op_precision(Sdf.ValueTypeNames.Color3d) == UsdGeom.XformOp.PrecisionDouble) self.assertTrue(get_inverse_op_Name(RESET_XFORM_STACK, True) == RESET_XFORM_STACK) self.assertTrue(get_inverse_op_Name("Dummy", True) == "!invert!Dummy") self.assertTrue(get_inverse_op_Name("!invert!xformOp:Dummy", False) == "xformOp:Dummy") self.assertTrue(get_op_attr_name(RESET_XFORM_STACK) == None)
16,863
Python
41.910941
162
0.631264
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_transform_context_menu.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. ## import omni.kit.test import os import sys import unittest import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.usd from pathlib import Path from omni.kit import ui_test from pxr import Gf, UsdGeom from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows ) def include_op_code(xform : UsdGeom.Xformable, op_name): xform_ops = xform.GetOrderedXformOps() for op in xform_ops: print(op.GetOpName()) if op.GetOpName() == op_name: return True return False class TransformContextMenu(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 64) extension_root_folder = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) self._usd_path = extension_root_folder.joinpath("data/test_data/test_map") # After running each test async def tearDown(self): await wait_stage_loading() @unittest.skipIf(sys.platform.startswith("linux"), "Pyperclip fails on some TeamCity agents") async def test_transform_context_menu(self): await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda")) await wait_stage_loading() usd_context = omni.usd.get_context() stage = usd_context.get_stage() # get prim attributes torus_translate = stage.GetPrimAtPath("/World/Torus").GetAttribute('xformOp:translate') cone_translate = stage.GetPrimAtPath("/World/Cone").GetAttribute('xformOp:translate') torus_rotate = stage.GetPrimAtPath("/World/Torus").GetAttribute('xformOp:rotateXYZ') cone_rotate = stage.GetPrimAtPath("/World/Cone").GetAttribute('xformOp:rotateXYZ') torus_scale = stage.GetPrimAtPath("/World/Torus").GetAttribute('xformOp:scale') cone_scale = stage.GetPrimAtPath("/World/Cone").GetAttribute('xformOp:scale') # verify transforms different self.assertNotEqual(torus_translate.Get(), cone_translate.Get()) self.assertNotEqual(torus_rotate.Get(), cone_rotate.Get()) self.assertNotEqual(torus_scale.Get(), cone_scale.Get()) # select torus await select_prims(["/World/Torus"]) await ui_test.human_delay() # right click on transform header widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Transform'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu copy await ui_test.select_context_menu("Copy All Property Values in Transform", offset=ui_test.Vec2(10, 10)) # select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() # right click on Transform header widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Transform'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu paste await ui_test.select_context_menu("Paste All Property Values to Transform", offset=ui_test.Vec2(10, 10)) # verify transforms same self.assertEqual(torus_translate.Get(), cone_translate.Get()) self.assertEqual(torus_rotate.Get(), cone_rotate.Get()) self.assertEqual(torus_scale.Get(), cone_scale.Get()) # select torus await select_prims(["/World/Torus"]) await ui_test.human_delay() # right click on Transform header widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Transform'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Reset All Property Values in Transform", offset=ui_test.Vec2(10, 10)) # verify transforms reset self.assertEqual(torus_translate.Get(), Gf.Vec3d(0, 0, 0)) self.assertEqual(torus_rotate.Get(), Gf.Vec3d(0, 0, 0)) self.assertEqual(torus_scale.Get(), Gf.Vec3d(1, 1, 1)) async def open_property_map(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() async def test_translate_context_menu(self): await self.open_property_map() usd_context = omni.usd.get_context() stage = usd_context.get_stage() #test disable/delete #right click on translate #select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() prim = stage.GetObjectAtPath("/World/Cone") xform = UsdGeom.Xformable(prim) #test translate disable/enable/delete widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Disable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(not include_op_code(xform, "xformOp:translate")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Enable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(include_op_code(xform, "xformOp:translate")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate'") #now test delete await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) await ui_test.select_context_menu("Delete", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone attr = prim.GetAttribute("xformOp:translate") self.assertTrue(not attr) async def test_pivot_context_menu(self): await self.open_property_map() usd_context = omni.usd.get_context() stage = usd_context.get_stage() #test disable/delete #right click on translate #select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() prim = stage.GetObjectAtPath("/World/Cone") xform = UsdGeom.Xformable(prim) #test translate:pivot disable/enable/delete widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate:pivot'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Disable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(not include_op_code(xform, "xformOp:translate:pivot")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate:pivot'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu resety await ui_test.select_context_menu("Enable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(include_op_code(xform, "xformOp:translate:pivot")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate:pivot'") #now test delete await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) await ui_test.select_context_menu("Delete", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone attr = prim.GetAttribute("xformOp:translate:pivot") self.assertTrue(not attr) async def test_scale_context_menu(self): await self.open_property_map() usd_context = omni.usd.get_context() stage = usd_context.get_stage() #test disable/delete #right click on translate #select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() prim = stage.GetObjectAtPath("/World/Cone") xform = UsdGeom.Xformable(prim) #test translate:pivot disable/enable/delete widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Scale'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Disable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(not include_op_code(xform, "xformOp:scale")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Scale'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu resety await ui_test.select_context_menu("Enable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(include_op_code(xform, "xformOp:scale")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Scale'") #now test delete await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) await ui_test.select_context_menu("Delete", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone attr = prim.GetAttribute("xformOp:scale") self.assertTrue(not attr) async def test_rotate_context_menu(self): await self.open_property_map() usd_context = omni.usd.get_context() stage = usd_context.get_stage() #test disable/delete #right click on translate #select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() prim = stage.GetObjectAtPath("/World/Cone") xform = UsdGeom.Xformable(prim) #test rotate rotation order change widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Rotate'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) #find ZYX label widget = ui_test.find("RotationOrder//Frame/**/Label[*].text=='ZYX'") #switch and make sure it's changed await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) self.assertTrue(not include_op_code(xform, "xformOp:rotateXYZ")) self.assertTrue(include_op_code(xform, "xformOp:rotateZYX")) #chgange it to YZX widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Rotate'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) #find YZX label widget = ui_test.find("RotationOrder//Frame/**/Label[*].text=='YZX'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) self.assertTrue(not include_op_code(xform, "xformOp:rotateZYX")) self.assertTrue(include_op_code(xform, "xformOp:rotateYZX"))
12,428
Python
43.231317
123
0.661168
omniverse-code/kit/exts/omni.kit.property.transform/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.3.5] - 2023-02-08 ### Fixed - Add Transform button's error for prims constructed from reference layer and doesn't have xformOpOrder attribute ## [1.3.4] - 2022-09-20 ### Added - Added listener for `ADDITIONAL_CHANGED_PATH_EVENT_TYPE` event in message bus to trigger additional property invalidation. ## [1.3.3] - 2022-08-03 - Linked scaling now works for resetting to defaults - Linked scaling no longer breaks when value is zero ## [1.3.2] - 2022-06-16 - Support Reset all attributes for the Transform Widget - Updating link scale button icon ## [1.3.1] - 2022-05-27 ### Changed - Support Copy/Paste all attribute for the Transform Widget - ## [1.3.0] - 2022-05-12 ### Changed - Offset mode updated to consider add/multiply operations ## [1.2.0] - 2022-04-28 ### Added - Option to link scale components - offset mode test ## [1.1.0] - 2022-03-09 ### Added - Added offset mode ## [1.0.2] - 2020-12-09 ### Changes - Added extension icon - Added readme - Updated preview image ## [1.0.1] - 2020-10-22 ### Added - removed `TransformPrimDelegate` so its now controlled by omni.kit.property.bundle ## [1.0.0] - 2020-10-7 ### Added - Created
1,250
Markdown
23.057692
123
0.6968
omniverse-code/kit/exts/omni.kit.property.transform/docs/README.md
# omni.kit.property.transform ## Introduction Property window extensions are for viewing and editing Usd Prim Attributes ## This extension supports editing of XForm transforms
180
Markdown
19.111109
74
0.805556
omniverse-code/kit/exts/omni.kit.property.transform/docs/index.rst
omni.kit.property.transform ########################### Property Transform Values .. toctree:: :maxdepth: 1 CHANGELOG
129
reStructuredText
9.833333
27
0.55814
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/__init__.py
from .scripts import * def deferred_capture(viewport_window, callback, is_hdr=False, subscription_name=None): def _get_subs_name(): import sys frame = sys._getframe(1).f_back f_code = frame.f_code filepath = f_code.co_filename lineno = frame.f_lineno return "VP capt %s:%d" % (filepath[-40:], lineno) class CaptureHelper: def capture_function(self, event): self.deferred_capture_subs = None if is_hdr: viewport_rp_resource = viewport_window.get_drawable_hdr_resource() else: viewport_rp_resource = viewport_window.get_drawable_ldr_resource() callback(viewport_rp_resource) if subscription_name is None: subscription_name = _get_subs_name() capture_helper = CaptureHelper() capture_helper.deferred_capture_subs = viewport_window.get_ui_draw_event_stream().create_subscription_to_pop( capture_helper.capture_function, name=subscription_name )
1,031
Python
32.290322
113
0.629486
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/external_drag_drop_helper.py
import os import re import pathlib from pxr import Sdf, Tf from typing import List from omni.kit.window.drop_support import ExternalDragDrop external_drag_drop = None def setup_external_drag_drop(window_name :str): global external_drag_drop destroy_external_drag_drop() external_drag_drop = ExternalDragDrop(window_name=window_name, drag_drop_fn=_on_ext_drag_drop) def destroy_external_drag_drop(): global external_drag_drop if external_drag_drop: external_drag_drop.destroy() external_drag_drop = None def _on_ext_drag_drop(edd: ExternalDragDrop, payload: List[str]): import omni.usd import omni.kit.undo import omni.kit.commands default_prim_path = Sdf.Path("/") stage = omni.usd.get_context().get_stage() if stage.HasDefaultPrim(): default_prim_path = stage.GetDefaultPrim().GetPath() re_audio = re.compile(r"^.*\.(wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus)(\?.*)?$", re.IGNORECASE) re_usd = re.compile(r"^.*\.(usd|usda|usdc|usdz)(\?.*)?$", re.IGNORECASE) for source_url in edd.expand_payload(payload): if re_usd.match(source_url): try: import omni.kit.window.file omni.kit.window.file.open_stage(source_url.replace(os.sep, '/')) except ImportError: import carb carb.log_warn(f'Failed to import omni.kit.window.file - Cannot open stage {source_url}') return with omni.kit.undo.group(): for source_url in edd.expand_payload(payload): if re_audio.match(source_url): stem = pathlib.Path(source_url).stem path = default_prim_path.AppendChild(Tf.MakeValidIdentifier(stem)) omni.kit.commands.execute( "CreateAudioPrimFromAssetPath", path_to=path, asset_path=source_url, usd_context=omni.usd.get_context(), )
1,973
Python
33.034482
104
0.618348
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/commands.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.commands import omni.kit.viewport_legacy import omni.usd from pxr import Sdf, UsdGeom, Usd from typing import Union def get_viewport_window_from_name(viewport_name: str): vp = omni.kit.viewport_legacy.get_viewport_interface() instance = vp.get_instance(viewport_name) if instance: return vp.get_viewport_window(instance) return None class SetActiveViewportCameraCommand(omni.kit.commands.Command): """ Sets Viewport's actively bound camera to given camera at give path. Args: new_active_cam_path (Union[str, Sdf.Path): new camera path to bind to viewport. viewport_name (str): name of the viewport to set active camera (for multi-viewport). """ def __init__(self, new_active_cam_path: Union[str, Sdf.Path], viewport_name: str = ""): self._new_active_cam_path = str(new_active_cam_path) self._viewport_window = get_viewport_window_from_name(viewport_name) if not viewport_name and not self._viewport_window: self._viewport_window = omni.kit.viewport_legacy.get_default_viewport_window() self._prev_active_camera = None def do(self): if not self._viewport_window: return self._prev_active_camera = self._viewport_window.get_active_camera() self._viewport_window.set_active_camera(self._new_active_cam_path) def undo(self): if not self._viewport_window: return self._viewport_window.set_active_camera(self._prev_active_camera) class DuplicateFromActiveViewportCameraCommand(omni.kit.commands.Command): """ Duplicates Viewport's actively bound camera and bind active camera to the duplicated one. Args: viewport_name (str): name of the viewport to set active camera (for multi-viewport). """ def __init__(self, viewport_name: str = ""): self._viewport_name = viewport_name self._viewport_window = get_viewport_window_from_name(viewport_name) if not viewport_name and not self._viewport_window: self._viewport_window = omni.kit.viewport_legacy.get_default_viewport_window() self._usd_context_name = "" self._usd_context = omni.usd.get_context("") # TODO get associated usd_context from Viewport itself self._prev_active_camera = None def do(self): if not self._viewport_window: return self._prev_active_camera = self._viewport_window.get_active_camera() if self._prev_active_camera: stage = self._usd_context.get_stage() target_path = omni.usd.get_stage_next_free_path(stage, "/Camera", True) old_prim = stage.GetPrimAtPath(self._prev_active_camera) omni.kit.commands.execute("CreatePrim", prim_path=target_path, prim_type="Camera") new_prim = stage.GetPrimAtPath(target_path) if old_prim and new_prim: # copy attributes timeline = omni.timeline.get_timeline_interface() timecode = timeline.get_current_time() * stage.GetTimeCodesPerSecond() for attr in old_prim.GetAttributes(): value = attr.Get(timecode) if value is not None: new_prim.CreateAttribute(attr.GetName(), attr.GetTypeName()).Set(value) default_prim = stage.GetDefaultPrim() # OM-35156: It's possible that transform of default prim is not identity. # And it tries to copy a camera that's outside of the default prim tree. # It needs to be transformed to the default prim space. if default_prim and default_prim.IsA(UsdGeom.Xformable): default_prim_world_mtx = omni.usd.get_world_transform_matrix(default_prim, timecode) old_camera_prim_world_mtx = omni.usd.get_world_transform_matrix(old_prim, timecode) new_camera_prim_local_mtx = old_camera_prim_world_mtx * default_prim_world_mtx.GetInverse() omni.kit.commands.execute( "TransformPrim", path=new_prim.GetPath(), new_transform_matrix=new_camera_prim_local_mtx ) omni.usd.editor.set_no_delete(new_prim, False) omni.kit.commands.execute( "SetActiveViewportCamera", new_active_cam_path=target_path, viewport_name=self._viewport_name ) def undo(self): pass omni.kit.commands.register_all_commands_in_module(__name__)
5,022
Python
42.301724
113
0.644166
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/__init__.py
from .context_menu import * from .viewport import * from .commands import *
75
Python
24.333325
27
0.76
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/context_menu.py
# Copyright (c) 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. # import asyncio import omni.ext import carb import carb.settings import omni.kit.ui from .viewport import get_viewport_interface from .external_drag_drop_helper import setup_external_drag_drop, destroy_external_drag_drop class Extension(omni.ext.IExt): def on_startup(self): # get window event stream viewport_win = get_viewport_interface().get_viewport_window() # on_mouse_event called when event dispatched if viewport_win: self._stage_event_sub = viewport_win.get_mouse_event_stream().create_subscription_to_pop(self.on_mouse_event) self._menu_path = "Window/New Viewport Window" self._editor_menu = omni.kit.ui.get_editor_menu() if self._editor_menu is not None: self._menu = self._editor_menu.add_item(self._menu_path, self._on_menu_click, False, priority=200) # external drag/drop if viewport_win: setup_external_drag_drop("Viewport") def on_shutdown(self): # remove event self._stage_event_sub = None destroy_external_drag_drop() def _on_menu_click(self, menu, toggled): async def new_viewport(): await omni.kit.app.get_app().next_update_async() viewportFactory = get_viewport_interface() viewportHandle = viewportFactory.create_instance() window = viewportFactory.get_viewport_window(viewportHandle) window.set_window_size(350, 350) asyncio.ensure_future(new_viewport()) def on_mouse_event(self, event): # check its expected event if event.type == int(omni.kit.ui.MenuEventType.ACTIVATE): if carb.settings.get_settings().get("/exts/omni.kit.window.viewport/showContextMenu"): self.show_context_menu(event.payload) def show_context_menu(self, payload: dict): viewport_win = get_viewport_interface().get_viewport_window() usd_context_name = viewport_win.get_usd_context_name() #This is actuall world-position ! world_position = payload.get('mouse_pos_x', None) if world_position is not None: world_position = ( world_position, payload['mouse_pos_y'], payload['mouse_pos_z'] ) try: from omni.kit.context_menu import ViewportMenu ViewportMenu.show_menu( usd_context_name, payload.get('prim_path', None), world_position ) except ImportError: carb.log_error('omni.kit.context_menu must be loaded to use the context menu') @staticmethod def add_menu(menu_dict): """ Add the menu to the end of the context menu. Return the object that should be alive all the time. Once the returned object is destroyed, the added menu is destroyed as well. """ return omni.kit.context_menu.add_menu(menu_dict, "MENU", "omni.kit.window.viewport") @staticmethod def add_create_menu(menu_dict): """ Add the menu to the end of the stage context create menu. Return the object that should be alive all the time. Once the returned object is destroyed, the added menu is destroyed as well. """ return omni.kit.context_menu.add_menu(menu_dict, "CREATE", "omni.kit.window.viewport")
3,774
Python
39.159574
121
0.653683
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/viewport.py
# Because ExtensionWindowHandle is used, we should get rid of it really: import omni.kit.extensionwindow import asyncio import carb import copy from .._viewport_legacy import * from omni.hydra.engine.stats import HydraEngineStats, get_mem_stats import warnings def get_viewport_interface(): """Returns cached :class:`omni.kit.viewport_legacy.IViewport` interface""" if not hasattr(get_viewport_interface, "viewport"): get_viewport_interface.viewport = acquire_viewport_interface() return get_viewport_interface.viewport def get_default_viewport_window(): """Returns default (first) Viewport Window if available""" viewport = get_viewport_interface() if viewport: return viewport.get_viewport_window() return None def menu_update(menu_path, visible): # get the correct viewport window as there can be multiple vp_iface = omni.kit.viewport_legacy.get_viewport_interface() viewports = vp_iface.get_instance_list() for viewport in viewports: if menu_path.endswith(vp_iface.get_viewport_window_name(viewport)): viewport_window = vp_iface.get_viewport_window(viewport) viewport_window.show_hide_window(visible) omni.kit.ui.get_editor_menu().set_value(menu_path, visible) async def _query_next_picked_world_position_async(self) -> carb.Double3: """Asynchronous version of :func:`IViewportWindow.query_next_picked_world_position`. Return a ``carb.Double3``. If no position is sampled, the returned object is None.""" f = asyncio.Future() def cb(pos): f.set_result(copy.deepcopy(pos)) self.query_next_picked_world_position(cb) return await f IViewportWindow.query_next_picked_world_position_async = _query_next_picked_world_position_async def get_nested_gpu_profiler_result(vw: IViewportWindow, max_indent: int = 1): warnings.warn( "IViewportWindow.get_nested_gpu_profiler_result is deprecated, use omni.hydra.engine.stats.HydraEngineStats instead", DeprecationWarning ) return HydraEngineStats(vw.get_usd_context_name(), vw.get_active_hydra_engine()).get_nested_gpu_profiler_result(max_indent) def get_gpu_profiler_result(vw: IViewportWindow): warnings.warn( "IViewportWindow.get_gpu_profiler_result is deprecated, use omni.hydra.engine.stats.HydraEngineStats instead", DeprecationWarning ) return HydraEngineStats(vw.get_usd_context_name(), vw.get_active_hydra_engine()).get_gpu_profiler_result() def save_gpu_profiler_result_to_json(vw: IViewportWindow, file_name: str): warnings.warn( "IViewportWindow.save_gpu_profiler_result_to_json is deprecated, use omni.hydra.engine.stats.HydraEngineStats instead", DeprecationWarning ) return HydraEngineStats(vw.get_usd_context_name(), vw.get_active_hydra_engine()).save_gpu_profiler_result_to_json(file_name) def reset_gpu_profiler_containers(vw: IViewportWindow): warnings.warn( "IViewportWindow.reset_gpu_profiler_containers is deprecated, use omni.hydra.engine.stats.HydraEngineStats instead", DeprecationWarning ) return HydraEngineStats(vw.get_usd_context_name(), vw.get_active_hydra_engine()).reset_gpu_profiler_containers() def get_mem_stats_result(vw: IViewportWindow, detailed: bool = False): warnings.warn( "IViewportWindow.get_mem_stats_result is deprecated, use omni.hydra.engine.stats.get_mem_stats instead", DeprecationWarning ) return get_mem_stats(detailed) IViewportWindow.get_nested_gpu_profiler_result = get_nested_gpu_profiler_result IViewportWindow.get_gpu_profiler_result = get_gpu_profiler_result IViewportWindow.save_gpu_profiler_result_to_json = save_gpu_profiler_result_to_json IViewportWindow.reset_gpu_profiler_containers = reset_gpu_profiler_containers IViewportWindow.get_mem_stats_result = get_mem_stats_result
3,877
Python
40.255319
128
0.740005
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/camera_tests.py
# Copyright (c) 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. # import asyncio import os import tempfile import uuid import carb import omni.kit.commands import omni.kit.test import omni.kit.viewport_legacy from pxr import Gf, Usd, UsdGeom, Sdf from omni.kit.test_suite.helpers import arrange_windows class TestViewportWindowCamera(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() # After running each test async def tearDown(self): pass async def test_builtin_camera_settings(self): async def test_builtin_camera_settings_inner(modify_camera=False): await omni.usd.get_context().new_stage_async() # Waiting one frame after the new stage, so in sync load cases # the USD context had a chance to launch a preSync event await omni.kit.app.get_app().next_update_async() viewport_window = omni.kit.viewport_legacy.get_default_viewport_window() omni.kit.commands.execute("CreatePrim", prim_type="Sphere") camera_paths = ["/OmniverseKit_Persp", "/OmniverseKit_Front", "/OmniverseKit_Top", "/OmniverseKit_Right"] camera_names = ["Perspective", "Front", "Top", "Right"] positions = [] targets = [] if modify_camera: viewport_window.set_camera_position("/OmniverseKit_Persp", 100, 200, 300, True) viewport_window.set_camera_target("/OmniverseKit_Persp", 300, 200, 100, True) viewport_window.set_active_camera("/OmniverseKit_Front") for i in range(len(camera_paths)): position = viewport_window.get_camera_position(camera_paths[i]) self.assertTrue(position[0]) positions.append(Gf.Vec3d(position[1], position[2], position[3])) target = viewport_window.get_camera_target(camera_paths[i]) self.assertTrue(target[0]) targets.append(Gf.Vec3d(target[1], target[2], target[3])) active_camera = viewport_window.get_active_camera() with tempfile.TemporaryDirectory() as tmpdirname: tmpfilename = os.path.join(tmpdirname, f"camTest_{str(uuid.uuid4())}.usda") carb.log_info("Saving temp camera path as %s" % (tmpfilename)) await omni.usd.get_context().save_as_stage_async(tmpfilename) await omni.usd.get_context().reopen_stage_async() await omni.kit.app.get_app().next_update_async() for i in range(len(camera_names)): carb.log_info("Testing %s" % (camera_names[i])) # Position only saved for Persp camera if i == 0: saved_position = viewport_window.get_camera_position(camera_paths[i]) self.assertTrue(saved_position[0]) saved_position = Gf.Vec3d(saved_position[1], saved_position[2], saved_position[3]) carb.log_info("Comparing Positions: (%f,%f,%f) to (%f,%f,%f)" % (positions[i][0], positions[i][1], positions[i][2], saved_position[0], saved_position[1], saved_position[2])) self.assertTrue( Gf.IsClose(positions[i], saved_position, 0.000001), f"Camera position mismatched! {positions[i]} is not close to {saved_position}", ) saved_target = viewport_window.get_camera_target(camera_paths[i]) self.assertTrue(saved_target[0]) saved_target = Gf.Vec3d(saved_target[1], saved_target[2], saved_target[3]) active_camera_saved = viewport_window.get_active_camera() carb.log_info("Comparing Targets: (%f,%f,%f) to (%f,%f,%f)" % (targets[i][0], targets[i][1], targets[i][2], saved_target[0], saved_target[1], saved_target[2])) self.assertTrue( Gf.IsClose(targets[i], saved_target, 0.000001), f"Camera target mismatched! {targets[i]} is not close to {saved_target}", ) if modify_camera and i == 0: self.assertTrue(Gf.IsClose(positions[i], Gf.Vec3d(100, 200, 300), 0.000001)) self.assertTrue(Gf.IsClose(targets[i], Gf.Vec3d(300, 200, 100), 0.000001)) self.assertTrue( active_camera == active_camera_saved, f"Active camera mismatched! {active_camera} is not equal to {active_camera_saved}", ) # test default camera settings carb.log_info("Testing default camera settings") await test_builtin_camera_settings_inner() # test modified camera settings carb.log_info("Testing modified camera settings") await test_builtin_camera_settings_inner(True) async def test_camera_duplicate_from_static_active_camera(self): # Test for OM-35156 await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() stage = omni.usd.get_context().get_stage() prim = UsdGeom.Xform.Define(stage, "/World") stage.SetDefaultPrim(prim.GetPrim()) default_prim = stage.GetDefaultPrim() UsdGeom.XformCommonAPI(default_prim).SetTranslate(Gf.Vec3d(100, 0, 0)) perspective_camera = stage.GetPrimAtPath("/OmniverseKit_Persp") persp_camera_world_mtx = omni.usd.get_world_transform_matrix(perspective_camera) default_prim_world_mtx = omni.usd.get_world_transform_matrix(default_prim) omni.kit.commands.execute( "SetActiveViewportCamera", new_active_cam_path=perspective_camera.GetPath(), viewport_name="" ) await omni.kit.app.get_app().next_update_async() omni.kit.commands.execute("DuplicateFromActiveViewportCamera") await omni.kit.app.get_app().next_update_async() # The name of it will be Camera new_camera_prim = stage.GetPrimAtPath(default_prim.GetPath().AppendElementString("Camera")) new_camera_local_mtx = omni.usd.get_local_transform_matrix(new_camera_prim) local_mtx = persp_camera_world_mtx * default_prim_world_mtx.GetInverse() self.assertTrue(Gf.IsClose(new_camera_local_mtx, local_mtx, 0.000001)) async def test_camera_duplicate_from_animated_active_camera(self): # Test for OM-33581 layer_with_animated_camera = """\ #usda 1.0 ( customLayerData = { } defaultPrim = "World" endTimeCode = 619 framesPerSecond = 24 metersPerUnit = 0.01 startTimeCode = 90 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" ( kind = "assembly" ) { def Camera "SHOTCAM" { float2 clippingRange = (10, 10000) custom bool depthOfField = 0 float focalLength = 35 float focalLength.timeSamples = { 172: 35, 173: 34.650208 } float focusDistance = 5 float fStop = 5.6 float horizontalAperture = 35.999928 float verticalAperture = 20.22853 float3 xformOp:rotateXYZ.timeSamples = { 90: (8.786562, -19.858515, -1.2905762), 91: (8.744475, -19.858515, -1.274945) } float3 xformOp:scale.timeSamples = { 90: (12.21508, 12.21508, 12.21508) } double3 xformOp:translate.timeSamples = { 90: (-462.44292428348126, 1734.9897515804505, -2997.4519412288555), 151: (-462.4429242834828, 1734.9897515804498, -2997.451941228857) } uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } } """ format = Sdf.FileFormat.FindByExtension(".usd") root_layer = Sdf.Layer.CreateAnonymous("world.usd", format) root_layer.ImportFromString(layer_with_animated_camera) stage = Usd.Stage.Open(root_layer) await omni.usd.get_context().attach_stage_async(stage) await omni.kit.app.get_app().next_update_async() old_camera = stage.GetPrimAtPath("/World/SHOTCAM") omni.kit.commands.execute( "SetActiveViewportCamera", new_active_cam_path="/World/SHOTCAM", viewport_name="" ) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() omni.kit.commands.execute("DuplicateFromActiveViewportCamera") await omni.kit.app.get_app().next_update_async() new_camera = stage.GetPrimAtPath("/World/Camera") self.assertTrue(new_camera) timeline = omni.timeline.get_timeline_interface() timecode = timeline.get_current_time() * stage.GetTimeCodesPerSecond() old_matrix = omni.usd.get_world_transform_matrix(old_camera, timecode) new_matrix = omni.usd.get_world_transform_matrix(new_camera) self.assertTrue(Gf.IsClose(new_matrix, old_matrix, 0.000001)) # Set time code to the second timecode of rotateXYZ, so they are not equal. timeline.set_current_time(float(91.0 / stage.GetTimeCodesPerSecond())) timecode = timeline.get_current_time() * stage.GetTimeCodesPerSecond() old_matrix = omni.usd.get_world_transform_matrix(old_camera, timecode) self.assertFalse(Gf.IsClose(new_matrix, old_matrix, 0.000001)) # Make another duplicate that's duplicated from updated time. omni.kit.commands.execute( "SetActiveViewportCamera", new_active_cam_path="/World/SHOTCAM", viewport_name="" ) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() omni.kit.commands.execute("DuplicateFromActiveViewportCamera") await omni.kit.app.get_app().next_update_async() new_camera = stage.GetPrimAtPath("/World/Camera_01") self.assertTrue(new_camera) old_matrix = omni.usd.get_world_transform_matrix(old_camera, timecode) new_matrix = omni.usd.get_world_transform_matrix(new_camera) self.assertTrue(Gf.IsClose(new_matrix, old_matrix, 0.000001)) async def test_layer_clear_to_remove_camera_deltas(self): # Test for OM-47804 await omni.usd.get_context().new_stage_async() for _ in range(10): # Create anonymous layer and set edit target stage = omni.usd.get_context().get_stage() replicator_layer = None for layer in stage.GetLayerStack(): if layer.GetDisplayName() == "Replicator": replicator_layer = layer break if replicator_layer is None: root = stage.GetRootLayer() replicator_layer = Sdf.Layer.CreateAnonymous(tag="Replicator") root.subLayerPaths.append(replicator_layer.identifier) omni.usd.set_edit_target_by_identifier(stage, replicator_layer.identifier) # Clear prim and assert not valid replicator_layer.Clear() self.assertFalse(stage.GetPrimAtPath("/ReplicatorPrim").IsValid()) # Define some prim on the layer stage.DefinePrim("/ReplicatorPrim", "Camera")
12,035
Python
45.832685
197
0.602659
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/create_prims.py
import os import random import carb import omni.usd import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux def create_test_stage(): stage = omni.usd.get_context().get_stage() rootname = stage.GetDefaultPrim().GetPath().pathString prim_list1 = [] prim_list2 = [] # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=False ) # create material 1 mtl_created_list = [] omni.kit.commands.execute( "CreateAndBindMdlMaterialFromLibrary", mdl_name="OmniPBR.mdl", mtl_name="OmniPBR", mtl_created_list=mtl_created_list, ) mtl_path1 = mtl_created_list[0] # create material 2 mtl_created_list = [] omni.kit.commands.execute( "CreateAndBindMdlMaterialFromLibrary", mdl_name="OmniGlass.mdl", mtl_name="OmniGlass", mtl_created_list=mtl_created_list, ) mtl_path2 = mtl_created_list[0] # create prims & bind material random_list = {} samples = 100 for index in random.sample(range(samples), int(samples / 2)): random_list[index] = 0 strengths = [UsdShade.Tokens.strongerThanDescendants, UsdShade.Tokens.weakerThanDescendants] for index in range(samples): prim_path = omni.usd.get_stage_next_free_path(stage, "{}/TestCube_{}".format(rootname, index), False) omni.kit.commands.execute("CreatePrim", prim_path=prim_path, prim_type="Cube") if index in random_list: omni.kit.commands.execute( "BindMaterial", prim_path=prim_path, material_path=mtl_path1, strength=strengths[index & 1] ) prim_list1.append(prim_path) elif (index & 3) != 0: omni.kit.commands.execute( "BindMaterial", prim_path=prim_path, material_path=mtl_path2, strength=strengths[index & 1] ) prim_list2.append(prim_path) return [(mtl_path1, prim_list1), (mtl_path2, prim_list2)] def create_and_select_cube(): stage = omni.usd.get_context().get_stage() rootname = stage.GetDefaultPrim().GetPath().pathString prim_path = "{}/Cube".format(rootname) # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path=prim_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100} ) return prim_path
2,464
Python
31.012987
109
0.635958
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/context_tests.py
import asyncio import carb import omni.usd import omni.kit.test import omni.kit.viewport_legacy import omni.timeline from pxr import Usd, UsdGeom, Gf, Sdf from omni.kit.test_suite.helpers import arrange_windows, wait_stage_loading # 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 ViewportContextTest(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() self._usd_context = omni.usd.get_context() await self._usd_context.new_stage_async() # After running each test async def tearDown(self): await wait_stage_loading() async def _create_test_stage(self): # Create the objects test_list = omni.kit.viewport_legacy.tests.create_test_stage() # Wait so that the test does not exit before MDL loaded and crash on exit. while True: try: event, payload = await asyncio.wait_for(self._usd_context.next_stage_event_async(), timeout=60.0) if event == int(omni.usd.StageEventType.ASSETS_LOADED): break except asyncio.TimeoutError: _, files_loaded, total_files = self._usd_context.get_stage_loading_status() if files_loaded == total_files: carb.log_warn("Timed out waiting for ASSETS_LOADED event. Is MDL already loaded?") break return test_list # Simulate a mouse-click-selection at pos (x,y) in viewport async def _simulate_mouse_selection(self, viewport, pos): app = omni.kit.app.get_app() mouse = omni.appwindow.get_default_app_window().get_mouse() input_provider = carb.input.acquire_input_provider() async def simulate_mouse_click(): input_provider.buffer_mouse_event(mouse, carb.input.MouseEventType.MOVE, pos, 0, pos) input_provider.buffer_mouse_event(mouse, carb.input.MouseEventType.LEFT_BUTTON_DOWN, pos, 0, pos) await app.next_update_async() input_provider.buffer_mouse_event(mouse, carb.input.MouseEventType.LEFT_BUTTON_UP, pos, 0, pos) await app.next_update_async() # You're guess as good as mine. # Need to start and end with one wait, then need 12 more waits for mouse click loop_counts = (1, 5) for i in range(loop_counts[0]): await app.next_update_async() # Is this really to sync up carb and imgui state ? for i in range(loop_counts[1]): await simulate_mouse_click() # Enable picking and do the selection viewport.request_picking() await simulate_mouse_click() # Almost done! for i in range(loop_counts[0]): await app.next_update_async() # Actual test, notice it is "async" function, so "await" can be used if needed # # But why does this test exist in Viewport?? async def test_bound_objects(self): return # Create the objects usd_context, test_list = self._usd_context, await self._create_test_stage() self.assertIsNotNone(usd_context) self.assertIsNotNone(test_list) objects = {} stage = omni.usd.get_context().get_stage() objects["stage"] = stage for mtl, mtl_prims in test_list: # Select material prim objects["prim_list"] = [stage.GetPrimAtPath(Sdf.Path(mtl))] # Run select_prims_using_material omni.kit.context_menu.get_instance().select_prims_using_material(objects) # Verify selected prims prims = omni.usd.get_context().get_selection().get_selected_prim_paths() self.assertTrue(prims == mtl_prims) async def test_create_and_select(self): viewport_interface = omni.kit.viewport_legacy.acquire_viewport_interface() viewport = viewport_interface.get_viewport_window() viewport.set_enabled_picking(True) viewport.set_window_pos(0, 0) viewport.set_window_size(400, 400) # Create the objects usd_context, cube_path = self._usd_context, omni.kit.viewport_legacy.tests.create_and_select_cube() self.assertIsNotNone(usd_context) self.assertIsNotNone(cube_path) self.assertEqual([], self._usd_context.get_selection().get_selected_prim_paths()) await self._simulate_mouse_selection(viewport, (200, 230)) self.assertEqual([cube_path], self._usd_context.get_selection().get_selected_prim_paths())
4,610
Python
38.75
142
0.642082
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/mouse_raycast_tests.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import carb.input import omni.appwindow import omni.kit.commands import omni.kit.test import omni.kit.viewport_legacy import omni.usd from carb.input import KeyboardInput as Key from omni.kit.test_suite.helpers import arrange_windows class TestViewportMouseRayCast(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows(hide_viewport=True) self._input_provider = carb.input.acquire_input_provider() app_window = omni.appwindow.get_default_app_window() self._mouse = app_window.get_mouse() self._keyboard = app_window.get_keyboard() self._app = omni.kit.app.get_app() self._usd_context = omni.usd.get_context() await self._usd_context.new_stage_async() viewport_interface = omni.kit.viewport_legacy.acquire_viewport_interface() self._viewport = viewport_interface.get_viewport_window() self._viewport.set_enabled_picking(True) self._viewport.set_window_pos(0, 0) self._viewport.set_window_size(400, 400) self._viewport.show_hide_window(True) await self._app.next_update_async() # After running each test async def tearDown(self): pass async def test_viewport_mouse_raycast(self): stage_update = omni.stageupdate.get_stage_update_interface() stage_subscription = stage_update.create_stage_update_node( "viewport_mouse_raycast_test", on_raycast_fn=self._on_ray_cast ) test_data = [ ( "/OmniverseKit_Persp", (499.058, 499.735, 499.475), (-0.848083, -0.23903, -0.472884), ), ( "/OmniverseKit_Front", (-127.551, 165.44, 30000), (0, 0, -1), ), ( "/OmniverseKit_Top", (127.551, 30000, 165.44), (0, -1, 0), ), ( "/OmniverseKit_Right", (-30000, 165.44, -127.551), (1, 0, 0), ), ] for data in test_data: self._raycast_data = None self._viewport.set_active_camera(data[0]) await self._app.next_update_async() self._input_provider.buffer_mouse_event( self._mouse, carb.input.MouseEventType.MOVE, (100, 100), 0, (100, 100) ) await self._app.next_update_async() # Hold SHIFT down to start raycast self._input_provider.buffer_keyboard_key_event( self._keyboard, carb.input.KeyboardEventType.KEY_PRESS, Key.LEFT_SHIFT, 0 ) await self._app.next_update_async() self._input_provider.buffer_keyboard_key_event( self._keyboard, carb.input.KeyboardEventType.KEY_RELEASE, Key.LEFT_SHIFT, 0 ) await self._app.next_update_async() self._input_provider.buffer_mouse_event(self._mouse, carb.input.MouseEventType.MOVE, (0, 0), 0, (0, 0)) await self._app.next_update_async() self.assertIsNotNone(self._raycast_data) self.assertAlmostEqual(self._raycast_data[0][0], data[1][0], 3) self.assertAlmostEqual(self._raycast_data[0][1], data[1][1], 3) self.assertAlmostEqual(self._raycast_data[0][2], data[1][2], 3) self.assertAlmostEqual(self._raycast_data[1][0], data[2][0], 3) self.assertAlmostEqual(self._raycast_data[1][1], data[2][1], 3) self.assertAlmostEqual(self._raycast_data[1][2], data[2][2], 3) stage_subscription = None def _on_ray_cast(self, orig, dir, input): self._raycast_data = (orig, dir) print(self._raycast_data)
4,239
Python
35.551724
115
0.598726
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/drag_drop_multi_material_viewport.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. ## import os import omni.kit.app import omni.kit.test import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows ) from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class ZZViewportDragDropMaterialMulti(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) # After running each test async def tearDown(self): await wait_stage_loading() def _verify_material(self, stage, mtl_name, to_select): # verify material created prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()] self.assertTrue(f"/World/Looks/{mtl_name}" in prim_paths) self.assertTrue(f"/World/Looks/{mtl_name}/Shader" in prim_paths) # verify bound material if to_select: for prim_path in to_select: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, f"/World/Looks/{mtl_name}") def choose_material(self, mdl_list, excluded_list): # need to skip any multi-subid materials exclude_multi = {} for _, mdl_path, _ in mdl_list: mdl_name = os.path.splitext(os.path.basename(mdl_path))[0] if not mdl_name in exclude_multi: exclude_multi[mdl_name] = 1 else: exclude_multi[mdl_name] += 1 for _, mdl_path, _ in mdl_list: mdl_name = os.path.splitext(os.path.basename(mdl_path))[0] if mdl_name not in excluded_list and exclude_multi[mdl_name] < 2: return mdl_path, mdl_name return None, None async def test_l1_drag_drop_single_material_viewport(self): from carb.input import KeyboardInput await ui_test.find("Content").focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() to_select = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"] await wait_stage_loading() # verify bound materials before DnD for prim_path, material_path in [("/World/Cube", "/World/Looks/OmniGlass"), ("/World/Cone", "/World/Looks/OmniPBR"), ("/World/Sphere", "/World/Looks/OmniGlass"), ("/World/Cylinder", "/World/Looks/OmniPBR")]: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path) # drag to center of viewport window # NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used viewport_window = ui_test.find("Viewport") viewport_window = ui_test.find("Viewport") await viewport_window.focus() drag_target = viewport_window.center # select prim await select_prims(to_select) # wait for UI to update await ui_test.human_delay() # get paths mdl_list = await omni.kit.material.library.get_mdl_list_async() mdl_path1, mdl_name = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR"]) # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.drag_and_drop_tree_view(mdl_path1, drag_target=drag_target) # wait for material to load & UI to refresh await wait_stage_loading() # verify bound materials after DnD - Should be unchanged for prim_path, material_path in [("/World/Cube", "/World/Looks/OmniGlass"), ("/World/Cone", f"/World/Looks/{mdl_name}"), ("/World/Sphere", "/World/Looks/OmniGlass"), ("/World/Cylinder", "/World/Looks/OmniPBR")]: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path) async def test_l1_drag_drop_multi_material_viewport(self): from carb.input import KeyboardInput await ui_test.find("Content").focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() to_select = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"] expected_list = [("/World/Cube", "/World/Looks/OmniGlass"), ("/World/Cone", "/World/Looks/OmniPBR"), ("/World/Sphere", "/World/Looks/OmniGlass"), ("/World/Cylinder", "/World/Looks/OmniPBR")] await wait_stage_loading() # verify bound materials before DnD for prim_path, material_path in expected_list: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path) # drag to center of viewport window # NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used viewport_window = ui_test.find("Viewport") await viewport_window.focus() drag_target = viewport_window.center # select prim await select_prims(to_select) # wait for UI to update await ui_test.human_delay() # get paths mdl_list = await omni.kit.material.library.get_mdl_list_async() mdl_path1, mdl_name1 = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR"]) mdl_path2, mdl_name2 = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR", mdl_name1]) # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: dir_url = os.path.dirname(os.path.commonprefix([mdl_path1, mdl_path2])) filenames = [os.path.basename(url) for url in [mdl_path1, mdl_path2]] await content_browser_helper.drag_and_drop_tree_view(dir_url, names=filenames, drag_target=drag_target) # wait for material to load & UI to refresh await wait_stage_loading() # verify bound materials after DnD - Should be unchanged for prim_path, material_path in expected_list: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path)
7,880
Python
46.475903
219
0.65698
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/window_tests.py
# Copyright (c) 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. # import omni.kit.test from omni.kit.viewport.utility import get_active_viewport_window class TestViewportWindowShowHide(omni.kit.test.AsyncTestCase): async def test_window_show_hide(self): # Test that multiple show-hide invocations of a window doesn't crash await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() # Show hide 10 times, and wait 60 frames between a show hide # This does make the test take 10 seconds, but might be a bit # more representative of real-world usage when it. nwaits = 60 nitrations = 10 viewport, viewport_window = get_active_viewport_window() for x in range(nitrations): viewport_window.visible = True for x in range(nwaits): await omni.kit.app.get_app().next_update_async() viewport_window.visible = False for x in range(nwaits): await omni.kit.app.get_app().next_update_async() for x in range(nitrations): viewport_window.visible = False for x in range(nwaits): await omni.kit.app.get_app().next_update_async() viewport_window.visible = True for x in range(nwaits): await omni.kit.app.get_app().next_update_async()
1,774
Python
40.279069
76
0.666291
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/__init__.py
from .draw_tests import * from .context_tests import * from .create_prims import * from .camera_tests import * from .mouse_raycast_tests import * # these tests must be last or test_viewport_mouse_raycast fails. from .multi_descendents_dialog import * from .drag_drop_multi_material_viewport import * from .drag_drop_looks_material_viewport import *
349
Python
33.999997
64
0.776504
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/draw_tests.py
import carb.dictionary import omni.usd import omni.kit.test import omni.kit.viewport_legacy import omni.timeline from pxr import Usd, UsdGeom, Gf, Sdf from omni.kit.test_suite.helpers import arrange_windows # 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 ViewportDrawTest(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() # 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_ui_draw_event_payload(self): dictionary_interface = carb.dictionary.get_dictionary() viewport_interface = omni.kit.viewport_legacy.acquire_viewport_interface() viewport = viewport_interface.get_viewport_window() draw_event_stream = viewport.get_ui_draw_event_stream() CAM_PATH = "/OmniverseKit_Persp" usd_context = omni.usd.get_context() stage = usd_context.get_stage() cam_prim = stage.GetPrimAtPath(CAM_PATH) camera = UsdGeom.Camera(cam_prim) timeline_interface = omni.timeline.get_timeline_interface() timecode = timeline_interface.get_current_time() * stage.GetTimeCodesPerSecond() gf_camera = camera.GetCamera(timecode) expected_transform = gf_camera.transform expected_viewport_rect = viewport.get_viewport_rect() def uiDrawCallback(event): events_data = dictionary_interface.get_dict_copy(event.payload) vm = events_data["viewMatrix"] viewMatrix = Gf.Matrix4d( vm[0], vm[1], vm[2], vm[3], vm[4], vm[5], vm[6], vm[7], vm[8], vm[9], vm[10], vm[11], vm[12], vm[13], vm[14], vm[15], ).GetInverse() self.assertTrue(Gf.IsClose(expected_transform, viewMatrix, 0.00001)) vr = events_data["viewportRect"] self.assertAlmostEqual(expected_viewport_rect[0], vr[0]) self.assertAlmostEqual(expected_viewport_rect[1], vr[1]) self.assertAlmostEqual(expected_viewport_rect[2], vr[2]) self.assertAlmostEqual(expected_viewport_rect[3], vr[3]) subscription = draw_event_stream.create_subscription_to_pop(uiDrawCallback) await omni.kit.app.get_app().next_update_async()
2,646
Python
36.28169
142
0.608466
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/drag_drop_looks_material_viewport.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. ## import os import omni.kit.app import omni.kit.test import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class ZZViewportDragDropMaterialLooks(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() await omni.usd.get_context().new_stage_async() # After running each test async def tearDown(self): await wait_stage_loading() def choose_material(self, mdl_list, excluded_list): for _, mdl_path, _ in mdl_list: mdl_name = os.path.splitext(os.path.basename(mdl_path))[0] if mdl_name not in excluded_list: return mdl_path, mdl_name return None, None async def test_l1_drag_drop_single_material_viewport_looks(self): from carb.input import KeyboardInput await ui_test.find("Content").focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() # create default prim omni.kit.commands.execute("CreatePrim", prim_path="/World", prim_type="Xform", select_new_prim=False) stage.SetDefaultPrim(stage.GetPrimAtPath("/World")) # drag to center of viewport window # NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used viewport_window = ui_test.find("Viewport") await viewport_window.focus() drag_target = viewport_window.center # get paths mdl_list = await omni.kit.material.library.get_mdl_list_async() mdl_path1, mdl_name = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR"]) # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.drag_and_drop_tree_view(mdl_path1, drag_target=drag_target) # wait for material to load & UI to refresh await wait_stage_loading() # verify /World/Looks type after drag/drop prim = stage.GetPrimAtPath("/World/Looks") self.assertEqual(prim.GetTypeName(), "Scope")
2,792
Python
38.899999
126
0.698782
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/multi_descendents_dialog.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test import omni.usd import omni.ui as ui from omni.kit.test.async_unittest import AsyncTestCase from pxr import Sdf, UsdShade from omni.kit import ui_test from omni.kit.viewport.utility import get_ui_position_for_prim from omni.kit.material.library.test_helper import MaterialLibraryTestHelper from omni.kit.test_suite.helpers import ( arrange_windows, open_stage, get_test_data_path, wait_stage_loading, handle_multiple_descendents_dialog, Vec2 ) from omni.kit.material.library.test_helper import MaterialLibraryTestHelper from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper # has to be last or test_viewport_mouse_raycast fails. class ZZMultipleDescendentsDragDropTest(AsyncTestCase): # Before running each test async def setUp(self): manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.ui_test", True) manager.set_extension_enabled_immediate("omni.kit.window.status_bar", True) manager.set_extension_enabled_immediate("omni.kit.window.content_browser", True) # load stage await open_stage(get_test_data_path(__name__, "empty_stage.usda")) # After running each test async def tearDown(self): await wait_stage_loading() async def test_l1_drag_drop_material_viewport(self): viewport_window = await arrange_windows(topleft_width=0) ui_test_window = ui_test.find("Viewport") await ui_test_window.focus() # get single and multi-subid materials single_material = None multi_material = None mdl_list = await omni.kit.material.library.get_mdl_list_async() for mtl_name, mdl_path, submenu in mdl_list: if "Presets" in mdl_path or "Base" in mdl_path: continue if not single_material and not submenu: single_material = (mtl_name, mdl_path) if not multi_material and submenu: multi_material = (mtl_name, mdl_path) # verify both tests have run self.assertTrue(single_material != None) self.assertTrue(multi_material != None) async def verify_prims(stage, mtl_name, verify_prim_list): # verify material prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()] self.assertTrue(f"/World/Looks/{mtl_name}" in prim_paths) self.assertTrue(f"/World/Looks/{mtl_name}/Shader" in prim_paths) # verify bound material if verify_prim_list: for prim_path in verify_prim_list: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == f"/World/Looks/{mtl_name}") # undo omni.kit.undo.undo() # verify material was removed prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()] self.assertFalse(f"/World/Looks/{mtl_name}" in prim_paths) async def test_mtl(stage, material, verify_prim_list, drag_target): mtl_name, mdl_path = material # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # handle create material dialog async with MaterialLibraryTestHelper() as material_library_helper: await material_library_helper.handle_create_material_dialog(mdl_path, mtl_name) # wait for material to load & UI to refresh await wait_stage_loading() # verify created/bound prims await verify_prims(stage, mtl_name, verify_prim_list) async def test_multiple_descendents_mtl(stage, material, multiple_descendents_prim, target_prim, drag_target): mtl_name, mdl_path = material # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # use multiple descendents dialog await handle_multiple_descendents_dialog(stage, multiple_descendents_prim, target_prim) # handle create material dialog async with MaterialLibraryTestHelper() as material_library_helper: await material_library_helper.handle_create_material_dialog(mdl_path, mtl_name) # wait for material to load & UI to refresh await wait_stage_loading() # verify created/bound prims await verify_prims(stage, mtl_name, [target_prim]) # test DnD single & multi subid material from Content window to centre of viewport - Create material stage = omni.usd.get_context().get_stage() drag_target = ui_test_window.center await test_mtl(stage, single_material, [], drag_target) await test_mtl(stage, multi_material, [], drag_target) # load stage with multi-descendent prim await open_stage(get_test_data_path(__name__, "multi-material-object-cube-component.usda")) await wait_stage_loading() # test DnD single & multi subid material from Content window to /World/Sphere - Create material & Binding stage = omni.usd.get_context().get_stage() verify_prim_list = ["/World/Sphere"] drag_target, valid = get_ui_position_for_prim(viewport_window, verify_prim_list[0]) drag_target = Vec2(drag_target[0], drag_target[1]) await test_mtl(stage, single_material, verify_prim_list, drag_target) await test_mtl(stage, multi_material, verify_prim_list, drag_target) # test DnD single & multi subid material from Content window to /World/pCube1 targeting each descendent - Create material & Binding stage = omni.usd.get_context().get_stage() multiple_descendents_prim = "/World/pCube1" descendents = ["/World/pCube1", "/World/pCube1/front1", "/World/pCube1/side1", "/World/pCube1/back", "/World/pCube1/side2", "/World/pCube1/top1", "/World/pCube1/bottom"] drag_target, valid = get_ui_position_for_prim(viewport_window, multiple_descendents_prim) drag_target = Vec2(drag_target[0], drag_target[1]) for target_prim in descendents: await test_multiple_descendents_mtl(stage, single_material, multiple_descendents_prim, target_prim, drag_target) await test_multiple_descendents_mtl(stage, multi_material, multiple_descendents_prim, target_prim, drag_target)
7,382
Python
46.025477
177
0.670144
omniverse-code/kit/exts/omni.inspect/config/extension.toml
[package] version = "1.0.1" title = "Object Inspection Capabilities" description = "Provides interfaces you can add to your ABI to provide data inspection information in a compliant way" keywords = [ "debug", "inspect", "information" ] [[native.plugin]] path = "bin/*.plugin" recursive = false [[python.module]] name = "omni.inspect"
336
TOML
24.923075
117
0.723214
omniverse-code/kit/exts/omni.inspect/omni/inspect/_omni_inspect.pyi
from __future__ import annotations import omni.inspect._omni_inspect import typing import omni.core._core __all__ = [ "IInspectJsonSerializer", "IInspectMemoryUse", "IInspectSerializer", "IInspector" ] class IInspectJsonSerializer(_IInspectJsonSerializer, IInspector, _IInspector, omni.core._core.IObject): """ Base class for object inspection requests. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def as_string(self) -> str: """ Get the current output as a string. If the output is being sent to a file path then read the file at that path and return the contents of the file (with the usual caveats about file size). @returns String representation of the output so far """ def clear(self) -> None: """ Clear the contents of the serializer output, either emptying the file or clearing the string, depending on where the current output is directed. """ def close_array(self) -> bool: """ Finish writing a JSON array. @returns whether or not validation succeeded. """ def close_object(self) -> bool: """ Finish writing a JSON object. @returns whether or not validation succeeded. """ def finish(self) -> bool: """ Finishes writing the entire JSON dictionary. @returns whether or not validation succeeded. """ def open_array(self) -> bool: """ Begin a JSON array. @returns whether or not validation succeeded. @note This may throw a std::bad_alloc or a std::length_error if the stack of scopes gets too large """ def open_object(self) -> bool: """ Begin a JSON object. @returns whether or not validation succeeded. """ def set_output_to_string(self) -> None: """ Set the output location of the serializer data to be a local string. No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. """ def write_base64_encoded(self, value: bytes, size: int) -> bool: """ Write a set of bytes into the output JSON as a base64 encoded string. @param[in] value The bytes to be written. @param[in] size The number of bytes of data in @p value. @returns whether or not validation succeeded. @remarks This will take the input bytes and encode it in base64, then store that as base64 data in a string. """ def write_bool(self, value: bool) -> bool: """ Write out a JSON boolean value. @param[in] value The boolean value. @returns whether or not validation succeeded. """ def write_double(self, value: float) -> bool: """ Write out a JSON double (aka number) value. @param[in] value The double value. @returns whether or not validation succeeded. """ def write_float(self, value: float) -> bool: """ Write out a JSON float (aka number) value. @param[in] value The double value. @returns whether or not validation succeeded. """ def write_int(self, value: int) -> bool: """ Write out a JSON integer value. @param[in] value The integer value. @returns whether or not validation succeeded. """ def write_int64(self, value: int) -> bool: """ Write out a JSON 64-bit integer value. @param[in] value The 64-bit integer value. @returns whether or not validation succeeded. @note 64 bit integers will be written as a string of they are too long to be stored as a number that's interoperable with javascript's double precision floating point format. """ def write_key(self, key: str) -> bool: """ Write out a JSON key for an object property. @param[in] key The key name for this property. This may be nullptr. @returns whether or not validation succeeded. """ def write_key_with_length(self, key: str, key_len: int) -> bool: """ Write out a JSON key for an object property. @param[in] key The string value for the key. This can be nullptr. @param[in] keyLen The length of @ref key, excluding the null terminator. @returns whether or not validation succeeded. """ def write_null(self) -> bool: """ Write out a JSON null value. @returns whether or not validation succeeded. """ def write_string(self, value: str) -> bool: """ Write out a JSON string value. @param[in] value The string value. This can be nullptr. @returns whether or not validation succeeded. """ def write_string_with_length(self, value: str, len: int) -> bool: """ Write out a JSON string value. @param[in] value The string value. This can be nullptr if @p len is 0. @param[in] len The length of @p value, excluding the null terminator. @returns whether or not validation succeeded. """ def write_u_int(self, value: int) -> bool: """ Write out a JSON unsigned integer value. @param[in] value The unsigned integer value. @returns whether or not validation succeeded. """ def write_u_int64(self, value: int) -> bool: """ Write out a JSON 64-bit unsigned integer value. @param[in] value The 64-bit unsigned integer value. @returns whether or not validation succeeded. @note 64 bit integers will be written as a string of they are too long to be stored as a number that's interoperable with javascript's double precision floating point format. """ @property def output_location(self) -> str: """ :type: str """ @property def output_to_file_path(self) -> None: """ :type: None """ @output_to_file_path.setter def output_to_file_path(self, arg1: str) -> None: pass pass class IInspectMemoryUse(_IInspectMemoryUse, IInspector, _IInspector, omni.core._core.IObject): """ Base class for object inspection requests. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def reset(self) -> None: """ Reset the memory usage data to a zero state """ def total_used(self) -> int: """ @returns the total number of bytes of memory used since creation or the last call to reset(). """ def use_memory(self, ptr: capsule, bytes_used: int) -> bool: """ Add a block of used memory Returns false if the memory was not recorded (e.g. because it was already recorded) @param[in] ptr Pointer to the memory location being logged as in-use @param[in] bytesUsed Number of bytes in use at that location """ pass class IInspectSerializer(_IInspectSerializer, IInspector, _IInspector, omni.core._core.IObject): """ Base class for object serialization requests. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def as_string(self) -> str: """ Get the current output as a string. @returns The output that has been sent to the serializer. If the output is being sent to a file path then read the file at that path and return the contents of the file. If the output is being sent to stdout or stderr then nothing is returned as that output is unavailable after flushing. """ def clear(self) -> None: """ Clear the contents of the serializer output, either emptying the file or clearing the string, depending on where the current output is directed. """ def set_output_to_string(self) -> None: """ Set the output location of the serializer data to be a local string. No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. """ def write_string(self, to_write: str) -> None: """ Write a fixed string to the serializer output location @param[in] toWrite String to be written to the serializer """ @property def output_location(self) -> str: """ :type: str """ @property def output_to_file_path(self) -> None: """ :type: None """ @output_to_file_path.setter def output_to_file_path(self, arg1: str) -> None: pass pass class _IInspectJsonSerializer(IInspector, _IInspector, omni.core._core.IObject): pass class _IInspectMemoryUse(IInspector, _IInspector, omni.core._core.IObject): pass class _IInspectSerializer(IInspector, _IInspector, omni.core._core.IObject): pass class IInspector(_IInspector, omni.core._core.IObject): """ Base class for object inspection requests. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def help_flag(self) -> str: """ Returns the common flag used to tell the inspection process to put the help information into the inspector using the setHelp_abi function. Using this approach avoids having every inspector/object combination add an extra ABI function just for retrieving the help information, as well as providing a consistent method for requesting it. @returns String containing the name of the common flag used for help information """ def help_information(self) -> str: """ Returns the help information currently available on the inspector. Note that this could change from one invocation to the next so it's important to read it immediately after requesting it. @returns String containing the help information describing the current configuration of the inspector """ def is_flag_set(self, flag_name: str) -> bool: """ Checks whether a particular flag is currently set or not. @param[in] flagName Name of the flag to check @returns True if the named flag is set, false if not """ def set_flag(self, flag_name: str, flag_state: bool) -> None: """ Enable or disable an inspection flag. It's up to the individual inspection operations or the derived inspector interfaces to interpret the flag. @param[in] flagName Name of the flag to set @param[in] flagState New state for the flag """ @property def help(self) -> None: """ :type: None """ @help.setter def help(self, arg1: str) -> None: pass pass class _IInspector(omni.core._core.IObject): pass
11,159
unknown
35.351791
118
0.616005
omniverse-code/kit/exts/omni.inspect/omni/inspect/__init__.py
""" Contains interfaces for inspecting values used within other interfaces """ # Required to be able to instantiate the object types import omni.core # Interface from the ABI bindings from ._omni_inspect import IInspectJsonSerializer from ._omni_inspect import IInspectMemoryUse from ._omni_inspect import IInspectSerializer from ._omni_inspect import IInspector
364
Python
29.416664
70
0.815934
omniverse-code/kit/exts/omni.inspect/omni/inspect/tests/test_bindings.py
"""Suite of tests to exercise the bindings exposed by omni.inspect""" import omni.kit.test import omni.inspect as oi from pathlib import Path import tempfile # ============================================================================================================== class TestOmniInspectBindings(omni.kit.test.AsyncTestCase): """Wrapper for tests to verify functionality in the omni.inspect bindings module""" # ---------------------------------------------------------------------- def __test_inspector_api(self, inspector: oi.IInspector): """Run tests on flags common to all inspector types API surface being tested: omni.inspect.IInspector @help, help_flag, help_information, is_flag_set, set_flag """ HELP_FLAG = "help" HELP_INFO = "This is some help" self.assertEqual(inspector.help_flag(), HELP_FLAG) self.assertFalse(inspector.is_flag_set(HELP_FLAG)) inspector.help = HELP_INFO self.assertEqual(inspector.help_information(), HELP_INFO) inspector.set_flag("help", True) self.assertTrue(inspector.is_flag_set(HELP_FLAG)) inspector.set_flag("help", False) inspector.set_flag("Canadian", True) self.assertFalse(inspector.is_flag_set(HELP_FLAG)) self.assertTrue(inspector.is_flag_set("Canadian")) # ---------------------------------------------------------------------- async def test_memory_inspector(self): """Test features only available to the memory usage inspector API surface being tested: omni.inspect.IInspectMemoryUse [omni.inspect.IInspector] reset, total_used, use_memory """ inspector = oi.IInspectMemoryUse() self.__test_inspector_api(inspector) self.assertEqual(inspector.total_used(), 0) self.assertTrue(inspector.use_memory(inspector, 111)) self.assertTrue(inspector.use_memory(inspector, 222)) self.assertTrue(inspector.use_memory(inspector, 333)) self.assertEqual(inspector.total_used(), 666) inspector.reset() self.assertEqual(inspector.total_used(), 0) # ---------------------------------------------------------------------- async def test_serializer(self): """Test features only available to the shared serializer types API surface being tested: omni.inspect.IInspectSerializer [omni.inspect.IInspector] as_string, clear, output_location, output_to_file_path, set_output_to_string, write_string """ inspector = oi.IInspectSerializer() self.__test_inspector_api(inspector) self.assertEqual(inspector.as_string(), "") TEST_STRINGS = [ "This is line 1", "This is line 2", ] # Test string output inspector.write_string(TEST_STRINGS[0]) self.assertEqual(inspector.as_string(), TEST_STRINGS[0]) inspector.write_string(TEST_STRINGS[1]) self.assertEqual(inspector.as_string(), "".join(TEST_STRINGS)) inspector.clear() self.assertEqual(inspector.as_string(), "") # Test file output with tempfile.TemporaryDirectory() as tmp: test_output_file = Path(tmp) / "test_serializer.txt" # Get the temp file path and test writing a line to it inspector.output_to_file_path = str(test_output_file) inspector.write_string(TEST_STRINGS[0]) self.assertEqual(inspector.as_string(), TEST_STRINGS[0]) # Set output back to string and check the temp file contents manually inspector.set_output_to_string() file_contents = open(test_output_file, "r").readlines() self.assertEqual(file_contents, [TEST_STRINGS[0]]) # ---------------------------------------------------------------------- async def test_json_serializer(self): """Test features only available to the JSON serializer type API surface being tested: omni.inspect.IInspectJsonSerializer [omni.inspect.IInspector] as_string, clear, close_array, close_object, finish, open_array, open_object, output_location, output_to_file_path, set_output_to_string, write_base64_encoded, write_bool, write_double, write_float, write_int, write_int64, write_key, write_key_with_length, write_null, write_string, write_string_with_length, write_u_int, write_u_int64 """ inspector = oi.IInspectJsonSerializer() self.__test_inspector_api(inspector) self.assertEqual(inspector.as_string(), "") self.assertTrue(inspector.open_array()) self.assertTrue(inspector.close_array()) self.assertEqual(inspector.as_string(), "[\n]") inspector.clear() self.assertEqual(inspector.as_string(), "") # Note: There's what looks like a bug in the StructuredLog JSON output that omits the space before # a base64_encoded value. If that's ever fixed the first entry in the dictionary will have to change. every_type = """ { "base64_key":"MTI=", "bool_key": true, "double_key": 123.456, "float_key": 125.25, "int_key": -123, "int64_key": -123456789, "null_key": null, "string_key": "Hello", "string_with_length_key": "Hell", "u_int_key": 123, "u_int64_key": 123456789, "array": [ 1, 2, 3 ] } """ def __inspect_every_type(): """Helper to write one of every type to the inspector""" self.assertTrue(inspector.open_object()) self.assertTrue(inspector.write_key("base64_key")) self.assertTrue(inspector.write_base64_encoded(b'1234', 2)) self.assertTrue(inspector.write_key("bool_key")) self.assertTrue(inspector.write_bool(True)) self.assertTrue(inspector.write_key("double_key")) self.assertTrue(inspector.write_double(123.456)) self.assertTrue(inspector.write_key("float_key")) self.assertTrue(inspector.write_float(125.25)) self.assertTrue(inspector.write_key_with_length("int_key_is_truncated", 7)) self.assertTrue(inspector.write_int(-123)) self.assertTrue(inspector.write_key("int64_key")) self.assertTrue(inspector.write_int64(-123456789)) self.assertTrue(inspector.write_key("null_key")) self.assertTrue(inspector.write_null()) self.assertTrue(inspector.write_key("string_key")) self.assertTrue(inspector.write_string("Hello")) self.assertTrue(inspector.write_key("string_with_length_key")) self.assertTrue(inspector.write_string_with_length("Hello World", 4)) self.assertTrue(inspector.write_key("u_int_key")) self.assertTrue(inspector.write_u_int(123)) self.assertTrue(inspector.write_key("u_int64_key")) self.assertTrue(inspector.write_u_int64(123456789)) self.assertTrue(inspector.write_key("array")) self.assertTrue(inspector.open_array()) self.assertTrue(inspector.write_int(1)) self.assertTrue(inspector.write_int(2)) self.assertTrue(inspector.write_int(3)) self.assertTrue(inspector.close_array()) self.assertTrue(inspector.close_object()) self.assertTrue(inspector.finish()) __inspect_every_type() self.assertEqual(inspector.as_string(), every_type) # Test file output with tempfile.TemporaryDirectory() as tmp: test_output_file = Path(tmp) / "test_serializer.txt" # Get the temp file path and test writing a line to it inspector.output_to_file_path = str(test_output_file) __inspect_every_type() self.assertEqual(inspector.as_string(), every_type) # Set output back to string and check the temp file contents manually inspector.set_output_to_string() file_contents = [line.rstrip() for line in open(test_output_file, "r").readlines()] self.assertCountEqual(file_contents, every_type.split("\n")[:-1])
8,329
Python
39.833333
115
0.593829
omniverse-code/kit/exts/omni.inspect/omni/inspect/tests/__init__.py
""" Scan the test directory for unit tests """ scan_for_test_modules = True
76
Python
14.399997
38
0.710526
omniverse-code/kit/exts/omni.inspect/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.0.1] - 2022-06-28 ### Added - Linked docs in the build area ## [1.0.0] - 2022-04-07 ### Added - Unit test for all of the functionality ### Changed - Updated to a real version for future compatibility - Made some bug fixes revealed by the unit test ## [0.1.0] - 2021-05-12 ### Initial Version - First implementation including basic features
618
Markdown
24.791666
87
0.71521
omniverse-code/kit/exts/omni.inspect/docs/README.md
# Omniverse Data Inspector [omni.inspect] The data inspector module contains interfaces that provide a consistent method of inspecting data from extensions in an ABI-friendly manner.
184
Markdown
35.999993
102
0.826087
omniverse-code/kit/exts/omni.inspect/docs/index.rst
.. _omni_inspect_ext: omni.inspect: Omniverse Data Inspector ####################################### The interfaces in this extension don't do anything themselves, they merely provide a conduit through which other objects can provide various information through a simple ABI without each object being required to provide the same inspection interface boilerplate. The general approach is that you create an inspector, then pass it to an object to be inspected. This model provides full access to the internal data to the inspector and makes it easy for objects to add inspection capabilities. Inspecting Data =============== To add inspection to your data you need two things - an interface to pass the inspector, and an implementation of the inspection, or inspections. We'll take two imaginary interface types, one of which uses the old Carbonite interface definitions and one which uses ONI. The interfaces just manage an integer and float value, though the concept extends to arbitrariliy complex structures. Carbonite ABI Integer --------------------- .. code-block:: c++ // Interface definition -------------------------------------------------- // Implementation for the integer is just a handle, which is an int*, and the interface pointer using IntegerHandle = uint64_t; struct IInteger; struct IntegerObj { const IInteger* iInteger; IntegerHandle integerHandle; }; struct IInteger { CARB_PLUGIN_INTERFACE("omni::inspect::IInteger", 1, 0); void(CARB_ABI* set)(IntegerObj& intObj, int value) = nullptr; bool(CARB_ABI* inspect)(const IntegerObj& intObj, inspect::IInspector* inspector) = nullptr; }; // Interface implementation -------------------------------------------------- void intSet(IntegerObj& intObj, int value) { intObj.iInteger->set(intObj, value); } bool intInspect(const IntegerObj& intObj, inspect::IInspector* inspector) { // This object can handle both a memory use inspector and a serialization inspector auto memoryInspector = omni::cast<inspect::IInspectMemoryUse>(inspector); if (memoryInspector) { // The memory used by this type is just a single integer, and the object itself memoryInspector->useMemory((void*)&intObj, sizeof(intObj)); memoryInspector->useMemory((void*)intObj.integerHandle, sizeof(int)); return true; } auto jsonSerializer = omni::cast<inspect::IInspectJsonSerializer>(inspector); if (jsonSerializer) { // Valid JSON requires more than just a bare integer. // Indenting on the return value gives you a visual representation of the JSON hierarchy if (jsonSerializer->openObject()) { jsonSerializer->writeKey("Integer Value"); jsonSerializer->writeInt(*(int*)(intObj.integerHandle)); jsonSerializer->closeObject(); } return true; } auto serializer = omni::cast<inspect::IInspectSerializer>(inspector); if (serializer) { // The interesting data to write is the integer value, though you could also write the pointer if desired serializer->write("Integer value %d", *(int*)(intObj.integerHandle)); return true; } // Returning false indicates an unsupported inspector return false; } // Interface use -------------------------------------------------- IInteger iFace{ intInspect, intSet }; int myInt{ 0 }; IntegerObj iObj{ &iFace, (uint64_t)&myInt }; ONI Float --------- .. code-block:: c++ // Interface definition -------------------------------------------------- OMNI_DECLARE_INTERFACE(IFloat); class IFloat_abi : public omni::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.inspect.IFloat")> { protected: virtual void set_abi(float newValue) noexcept = 0; virtual void inspect_abi(omni::inspect::IInspector* inspector) noexcept = 0; }; // Interface implementation -------------------------------------------------- class IFloat : public omni::Implements<IIFloat> { protected: void set_abi(float newvalue) noexcept override { m_value = value; } bool inspect(omni::inspect::IInspector* inspector) noexcept override { // This object can handle both a memory use inspector and a serialization inspector auto memoryInspector = omni::cast<inspect::IInspectMemoryUse>(inspector); if (memoryInspector) { // The memory used by this type is just the size of this object memoryInspector->useMemory((void*)this, sizeof(*this)); return true; } auto jsonSerializer = omni::cast<inspect::IInspectJsonSerializer>(inspector); if (jsonSerializer) { // Valid JSON requires more than just a bare float. // Indenting on the return value gives you a visual representation of the JSON hierarchy if (jsonSerializer->openObject()) { jsonSerializer->writeKey("Float Value"); jsonSerializer->writeFloat(m_value); jsonSerializer->closeObject(); } return true; } auto serializer = omni::cast<inspect::IInspectSerializer>(inspector); if (serializer) { // The interesting data to write is the float value, though you could also write "this" if desired serializer->write("float value %g", m_value); return true; } // Returning false indicates an unsupported inspector return false; } private: float m_value{ 0.0f }; }; Calling Inspectors From Python ------------------------------ The inspectors, being ONI objects, have Python bindings so they can be instantiated directly and passed to any of the interfaces that support them. .. code-block:: python import omni.inspect as oi memory_inspector = oi.IInspectMemoryUse() my_random_object.inspect(memory_inspector) print(f"Memory use is {memory_inspector.get_memory_use()} bytes") json_serializer = oi.IInspectJsonSerializer() my_random_object.inspect(json_serializer) print(f"JSON object:\n{json_serializer.as_string()}" ) serializer = oi.IInspectSerializer() my_random_object.inspect(serializer) print(f"Serialized object:\n{serializer.as_string()}" ) omni.inspect Python Docs ======================== .. automodule:: omni.inspect :platform: Windows-x86_64, Linux-x86_64, Linux-aarch64 :members: :undoc-members: :imported-members: Administrative Details ====================== .. toctree:: :maxdepth: 1 :caption: Administrivia :glob: CHANGELOG
7,043
reStructuredText
34.938775
117
0.606986
omniverse-code/kit/exts/omni.kit.widget.imageview/config/extension.toml
[package] version = "1.0.3" category = "Internal" title = "ImageView Widget" description="The widget that allows to view image in a canvas." changelog = "docs/CHANGELOG.md" [dependencies] "omni.ui" = {} [[python.module]] name = "omni.kit.widget.imageview" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", ]
461
TOML
17.479999
63
0.661605
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/__init__.py
from .imageview import ImageView
33
Python
15.999992
32
0.848485
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/imageview.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. # import omni.ui as ui class ImageView: """The widget that shows the image with the ability to navigate""" def __init__(self, filename, **kwargs): with ui.CanvasFrame(style_type_name_override="ImageView", **kwargs): self.__image = ui.Image(filename) def set_progress_changed_fn(self, fn): """Callback that is called when control state is changed""" self.__image.set_progress_changed_fn(fn) def destroy(self): if self.__image: self.__image.destroy() self.__image = None
985
Python
35.518517
76
0.701523
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/tests/imageview_test.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from ..imageview import ImageView from omni.ui.tests.test_base import OmniUiTest from functools import partial from pathlib import Path import omni.kit.app import asyncio class TestImageview(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute() # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): window = await self.create_test_window() f = asyncio.Future() def on_image_progress(future: asyncio.Future, progress): if progress >= 1: if not future.done(): future.set_result(None) with window.frame: image_view = ImageView(f"{self._golden_img_dir.joinpath('lenna.png')}") image_view.set_progress_changed_fn(partial(on_image_progress, f)) # Wait the image to be loaded await f await self.finalize_test(golden_img_dir=self._golden_img_dir)
1,697
Python
35.127659
110
0.683559
omniverse-code/kit/exts/omni.kit.widget.imageview/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.3] - 2022-11-10 ### Removed - Removed dependency on omni.kit.test ## [1.0.2] - 2022-05-04 ### Updated - Add set_progress_changed_fn API for caller to check if the image has been loaded. ## [1.0.1] - 2020-09-16 ### Updated - Fixed the unittest. ## [1.0.0] - 2020-07-19 ### Added - Added The widget that allows to view image in a canvas.
442
Markdown
21.149999
83
0.662896
omniverse-code/kit/exts/omni.graph.core/config/extension.toml
[package] title = "OmniGraph" version = "2.65.4" category = "Graph" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" description = "Contains the implementation of the OmniGraph core." preview_image = "data/preview.png" repository = "" keywords = ["omnigraph", "core"] # Other extensions on which this one relies [dependencies] "omni.usd" = {} "omni.client" = {} "omni.inspect" = {optional=true} "omni.gpucompute.plugins" = {} [[native.plugin]] path = "bin/*.plugin" recursive = false # Regression tests are not here because that would require Python. See the unit test tree for core-specific tests. [[test]] waiver = "Tests are in omni.graph.test" stdoutFailPatterns.exclude = [] [documentation] deps = [ ["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph refs until that workflow is moved ] pages = [ "docs/Overview.md", "docs/nodes.rst", "docs/architecture.rst", "docs/core_concepts.rst", "docs/usd.rst", "docs/naming_conventions.rst", "docs/directory_structure.rst", "docs/how_to.rst", "docs/versioning.rst", "docs/roadmap.rst", "docs/CHANGELOG.md", "docs/omnigraph_arch_decisions.rst", "docs/categories.rst", "docs/usd_representations.rst", # "docs/index.rst", # "docs/decisions/0000-use-markdown-any-decision-records.rst", # "docs/decisions/0001-python-api-definition.rst", # "docs/decisions/0002-python-api-exposure.rst", # "docs/decisions/0003-extension-locations.rst", # "docs/decisions/adr-template.rst", # "docs/internal/SchemaPrimSetting.rst", # "docs/internal/internal.rst", # "docs/internal/deprecation.rst", # "docs/internal/versioning.rst", # "docs/internal/versioning_behavior.rst", # "docs/internal/versioning_carbonite.rst", # "docs/internal/versioning_extensions.rst", # "docs/internal/versioning_nodes.rst", # "docs/internal/versioning_oni.rst", # "docs/internal/versioning_python.rst", # "docs/internal/versioning_settings.rst", # "docs/internal/versioning_testing.rst", # "docs/internal/versioning_usd.rst", ]
2,102
TOML
29.92647
114
0.683635
omniverse-code/kit/exts/omni.graph.core/omni/graph/core/ogn/nodes/core/OgnPrim.cpp
// Copyright (c) 2019-2021, 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. // #include "OgnPrimDatabase.h" #include "GraphContext.h" namespace omni { namespace graph { namespace core { namespace DataModel { //backdoor :( void backdoor_copyAttribute(ComputeCacheType& cache, AttrKey dst, AttrKey src); } HandleInt nodeCtxHandleToPath(NodeContextHandle const& handle); class OgnPrim { public: // copy computed data back to usd prim // This node is used as a placeholder representing a USD prim, which might have connection(s) to upstream node(s). // This data needs to be copied over, so it can be written back to USD // This is a legacy way of doing things. We are using a private backdoor in datamodel to achieve this legacy behavior static bool compute(OgnPrimDatabase& db) { auto& contextObj = db.abi_context(); GraphContext& contextImpl = *GraphContext::getGraphContextFromHandle(contextObj.contextHandle); ComputeCacheType& cache = contextImpl.getCache(); auto node = db.abi_node(); ConstAttributeDataHandle const invalidHandle(ConstAttributeDataHandle::invalidValue()); // find all connected attribute on that node size_t countAttr = node.iNode->getAttributeCount(node); AttributeObj* attrObjIn = (AttributeObj*)alloca(countAttr * sizeof(AttributeObj)); AttributeObj* end = attrObjIn + countAttr; node.iNode->getAttributes(node, attrObjIn, countAttr); auto getHdl = [&contextObj](AttributeObj const& a) { return contextObj.iToken->getHandle(a.iAttribute->getName(a)); }; AttrKey dst{ nodeCtxHandleToPath(node.nodeContextHandle), 0 }; for (size_t i = 0; i < countAttr; ++i) { AttrKey src = (AttrKey) attrObjIn[i].iAttribute->getConstAttributeDataHandle(attrObjIn[i]); dst.second = getHdl(attrObjIn[i]).token; if (dst != src) DataModel::backdoor_copyAttribute(cache, dst, src); } return true; } }; REGISTER_OGN_NODE() } // namespace core } // namespace graph } // namespace omni
2,485
C++
34.514285
123
0.699799
omniverse-code/kit/exts/omni.graph.core/docs/roadmap.rst
Roadmap ******* Pending Deprecations ==================== As described in :ref:`omnigraph_versioning` we attempt to provide backward compatibility for as long as we can. That notwithstanding it will always be a smoother experience for you if you migrate away from using deprecated functionality at your earliest convenience to ensure maximum compatibility. If anything is scheduled for "hard deprecation" Known Functionality Gaps ======================== As OmniGraph is still in early stages there are some known unimplemented edge cases to be aware of. Addressing these will be prioritized as resources and interests dictate. - The Node Description Editor does not support addition of tests or generation of C++ nodes - Bundle arrays are not supported - Arrays of strings are not supported - Bundles cannot contain "any" or "union" type attributes - "any" or "union" type attributes cannot be bundles - Loading a USD file with OmniGraph nodes in it will not automatically load the extensions required for those nodes to function properly
1,045
reStructuredText
44.478259
136
0.770335
omniverse-code/kit/exts/omni.graph.core/docs/nodes.rst
OmniGraph Nodes *************** The OmniGraph node provides an encapsulated piece of functionality that is used in a connected graph structure to form larger more complex calculations. One of the core strengths of the way the nodes are defined is that individual node writers do not have to deal with the complexity of the entire system, while still reaping the benefits of it. Support code is generated for the node type definitions that simplify the code necessary for implementing the algorithm, while also providing support for efficient manipulation of data through the use of Fabric both on the CPU and on the GPU. The user writes the description and code that define the operation of the node type and OmniGraph provides the interfaces that incorporate it into the Omniverse runtime. Node Type Implementations ========================= The node type definition implements the functionality that will be used by the node using two key pieces 1. The *authoring* definition, which comes in the form of a JSON format file with the suffix *.ogn* 2. The *runtime* algorithm, which can be implemented in one of several languages. The actual language of implementation is not important to OmniGraph and can be chosen based on the needs and abilities of the node writer. You can learn about the authoring description in the .ogn files by perusing the :ref:`OGN Node Writer Guide<ogn_user_guide>`, with full details in the :ref:`OGN Reference Guide<ogn_reference_guide>`, or you can follow along with some of the tutorials or node definitions seen below. A common component of all node type implementations is the presence of a generated structure known as the node type database. The database provides a simplified wrapper around the underlying OmniGraph functionality that hides all of the required boilerplate code that makes the nodes operate so efficiently. Python Implementation --------------------- The easiest type of node to write is a Python node. You only need implement a class with a static *compute(db)* method whose parameter is the generated database. The database provides access to the input values your node will use for its computation and the output values you generate as a result of that computation. +-------------------------------------------+ | :ref:`Example Below<ogn_example_node_py>` | +-------------------------------------------+ C++ Implementation ------------------ While the Python nodes are easier to write they are not particularly efficient, and for some types of nodes performance is critical. These node types can be implemented in C++. There is slightly more code to write, but you gain the performance benefits of compiled code. +--------------------------------------------+ | :ref:`Example Below<ogn_example_node_cpp>` | +--------------------------------------------+ C++/CUDA Implementation ----------------------- Sometimes you want to harness the power of the GPU to do some really complex or data-heavy computations. If you know how to program in CUDA, NVIDIA's general purpose GPU computing language, then you can insert CUDA code into your node's `compute()` method to move the computation over to the GPU. +-------------------------------------------+ | :ref:`Example Below<ogn_example_node_cu>` | +-------------------------------------------+ Warp Implementation ------------------- If you don't know how to write CUDA code but are familiar with Python then you can use the Warp package to accelerate your computations on the GPU as well. NVIDIA Warp is a Python framework for writing high-performance simulation and graphics code in Omniverse, and in particular OmniGraph. See the `Warp extension documentation <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_warp.html>`_ for details on how to write the implementation code for Warp nodes. +---------------------------------------------+ | :ref:`Example Below<ogn_example_node_warp>` | +---------------------------------------------+ Slang Implementation -------------------- `Slang <https://shader-slang.com/slang/user-guide/index.html>`_ is a language developed for efficient implementation of shaders, based on years of collaboration between researchers at NVIDIA, Carnegie Mellon University, and Stanford. To bring the benefits of Slang into Omnigraph an extension was written that allows you to create OmniGraph node implementations in the Slang language. To gain access to it you must enable the *omni.slangnode* extension, either through the extension window or via the `extension manager API <https://docs.omniverse.nvidia.com/py/kit/docs/api/core/omni.ext.html#omni.ext.ExtensionManager>`_ The Slang node type is slightly different from the others in that you do not define the authoring definition through a *.ogn* file. There is a single *.ogn* file shared by all Slang node types and you write the implementation of the node type's algorithm in the *inputs:code* attribute of an instantiation of that node type. You dynamically add attributes to the node to define the authoring interface and then you can access the attribute data using some generated Slang conventions. Moreover, the Slang language has the capability of targeting either CPU or GPU when compiled, so once the graph supports it the node will be able to run on either CPU or GPU, depending on which is more efficient on the available resources. See the `Slang extension documentation <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph/slang-nodes/nodes/slang.html>`_ for details on how to write Slang nodes. +----------------------------------------------+ | :ref:`Example Below<ogn_example_node_slang>` | +----------------------------------------------+ AutoNode Implementation ----------------------- AutoNode is a variation of the Python implementation that makes use of the Python AST to combine both the authoring description and the runtime implementation into a single Python class or function. While not yet fully functional, it provides a rapid method of implementing simple node types with minimal overhead. +---------------------------------------------+ | :ref:`Example Below<ogn_example_node_auto>` | +---------------------------------------------+ Sample Node With Different Implementations ========================================== To illustrate the difference in implementations a simple node type definition will be shown that takes in two arrays of points and outputs a weighted blend of them. .. note:: The implementations are not necessarily the most efficient, nor the most appropriate for the type of computation being performed. They are merely meant to be illustrative of the implementation options. This *.ogn* file will be used by all but the Slang and AutoNode implementations. The first highlighted line is only present in the Python and Warp implementations, as they are both Python-based. The remaining highlighted lines are used only for Warp and CUDA implementations, being used to indicate that the memory for the attributes should be retrieved from the GPU rather than the CPU. .. code-block:: json :emphasize-lines: 4,8,9,15 { "AddWeightedPoints": { "version": 1, "language": "python", "description": [ "Add two sets of points together, using an alpha value to determine how much of each point set to", "include in the result. The weighting is alpha*firstSet + (1 - alpha)*secondSet.", "memoryType": "cuda", "cudaPointers": "cpu" ], "inputs": { "alpha": { "type": "double", "description": "Relative weights to give to each of the two point sets" "memoryType": "cpu" }, "firstSet": { "type": "pointd[3][]", "description": "First set of points to blend together" }, "secondSet": { "type": "pointd[3][]", "description": "Second set of points to blend together" }, "outputs": { "result": { "type": "pointd[3][]", "description": "Weighted sum of the two sets of input points" } } } } .. _ogn_example_node_py: Python Version -------------- .. code-block:: python class OgnAddWeightedPoints: @staticmethod def compute(db) -> bool: db.outputs.result_size = len(db.inputs.firstSet) db.outputs.result = db.inputs.firstSet * db.inputs.alpha + db.inputs.secondSet * (1.0 - db.inputs.alpha) return True For illustration purposes here is the same code but with proper handling of unexpected input values, which is a good practice no matter what the implementation language. .. code-block:: python class OgnAddWeightedPoints: @staticmethod def compute(db) -> bool: first_set = db.inputs.firstSet second_set = db.inputs.secondSet if len(first_set) != len(second_set): db.log_error(f"Cannot blend two unequally sized point sets - {len(first_set)} and {len(second_set)}") return False if not (0.0 <= db.inputs.alpha <= 1.0): db.log_error(f"Alpha blend must be in the range [0.0, 1.0], not computing with {db.inputs.alpha}) return False db.outputs.result_size = len(first_set) db.outputs.result = first_set * db.inputs.alpha + second_set * (1.0 - db.inputs.alpha) return True To see further examples of the Python implementation code you can peruse the :ref:`samples used by the user guide<ogn_code_samples_py>` or the :ref:`user guide itself<ogn_user_guide>` itself. .. _ogn_example_node_cpp: C++ Version ----------- .. code-block:: cpp #include <OgnAddWeightedPointsDatabase.h> #include <algorithm> class OgnAddWeightedPoints { public: static bool compute(OgnAddWeightedPointsDatabase& db) { auto const& firstSet = db.inputs.firstSet(); auto const& secondSet = db.inputs.secondSet(); auto const& alpha = db.inputs.alpha(); const& result = db.outputs.result(); // Output arrays always have their size set before use, for efficiency result.resize(firstSet.size()); std::transform(firstSet.begin(), firstSet.end(), secondSet.begin(), result.begin(), [alpha](GfVec3d const& firstValue, GfVec3d const& secondValue) -> GfVec3d { return firstValue * alpha + (1.0 - alpha) * secondValue; }); return true; } }; REGISTER_OGN_NODE() To see further examples of the C++ implementation code you can peruse the :ref:`samples used by the user guide<ogn_code_samples_py>` or the :ref:`user guide itself<ogn_user_guide>` itself. .. _ogn_example_node_cu: C++/Cuda Version ---------------- Nodes using CUDA are split into two parts - the `.cpp` implementation that sets up the CUDA execution, and the `.cu` file containing the actual GPU functions. .. code-block:: cpp #include <OgnAddWeightedPointsDatabase.h> // The generated code gives helper types matching the attribute names to make passing data more intuitive. // This declares the CUDA function that applies the blend. extern "C" void applyBlendGPU(inputs::points_t firstSet, inputs::points_t secondSet, inputs::alpha_t alpha, outputs::points_t outputPoints, size_t numberOfPoints); class OgnAddWeightedPoints { public: static bool compute(OgnAddWeightedPointsDatabase& db) { // Output arrays always have their size set before use, for efficiency size_t numberOfPoints = db.inputs.firstSet.size(); db.outputs.result.resize(numberOfPoints); if (numberOfPoints > 0) { auto const& alpha = db.inputs.alpha(); applyBlendGPU(db.inputs.firstSet(), db.inputs.secondSet(), alpha, db.outputs.result(), numberOfPoints); } return true; } }; REGISTER_OGN_NODE() The corresponding `.cu` implementation is: .. code-block:: cpp // Although it contains unsafe CUDA constructs the generated code has guards to let this inclusion work here too #include <OgnTutorialCudaDataDatabase.h> // CUDA compute implementation code will usually have two methods; // fooGPU() - Host function to act as an intermediary between CPU and GPU code // fooCUDA() - CUDA implementation of the actual node algorithm. __global__ void applyBlendCUDA( inputs::points_t firstSet, inputs::points_t secondSet, inputs::alpha_t alpha, outputs::points_t result, size_t numberOfPoints ) { int ptIdx = blockIdx.x * blockDim.x + threadIdx.x; if (numberOfPoints <= ptIdx) return; (*result)[ptIdx].x = (*firstSet)[ptIdx].x * alpha + (*secondSet)[ptIdx].x * (1.0 - alpha); (*result)[ptIdx].y = (*firstSet)[ptIdx].y * alpha + (*secondSet)[ptIdx].y * (1.0 - alpha); (*result)[ptIdx].z = (*firstSet)[ptIdx].z * alpha + (*secondSet)[ptIdx].z * (1.0 - alpha); } extern "C" void applyBlendGPU( inputs::points_t firstSet, inputs::points_t secondSet, outputs::points_t result, inputs::alpha_t& alpha, size_t numberOfPoints ) { const int numberOfThreads = 256; const int numberOfBlocks = (numberOfPoints + numberOfThreads - 1) / numberOfThreads; applyBlendCUDA<<<numberOfBlocks, numberOfThreads>>>(firstSet, secondSet, result, alpha, numberOfPoints); } To see further examples of how CUDA compute can be used see the :ref:`CUDA tutorial node <ogn_tutorial_cudaData>`. .. _ogn_example_node_warp: Warp Version ------------ A Warp node is written in exactly the same way as a Python node, except for its `compute()` it will make use of the Warp cross-compiler to convert the Python into highly performant CUDA code. You'll notice that there is more boilerplate code to write but it is pretty straightforward, mostly wrapping arrays into common types, and the performance is the result. .. code-block:: python import numpy as np import warp as wp @wp.kernel def deform(first_set: wp.array(dtype=wp.vec3), second_set: wp.array(dtype=wp.vec3), points_out: wp.array(dtype=wp.vec3), alpha: float): tid = wp.tid() points_out[tid] = first_set[tid] * alpha + second_set[tid] * (1.0 - alpha) class OgnAddWeightedPoints: @staticmethod def compute(db) -> bool: if not db.inputs.points: return True with wp.ScopedDevice("cuda:0"): # Get the inputs first_set = wp.array(db.inputs.points, dtype=wp.vec3) second_set = wp.array(db.inputs.points, dtype=wp.vec3) points_out = wp.zeros_like(first_set) # Do the work wp.launch(kernel=deform, dim=len(first_set), inputs=[first_set, second_set, points_out, db.inputs.alpha]) # Set the result db.outputs.points = points_out.numpy() To see further examples of how Warp can be used see the `Warp extension documentation. <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_warp.html>`_ .. _ogn_example_node_slang: Slang Version ------------- Unlike the previous types, Slang implementations are done directly within the application. Once you create a blank Slang node you open up the property panel and use the **Add+** button to add the attributes. This is what the attribute definition window will look like for one of the inputs. .. image:: images/SlangAddInput.png Add the three inputs and one input in this way. In the end the property panel should reflect the addition of the attributes the node will use. .. image:: images/SlangFinalProperties.png .. note:: For now the array index is passed through to the Slang compute function as the `instanceId` as the function will be called in parallel for each element in the array. The number of elements is reflected in the attribute `inputs:instanceCount` as seen in the property panel. In an OmniGraph you can connect either of the input point arrays through an `ArrayGetSize<GENERATED - Documentation _ognomni.graph.nodes.ArrayGetSize>` node to that attribute to correctly size the output array. .. code-block:: cpp void compute(uint instanceId) { double alpha = inputs_alpha_get(); double[3] v1 = inputs_firstSet_get(instanceId); double[3] v2 = inputs_secondSet_get(instanceId); double[3] result = { v1[0] * alpha + v2[0] * (1.0 - alpha), v1[1] * alpha + v2[1] * (1.0 - alpha), v1[2] * alpha + v2[2] * (1.0 - alpha) }; outputs_result_set(instanceId, result); } To see further examples of how Slang can be used see the `Slang extension documentation <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph/slang-nodes/nodes/slang.html>`_ .. _ogn_example_node_auto: AutoNode Version ---------------- For this version, as with the Slang version, there is no *.ogn* file required as the type information is gleaned from the node type definition. For this example only a single point will be used for inputs and outputs as the arrays are not yet fully supported. You just execute this code in the script editor or through a file and it will define a node type `my.local.extension.blend_point` for you to use as you would any other node. .. code-block:: python @og.AutoFunc(pure=True, module_name="my.local.extension") def blend_point(firstSet: og.Double3, secondSet: og.Double3, alpha: og.Double) -> og.Double3: return ( firstSet[0] * alpha + secondSet[0] * (1.0 - alpha), firstSet[1] * alpha + secondSet[1] * (1.0 - alpha), firstSet[2] * alpha + secondSet[2] * (1.0 - alpha), ) To see further examples of how AutoNode can be used see the :ref:`AutoNode documentation<autonode_ref>`. Node Writing Tutorials ====================== We have a number of tutorials to help you write nodes in OmniGraph. This set of tutorials will walk you through the node writing process by using examples that build on each other, from the simplest to the most complex nodes. .. toctree:: :maxdepth: 2 :glob: :ref:`Node Writing Tutorials <ogn_tutorial_nodes>` OmniGraph Nodes In Kit ====================== This is an amalgamated collection of documentation for all OmniGraph nodes that have been defined in Kit proper. Other nodes may exist in other extensions and will be in the documentation for those extensions. .. toctree:: :maxdepth: 1 :glob: ../../../../_build/ogn/docs/*
18,789
reStructuredText
40.026201
151
0.667199
omniverse-code/kit/exts/omni.graph.core/docs/omnigraph_arch_decisions.rst
.. _omnigraph_architectural_decisions_log: OmniGraph Architectural Decisions Log ------------------------------------- This log lists the architectural decisions for OmniGraph. For new ADRs, please use :doc:`the ADR Decision template<decisions/adr-template>`. More information on MADR is available at `the MADR website <https://adr.github.io/madr/>`_. General information about architectural decision records is available at `the MADR GitHub repository <https://adr.github.io/>`_. .. toctree:: :maxdepth: 1 :glob: decisions/0**
547
reStructuredText
23.90909
128
0.698355
omniverse-code/kit/exts/omni.graph.core/docs/architecture.rst
OmniGraph Architecture ********************** Fabric ====== As mentioned in the introduction, one of the key dependencies that OmniGraph has is Fabric. While not doing it justice, in a nutshell Fabric is a cache of USD data in vectorized, compute friendly form. OmniGraph leverages Fabric's data vectorization feature to help optimize its performance. Fabric also facilitates the movement of data between CPU and GPU, allowing data to migrate between the two in a transparent manner. There are currently two kinds of caches. There is a single StageWithHistory cache in the whole system, and any number of StageWithoutHistory caches. When a graph is created, it must specify what kind of Fabric cache "backs" it. All the data for the graph will be stored in that cache. USD === Like the rest of Omniverse, OmniGraph interacts with and is highly compatible with USD. We use USD for persistence of the graph. Moreover, since Fabric is essentially USD in compute efficient form, any transient compute data can be "hardened" to USD if we so choose. That said, while it is possible to do so, we recommend that node writers refrain from accessing USD data directly from the node, as USD is essentially global data, and accessing it from the node would prevent it from being parallel scheduled and thus get in the way of scaling and distribution of the overall system. .. toctree:: :maxdepth: 2 :glob: OmniGraph representations in USD<usd_representations> Data model ========== The heart of any graph system is its data model, as it strictly limits the range of compute expressible with the graph. Imagine what sort of compute can be expressed if the graph can only accept two integers, for example. OmniGraph supports a range of options for the data coursing through its connections. Regular attributes ------------------ As the most basic and straightforward, you can predeclare any attributes supported by USD on the node. Give it a name, a type, and a description, and that's pretty much all there is to it. OGN will synthesize the rest. While straightforward, this option limits the data to that which is predeclared, and limits the data types to the default ones available in USD. Bundle ------ To address the limitations of "regular" attributes, we introduced the notion of the "bundle". As the name suggests, this is a flexible "bundle" of data, similar to a prim. One can dynamically create any number of attributes inside the bundle and transport that data down the graph. This serves two important purposes. First, the system becomes more flexible - we are no longer limited to pre-declared data. Second, the system becomes more usable. Instead of many connections in the graph, we have just a single connection, with all the necessary data that needs to be transported. Extended Attributes ------------------- While bundles are flexible and powerful, they are still not enough. This is because its often desirable to apply a given set of functionality against a variety of data types. Think, for example, the functionality to add things. While the concept is the same, one might want to add integers, floats, and arrays of them, to name a few. It would be infeasible to create separate nodes for each possible type. Instead, we create the notion of extended attributes, where the attribute has just an unresolved placeholder at node creation time. Once the attribute is connected to another, regular attribute, it resolves to the type of that regular attribute. Note that extended attributes will not extend to bundles. Dynamic Attributes ------------------ Sometimes, it is desirable to modify an individual node instance rather than the node type. An example is a script node, where the user wants to just type in some bits of Python to create some custom functionality, without going through the trouble of creating a new node type. To this end it would be really beneficial to just be able to add some custom attributes onto the node instance (as opposed to the node type), to customize it for use. Dynamic attributes are created for this purpose - these are attributes that are not predeclared, and do not exist on the node type, but rather tacked on at runtime onto the node instance. OGN === Node systems come with a lot of boilerplate. For example, for every attribute one adds on a node, there needs to be code to create the attribute, initialize its value, and verify its value before compute, as a few examples. If the node writer is made responsible for these mundane tasks, not only would that add substantially to the overall cost of writing and maintaining the node, but also impact the robustness of the system overall as there may be inconsistencies/errors in how node writers go about implementing that functionality. Instead, we created a code synthesizing system named OGN (OmniGraph Nodes) to alleviate those issues. From a single json description of the node, OGN is able to synthesize all the boilerplate code to take the burden off developers and keep them focused on the core functionality of the node. In addition, from the same information, OGN is able to synthesize the docs and the tests for the node if the node writer provides it with expected inputs and outputs. .. toctree:: :maxdepth: 2 :glob: :ref:`OGN Node Writer Guide<ogn_user_guide>` :ref:`OGN Reference Guide<ogn_reference_guide>` OmniGraph is a graph of graphs ============================== Due to the wide range of use cases it needs to handle, a key design goal for OmniGraph is to able to create graphs of any kind, and not just the traditional flow graphs. To achieve this goal, OmniGraph maintains strict separation between graph representation and graph evaluation. Different evaluators can attach different semantics to the graph representation, and thus create any kind of graph. Broadly speaking, graph evaluators translate the graph representation into schedulable tasks. These tasks are then scheduled with the scheduling component. Unfortunately, as of this writing this mechanism has not been fully exposed externally. Creating new graph types still requires modification to the graph core. That said, we have already created several graph types, including busy graph (push), lazy evaluation graph (dirty_push), and event handling graph (action). Although it's desirable to be able to create different graph types, the value of the different graph types would be diminished if they didn't interact with each other. To this end, OmniGraph allows graphs to interact with each other by coordinating the tasks each graph generates. The rule is that each parent graph defines the rules by which tasks from subgraphs will coordinate with its own. Practically speaking, this means that current graph types are interoperable with one another. For example it is possible to combine a lazy evaluation graph with a busy evaluation graph, by constructing the lazy evaluation graph as a subgraph of the busy one - this allows part of the overall graph to be lazy and part of it to be busy. The lazy part of the graph will only be scheduled if someone touches some node in the graph, whereas the busy part will be scheduled always. The diagram below ties the concepts together - here we have two graphs interacting with each other. The outer blue, push graph and the inner green lazy evaluation graph. Through graph evaluation (the first yellow arrow), the nodes are translated to tasks. Here the rectangles are nodes and circles are tasks. Note that the translation of the outer graph is trivial - each node just maps to 1 task. The inner lazy graph is slightly more complicated - only those nodes that are dirty (marked by yellow) have tasks to be scheduled (tasks 3,5). Finally, through the graph stitching mechanism, task 5 is joined to task 8 as one of its dependencies: .. image:: ./images/graph_stitching.png :align: center push Graph ---------- This is the simplest of graph types. Nodes are translated to tasks on a one to one basis every single frame, causing all nodes in the graph to be scheduled. dirty_push Graph ---------------- This is a lazy evaluation graph. When nodes are modified, they send dirty bits downstream, just like traditional pull graphs as in Maya or Houdini, if the reader is familiar with those systems. However, unlike standard pull graphs, all dirtied nodes are scheduled, rather than the subset whose output is requested as in standard pull graphs. This is due to the fact that our viewport is not yet setup to generate the "pull". That said, just by scheduling only the dirtied nodes, this graph already goes most of the way in terms of minimizing the amount of work by not scheduling nodes that have not changed. action graph ------------ This is a graph type that is able to respond to events, such as mouse clicked or time changed. In response to these events, we can trigger certain downstream nodes into executing. The graph works in a similar way to Blueprints in UnReal Engine, in case the user is familiar with that system. This graph contains specialized attributes (execution) that allow users to describe the execution path upon receipt of an event. Action graphs also supports constructs such as branching and looping. Subgraphs --------- Currently subgraphs can be defined within the scope of its parent graph, and can be of a different type of graph than its parent. As mentioned in the previous section, it's up to the parent graph to define the rules of interoperability, if any, between itself and the subgraphs it contains. Note that currently there are no rules defined between sibling subgraphs, and any connections between nodes of sibling subgraphs can lead to undefined behavior. Pipeline Stages =============== Graphs are currently organized into several categories, also called "pipeline stages". There are currently 4 pipeline stages: simulation, pre-render, post-render, and on-demand. Graphs in the simulation pipeline stage are run before those in pre-render which in turn are run before those in post-render. When a pipeline stage runs, all the graphs contained in the pipeline stage are evaluated. The on-demand pipeline stage is a collection of graphs that aren't run in the above described order. Instead, are individually run at an unspecified time. The owner of the graphs in the on-demand stage are responsible for calling evaluate on the graph and thus "ticking" them. Global Graphs ------------- Within each pipeline stage, there may be a number of graphs, all independent of each other. Each of these independent graphs are known as a global graph. Each of the global graphs may contain further subgraphs that interoperate with each other in the above described manner. Global graphs are special in two ways: 1. They may have their own Fabric. When the global graph is created, it can specify whether it wants to use the "StageWithHistory" cache, or its very own "StageWithoutHistory" cache. All subgraphs of the global graph must choose the "shared" Fabric setting, to share the cache of its parent global graph. Since there is only one StageWithHistory cache, specifying the shared option with a global graph is the same as specifying the StageWithHistory option. 2. They handle USD notices Currently, all subgraphs must share the Fabric cache of the parent global graph, and they do not handle their own USD notices. Global graphs that have their own cache can always be run in parallel in a threadsafe way. Global graphs that share a Fabric cache must be more careful - currently update operations (say moving an object by updating its transform) are threadsafe, but adding / deleting things from the shared Fabric are not. Orchestration Graph ------------------- Within a pipeline stage, how do we determine the order of execution of all the global graphs contained in it? The answer is the orchestration graph. Each global graph is wrapped as a node in this orchestration graph. By default, all the nodes are independent, meaning the graphs can potentially execute in parallel, independent of each other. However, if ordering is important, the nodes that wrap the graph may introduce edges to specify ordering of graph execution. While graphs in the on-demand pipeline stage also do have an orchestration graph, no edges are permitted in here as the graphs in this stage aren't necessarily executed together. Python ====== All of OmniGraph's functionality is fully bound to Python. This allows scripting, testing in Python, as well as writing of nodes in Python. Python is a first class citizen in OmniGraph. The full Python API and commands are documented here: .. toctree:: :maxdepth: 1 :glob: :ref:`Python Documentation<omniGraph_python_scripting>` Scheduling ========== As OmniGraph separates graph evaluation from graph representation, it also separates scheduling concerns from the other pieces. Once the graph evaluator does its job and translates the graph representation into tasks, we can schedule those tasks through any number of means. Static serial scheduler ----------------------- This is the simplest of the schedulers. It schedules tasks serially, and does not allow modification of the task graph. Realm scheduler --------------- This scheduler takes advantage of the Realm technology (super efficient microsecond level efficient scheduler) to parallel schedule the tasks. Dynamic scheduler ----------------- The dynamic scheduler allows the modification of the task graph at runtime, based on results of previous tasks. Currently the modification is limited to canceling of future tasks already scheduled. Extensions ========== Although you can see these in the extension window it is cluttered up with non-OmniGraph extensions. This is a distillation of how all of the **omni.graph.XXX** extensions depend on each other. Dotted lines represent optional dependencies. Lines with numbers represent dependencies on specific extension version numbers. Lines with `Test Only` represent dependencies that are only enabled for the purposes of running the extension's test suite. .. mermaid:: flowchart LR subgraph Core core(omni.graph.core) inspect(omni.inspect) py(omni.graph) tools(omni.graph.tools) end subgraph UI ui(omni.graph.ui) win(omni.graph.window.action) win_core(omni.graph.window.core) win_gen(omni.graph.window.generic) end subgraph Nodes ex_cpp(omni.graph.examples.cpp) ex_py(omni.graph.examples.python) action(omni.graph.action) exp(omni.graph.expression) nodes(omni.graph.nodes) script(omni.graph.scriptnode) io(omni.graph.io) end subgraph Support ext(omni.graph.example.ext) test(omni.graph.test) tut(omni.graph.tutorials) end bundle(omni.graph.bundle.action) core -.-> inspect py --> core py --> tools ex_cpp --> py ex_cpp --> tools ex_py --> py ex_py --> tools action --> py action --> tools action -.-> ui bundle --> py bundle --> action bundle --> nodes bundle --> tut bundle --> ui bundle --> win bundle --> inst inst --> core inst --> py inst --> tools inst --> nodes inst --> ui ui --> py ui --> tools ui -- Test Only --> action exp --> py exp --> tools ext --> py ext --> tools io --> py io --> ui nodes --> py nodes --> script nodes --> tools nodes -.-> ui script --> py script --> tools script --> action test --> py test --> tools test --> ex_cpp test --> ex_py test --> nodes test --> tut test --> action test --> script tut --> py tut --> nodes tut --> tools win_core -- 1.11 --> py win_core --> tools win_core -- 1.5 --> ui win_gen -- 1.16 --> win_core win_gen -- 1.5 --> ui win -- 1.16 --> win_core win -- 1.5 --> ui
16,177
reStructuredText
47.292537
458
0.740619
omniverse-code/kit/exts/omni.graph.core/docs/categories.rst
.. _omnigraph_node_categories: OmniGraph Node Categories ========================= An OmniGraph node can have one or more categories associated with it, giving the UI a method of presenting large lists of nodes or node types in a more organized manner. Category Specification In .ogn File ----------------------------------- For now the node categories are all specified through the .ogn file, so the node will inherit all of the categories that were associated with its node type. There are three ways you can specify a node type category in a .ogn file; using a predefined category, creating a new category definition inline, or referencing an external file that has shared category definitions. Predefined Categories +++++++++++++++++++++ This is the simplest, and recommended, method of specifying categories. There is a single .ogn keyword to add to the file to associate categories with the node type. It can take three different forms. The first is a simple string with a single category in it: .. code-block:: json { "MyNodeWithOneCategory": { "version": 1, "categories": "function", "description": "Empty node with one category" } } .. warning:: The list of categories is intentionally fixed. Using a category name that is not known to the system will result in a parsing failure and the node will not be generated. See below for methods of expanding the list of available categories. The second is a comma-separated list within that string, which specifies more than one category. .. code-block:: json { "MyNodeWithTwoCategories": { "version": 1, "categories": "function,time", "description": "Empty node with two categories" } } The last also specifies more than one category; this time in a list format: .. code-block:: json { "MyNodeWithAListOfTwoCategories": { "version": 1, "categories": ["function", "time"], "description": "Empty node with a list of two categories" } } The predefined list is contained within a configuration file. :ref:`Later<omnigraph_categories_shared_file>` you will see how to add your own category definitions. The predefined configuration file looks like this: .. literalinclude:: ../../../../source/extensions/omni.graph.tools/ogn_config/CategoryConfiguration.json :language: json .. note:: You might have noticed some categories contain a colon as a separator. This is a convention that allows splitting of a single category into subcategories. Some UI may choose to use this information to provide more fine-grained filtering an organizing features. Inline Category Definition ++++++++++++++++++++++++++ On occasion you may find that your node does not fit into any of the predefined categories, or you may wish to add extra categories that are specific to your project. One way to do this is to define a new category directly within the .ogn file. The way you define a new category is to use a *name:description* category dictionary rather than a simple string. For example, you could replace a single string directly: .. code-block:: json { "MyNodeWithOneCustomCategory": { "version": 1, "categories": {"light": "Nodes implementing lights for rendering"}, "description": "Empty node with one custom category" } } You can add more than one category by adding more dictionary entries: .. code-block:: json { "MyNodeWithTwoCustomCategories": { "version": 1, "categories": { "light": "Nodes implementing lights for rendering", "night": "Nodes implementing all aspects of nighttime" }, "description": "Empty node with two custom categories" } } You can also mix custom categories with predefined categories using the list form: .. code-block:: json { "MyNodeWithMixedCategories": { "version": 1, "categories": ["rendering", { "light": "Nodes implementing lights for rendering", "night": "Nodes implementing all aspects of nighttime" } ], "description": "Empty node with mixed categories" } } .. _omnigraph_categories_shared_file: Shared Category Definition File +++++++++++++++++++++++++++++++ While adding a category definition directly within a file is convenient, it is not all that useful as you either only have one node type per category, or you have to duplicate the category definitions in every .ogn file. A better approach is to put all of your extension's, or project's, categories into a single configuration file and add it to the build. The configuration file is a .json file containing a single dictionary entry with the keyword *categoryDefinitions*. The entries are *name:description* pairs, where *name* is the name of the category that can be used in the .ogn file and *description* is a short description of the function of node types within that category. Here is the file that would implement the above two custom categories: .. code-block:: json { "categoryDefinitions": { "$description": "These categories are applied to nodes in MyProject", "light": "Nodes implementing lights for rendering", "night": "Nodes implementing all aspects of nighttime" } } .. tip:: As with regular .ogn file any keyword beginning with a "*$*" will be ignored and can be used for documentation. If your extension is building within Kit then you can install your configuration into the build by adding this line to your *premake5.lua* file: .. code-block:: lua install_ogn_configuration_file("MyProjectCategories.json") This allows you to reference the new category list directly from your .ogn file, expanding the list of available categories using the .ogn keyword *categoryDefinitions*: .. code-block:: json { "MyNodeWithOneCustomCategory": { "version": 1, "categoryDefinitions": "MyProjectCategories.json", "categories": "light", "description": "Empty node with one custom category" } } Here, the predefined category list has been expanded to include those defined in your custom category configuration file, allowing use of the new category name without an explicit definition. If your extension is independent, either using the Kit SDK to build or not having a build component at all, you can instead reference either the absolute path of your configuration file, or the path relative to the directory in which your .ogn resides. As with categories, the definition references can be a single value or a list of values: .. code-block:: json { "MyNodeWithOneCustomCategory": { "version": 1, "categoryDefinitions": ["myConfigDirectory/MyProjectCategories.json", "C:/Shared/Categories.json"], "categories": "light", "description": "Empty node with one custom category" } } Category Access From Python --------------------------- Category Access From C++ ------------------------
7,300
reStructuredText
36.060914
120
0.673836
omniverse-code/kit/exts/omni.graph.core/docs/how_to.rst
.. _omnigraph_how_to: OmniGraph How-To Guide ====================== .. toctree:: :maxdepth: 2 :caption: How-To :glob: :ref:`Specifying Categories In Your Nodes <omnigraph_node_categories>` :ref:`Interfacing With OmniGraph <omnigraph_controller_class>` :ref:`Initializing Attribute Values At Runtime <runtime_attribute_value_initialization_in_omnigraph_nodes>` :ref:`Set Up Test Scripts <set_up_omnigraph_tests>` :ref:`Run Only A Python Script With OmniGraph code <run_omnigraph_python_script>`
521
reStructuredText
31.624998
110
0.700576
omniverse-code/kit/exts/omni.graph.core/docs/directory_structure.rst
.. _omnigraph_directory_structure: OmniGraph Directory Structure ----------------------------- It is advantageous to consider nodes as a separate type of thing and structure your directories to make them easier to find. While it's not required in order to make the build work, it's recommended in order to keep the location of files consistent. The standard Kit extension layout has these directories by default:: omni.my.feature/ bindings/ Files related to Python bindings of your C++ config/ extension.toml configuration file docs/ index.rst explaining your extension plugins/ C++ code used by your extension python/ __init__.py extension.py = Imports of your bindings and commands, and a omni.ext.IExt object for startup/shutdown scripts/ Python code used by your extension The contents of your *__init__.py* file should expose the parts of your Python code that you wish to make public, including some boilerplate to register your extension and its nodes. For example, if you have two scripts for general use in a *utility.py* file then your *__init__.py* file might look like this: .. code-block:: python """Public interface for my.extension""" import .extension import .ogn from .scripts.utility import my_first_useful_script from .scripts.utility import my_second_useful_script The C++ node files (OgnSomeNode.ogn and OgnSomeNode.cpp) will live in a top level *nodes/* directory and the Python ones (OgnSomePythonNode.ogn and OgnSomePythonNode.py) go into a *python/nodes/* subdirectory:: omni.my.feature/ bindings/ config/ docs/ nodes/ OgnSomeNode.ogn OgnSomeNode.cpp plugins/ python/ nodes/ OgnSomePythonNode.ogn OgnSomePythonNode.py If your extension has a large number of nodes you might also consider adding extra subdirectories to keep them together:: omni.my.feature/ ... nodes/ math/ OgnMathSomeNode.ogn OgnMathSomeNode.cpp physics/ OgnPhysicsSomeNode.ogn OgnPhysicsSomeNode.cpp utility/ OgnUtilitySomeNode.ogn OgnUtilitySomeNode.cpp ... .. tip:: Although any directory structure can be used, using this particular structure lets you take advantage of the predefined build project settings for OmniGraph nodes, and makes it easier to find files in both familiar and unfamiliar extensions.
2,677
reStructuredText
33.77922
120
0.649608
omniverse-code/kit/exts/omni.graph.core/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [2.65.4] - 2023-02-10 ### Fixed - Ordering of dependency node compute for AG fan-out with shared dependencies ## [2.65.3] - 2023-02-10 ### Removed - Remove a workaround now useless and affecting perf, as real fix has been merged ## [2.65.2] - 2022-12-20 ### Fixed - Crash fix when resizing a GPU buffer ## [2.65.1] - 2022-12-19 ### Fixed - Write back to Usd. ## [2.65.0] - 2022-12-16 ### Added - Initialize setting to ensure defaults are set properly the first run ## [2.64.8] - 2022-12-15 ### Fixed - Performance for processing of large node fan-in (action graph) ## [2.64.7] - 2022-12-12 ### Fixed - Previous fix is crashing in master. Reseting it to a state where it is actually stable on master ## [2.64.6] - 2022-12-09 ### Fixed - Invalidate any soon-to-be stalled pointers before deleting nodes ## [2.64.5] - 2022-12-08 ### Fixed - Accessing the size of an inexistent array was returning 1 ## [2.64.4] - 2022-12-06 ### Fixed - Don't assign the node's database until *after* its bucket has been invalidated. ## [2.64.3] - 2022-12-03 ### Fixed - Fixed crash when loading resolved string attributes ## [2.64.2] - 2022-11-29 ### Changed - GraphContext::invalidateBucket() now also invalidates the databases of downstream nodes. ### Fixed - OM-75593 Fixed DataModel::copyAttributeInternal for array attribute that used to set array size to 0 when src and dst was the same. ## [2.64.1] - 2022-11-22 ### Added - Documentation link in how-tos for running a minimal Kit with OmniGraph - Documentation for the various types of node implementations and what they are for ## [2.64.0] - 2022-11-17 ### Changed - Improved attach time overhead of OmniGraph for stages that do not contain OmniGraph prims ## [2.63.0] - 2022-11-14 ### Added - IGraphContext 3.3 -> 3.4: getVariableInstanceDataHandle, getVariableInstanceConstDataHandle ## [2.62.7] - 2022-11-11 ### Fixed - Do not reinitialize node's bucket to empty bucket. ## [2.62.6] - 2022-11-07 ### Fixed - potential crash on detach stage in same update that nodes are removed ## [2.62.5] - 2022-09-07 ### Changed - Fixes OM-62261 `og.OmniGraphInspector().as_json` Returns Bad Json ## [2.62.4] - 2022-10-20 ### Fixed - Made the category check more lenient, ignoring empty descriptions ## [2.62.3] - 2022-10-19 ### Changed - Fix for AG dependency logic ## [2.62.2] - 2022-10-08 ### Changed - Fix for evaluation of event inputs to latent nodes ## [2.62.1] - 2022-09-29 ### Fixed - Inconsistent evaluation of nodes with fan-in ## [2.62.0] - 2022-09-23 ### Changed - Extended attribute type values are now persisted to USD as customData - Dynamic extended attribute types are now persisted to scoped customData as well as deprecated unscoped ## [2.61.4] - 2022-09-21 ### Fixed - A bug in action graph logic related to fan-in ## [2.61.3] - 2022-09-08 ### Added - Fixed a bug in action graph traversal logic ## [2.61.2] - 2022-09-06 ### Changed - Gave a better error message for deprecated node type presence ## [2.61.1] - 2022-08-31 ### Fixed - Changed an error into an info message since it is usually harmless ## [2.61.0] - 2022-09-01 ### Added - Added isValid() methods to OG Obj ABI structs ## [2.60.0] - 2022-08-30 ### Removed - Temporary hack for Python node late delayed default value setting ### Added - Extra information to flag when the node type definition is responsible for deletion of default data memory ## [2.59.2] - 2022-08-25 ### Added - Architectural decision for splitting off the extensions into a separate repo - Added isValid() methods to OG Obj ABI structs ### Fixed - Made Fabric dump of connections provide a default when presented with bad data ### Changed - Updated the apply_change_info script to preserve local branch edits of extension.toml ## [2.59.1] - 2022-08-25 ### Fixed - Fixes ReadOnly array attribute sometimes having a dangling pointer ## [2.59.0] - 2022-08-25 ### Added - Support for new setting that turns deprecations into errors - New macro for flagging use of deprecated code path - Deprecation messages for code paths not using schema prims ## [2.58.2] - 2022-08-18 ### Fixed - Added missing call to tell nodes created from a Prim that they already have a default set ## [2.58.1] - 2022-08-15 ### Changed - Allow write variable to operate even if role types differs ## [2.58.0] - 2022-08-12 ### Changed - Node path is now added to console-logged messages - Node path is no longer added to messages captured on nodes ## [2.57.4] - 2022-08-11 ### Changed - Handles auto conversion in data model ## [2.57.3] - 2022-08-08 ### Added - Warning when schema prims are loaded when the setting is disabled. ## [2.57.2] - 2022-08-05 ### Fixed - action evaluator for cycles in connections ## [2.57.1] - 2022-08-04 ### Fixed - Avoided multiple `__metadata__bundle__` tokens in a path ## [2.57.0] - 2022-08-03 ### Changed - OGN Bundle wrapper `size` and `abi_primHandle` are marked as deprecated. ### Added - Two methods to OGN Bundle wrapper: `attributeCount` and `childCount`. ## [2.56.0] - 2022-08-02 ### Added - Update OGN Bundle wrapper to use IBundle2 ## [2.55.0] - 2022-08-02 ### Added - /persistent/omnigraph/enablePathChangedCallback to deprecate INode::registerPathChangedCallback - /persistent/omnigraph/disableInfoNoticeHandlingInPlayback optimization setting ### Changed - pathChangedCallback will now trigger once per OG update with accumulated changes instead of immediately ## [2.54.0] - 2022-07-28 ### Added - Added `IDirtyID` interface - Added `BundleAttrib` class and `BundleAttribSource` enumeration - Added `BundlePrim`, `BundlePrims`, `BundlePrimIterator` and `BundlePrimAttrIterator` - Added `ConstBundlePrim`, `ConstBundlePrims`, `ConstBundlePrimIterator` and `ConstBundlePrimAttrIterator` ## [2.53.1] - 2022-07-28 ### Fixed - Fixed handling of empty strings in operator< and operator> of ogn::base_string ## [2.53.0] - 2022-07-22 ### Added - IBundle2 - remove_attributes_by_name and remove_child_bundles_by_name ## [2.52.1] - 2022-07-27 ### Fixed - Fixed data model for storing attribute metadata in IBundle2 ## [2.52.0] - 2022-07-27 ### Changed - valueChanged callback handling ## [2.51.3] - 2022-07-23 ### Fixed - Fixed dirty_push graphs being re-run during playback when time has not advanced ## [2.51.2] - 2022-07-22 ### Fixed - Registration order of TfNotice handler for OG ## [2.51.1] - 2022-07-21 ### Fixed - OM-56991 Ill-formed sdf paths ## [2.51.0] - 2022-07-21 ### Changed - Undo revert and fix bug in evaluation of nodes with dynamic execution attribs ## [2.50.0] - 2022-07-19 ### Fixed - IBundle2 reviewed ABI, reviewed copy and link for attributes and bundles ## [2.49.0] - 2022-07-18 ### Changed - Reverted the changes in 2.48.0 ## [2.48.1] - 2022-07-18 ### Added - Better ReadPrimAttribute error reporting ## [2.48.0] - 2022-07-15 ### Changed - Action graph fan-out of execution wires are now evaluated in parallel instead of sequence ## [2.47.1] - 2022-07-12 ### Changed - Changed node create to write extended attributes to USD prior to node creation ## [2.47.0] - 2022-07-08 ### Added - 'deprecated' .ogn keyword for attributes - IInternal / omni.graph.core._internal - IInternal::deprecateAttribute() / omni.graph.core._internal.deprecate_attribute() - IAttribute::isDeprecated() / omni.graph.core.Attribute.is_deprecated() - IAttribute::deprecationMessage() / omni.graph.core.Attribute.deprecation_message() - 'internal' attribute metadata keyword ## [2.46.0] - 2022-07-08 ### Fixed - Fixed memory leak coming from NodeType objects ### Changed - INodeType 1.6 -> 1.7 - fileFormatVersion attribute on OmniGraph objects only writes to USD if it has changed ### Added - INodeType::destroyNodeType to deallocate a node type object ## [2.45.2] - 2022-07-07 ### Fixed - IConstBundle2 and IBundle2 broken logging system ## [2.45.1] - 2022-07-06 ### Added - Ability to raise an error/warning for a node through (new) static methods of the database ## [2.45.0] - 2022-06-30 ### Added - Metadata support for IBundle2 interface ## [2.44.3] - 2022-06-30 ### Changed - USD write back is now performed just once per frame per Fabric cache ## [2.44.2] - 2022-06-28 ### Fixed - Checked newly added nodes for file format version upgrade requirements ## [2.44.1] - 2022-06-28 ### Changed - Ensured nodeContextHandle is initialized correctly ## [2.44.0] - 2022-06-29 ### Changed - Deprecated IScheduleNode::getNode, INodeType::getScheduleNodeCount, INodeType::getScheduleNodes ## [2.43.1] - 2022-06-29 ### Added - A compile switch to disable OGN database caching ## [2.43.0] - 2022-06-28 ### Fixed - Array attributes not keeping a single copy of their data/size pointers as intended - Few places using P2AM directly instead of DataModel - Debugging features of DataModel - usdToCache overwritting connection informations - Bad performance of getLocalAttributeHandle ### Added - OGN Database caching at the node level - Tracking of changes that might invalidate this caching - Gives a chance to DataModel to prepare buckets of nodes at load time, in order to prevent useless rebucket later ## [2.42.0] - 2022-06-23 ### Added - clearContents method to IBundle2 interface ## [2.41.0] - 2022-06-22 ### Added - Faster check for deprecated node types ### Removed - Unused core node animation/OgnPointsWeight - Unused core node animation/OgnTextGenerator - Unused core node animation/OgnTimeSampleArray - Unused core node animation/OgnTimeSamplePoints - Unused core node animation/OgnXformDeformer - Unused core node animation/OgnXformSRT - Unused core node animation/OgnXformToFastCache - Unused core node core/OgnFetch - Unused core node core/OgnGather - Unused core node core/OgnScatter - Unused core node core/OgnSlang - Unused core node core/OgnTime - Unused core node core/OgnTimeSample - Unused core node core/OgnXtoY - Unused core node math/OgnVectorElementDecompose - Unused core node math/OgnVectorElementSet ## [2.40.4] - 2022-06-22 ### Changed - Fix for output attribute being resolved by downstream connection ## [2.40.3] - 2022-06-22 ### Added - Architectural decision records support - Added ADR for the decision around how to present the Python API surface ## [2.40.2] - 2022-06-21 ### Changed - Optimized attribute look up ## [2.40.1] - 2022-06-17 ### Changed - Added extra validity checks to bundle data access ### Added - Finished off the documentation for versioning, both internal and external ## [2.40.0] - 2022-06-17 ### Added - IGraph::getEvaluationName ### Changed - When using schemaPrims, OmniGraph now responds to changes made to graph settings in USD. ## [2.39.0] - 2022-06-16 ### Changed - ForceWriteBack mechanism (that was used to write back prim data to USD) is now soft deprecated behind a setting ### Added - A per attribute tracking system that allows to write back to USD at single attribute definition ## [2.38.3] - 2022-06-16 ### Fixed - cpp wrapepr getAttributesR template function, internally it wasn't casting to NameToken*. ### Changed - Outputs for `IBundle2::create*`, `IBundle2::link*` and `IBundle2::copy*` are optional. ## [2.38.2] - 2022-06-15 ### Fixed - Handled the one missing colorama reference ## [2.38.1] - 2022-06-14 ### Fixed - When removing the last attributes on a path, DataModel was failling to move it properly to the empty bucket ## [2.38.0] - 2022-06-13 ### Added - CreateGraphAsNodeOptions structure - GraphEvaluationMode enum - IGraph::getEvaluationMode - IGraph::setEvaluationMode - IGraph::createGraphAsNode(GraphObject&, const CreateGraphAsNodeOption*) ### Deprecated - IGraph::createGraphAsNode(GraphObject&, const char*, const char*, const char*, bool, bool, GraphBackingType, GraphPipelineStage) ## [2.37.1] - 2022-06-13 ### Fixed - Crash fix when trying to convert an invalid "FlatCacheBundle" to a value ## [2.37.0] - 2022-06-13 ### Added - Temporary support for flagging values already set for Python initialize ## [2.36.0] - 2022-06-08 ### Added - Pre-render evaluation functions ## [2.35.0] - 2022-06-07 ### Added - Support for the generator setting for Python optimization ## [2.34.3] - 2022-06-03 ### Fixed - Copy on Write for Child bundles ## [2.34.2] - 2022-06-02 ## Changed - Allow arguments arrayDepthsBuf and tuplesBuf for resolvePartiallyCoupledAttributes() to be null pointers ## [2.34.1] - 2022-06-01 ### Fixed - Input execution attribute are now reset to Disabled state when node enters latent state - Bug making bundle connection to legacy prim ## [2.34.0] - 2022-05-30 ### Changed - Connections between nodes are now not stored in fabric anymore - We now rely only on connections expressed in the Object Oriented Layer in OmniGraph core - DataModel now don't have to do extra logic to interpret FC connections as toppological connection or upstream reference ### Added - Ability to access and set default value on an attribute - Interfaced this new feature with python - Using this new feature in python OGN generator ### Fixed - Bug preventing to clear an attribute array in python ### Removed - Some useless dependencies/visibility to PathToAttributeMap ## [2.33.11] - 2022-05-27 ### Changed - Deprecated the GraphContext::updateToUsd() code path with useSchemaPrims off ### Fixed - Fixed the FlatCache dump in GraphContext, broken when FlatCache was upgraded - Fixed the graph population phase in PluginInterface to walk all graphs, not just the first one ## [2.33.10] - 2022-05-26 ### Fixed - Fixed memory leak with variables - Fixed errors caused by removing variables from Fabric ## [2.33.9] - 2022-05-24 ### Fixed - Attributes on bundle not properly materialized, attempt 2 ## [2.33.8] - 2022-05-18 ### Fixed - Attributes on bundle not properly materialized ## [2.33.7] - 2022-05-17 ### Fixed - Fixed reparenting graph to previous parent which otherwise corrupted fabric state and left nodes without properties ## [2.33.6] - 2022-05-17 ### Fixed - Duplicate bundle connections on rename ## [2.33.5] - 2022-05-16 ### Fixed - Connection-compatibility check for execution attributes ## [2.33.4] - 2022-05-16 ### Changed - Makes dynamic bundle works in python ## [2.33.3] - 2022-05-16 ### Changed - Fix type not properly registered in FC when adding new attributes ## [2.33.2] - 2022-05-13 ### Changed - Makes bundle works on node not backed by USD ## [2.33.1] - 2022-05-12 ### Changed - Array attribute are now using ABI, giving a chance to the framework to perform CoW and DS ## [2.33.0] - 2022-05-11 ### Changed - Refactoring of data model: centralized all FlatCache accesses in one place - MBiB now uses connections instead of bucket tagging ### Added - Lazy pointer retrieval (for read and write) in OGN layer - Array attribute and bundles are now passed by reference from node to node - Copy on Write: Array attributes/Bundle content are copied when mutated - ABI entry for batch attribute copy from one bundle/prim to another ### Fixed - Fixed som API for data retrieval in OGN layer that where missbehaving when used ### Removed - Data stealing prototype ## [2.32.2] - 2022-05-11 ### Fixed - Fixed read time node with pull evaluator when time changes outside of playback (e.g. timeline tool) ## [2.32.1] - 2022-05-06 ### Fixed - Fixed instances loaded from references requiring a stage reload to evaluate correctly ## [2.32.0] - 2022-05-05 ### Changed - Refactored settings to handle interdependencies ### Fixed - Changed std::is_pod to std::is_trivial for C++20 compatibility ### Added - Added architectural diagram of the OmniGraph extension interdependencies - Internal diagram of the schema prim code path dependencies - Adding callbacks in settings to handle interdependencies ## [2.31.3] - 2022-05-04 ### Fixed - Fixed a bit too agressive type unresolution on input attributes ## [2.31.2] - 2022-05-03 ### Fixed - Default variable values not always getting set to instances with no overrides ## [2.31.1] - 2022-05-02 ### Fixed - bug resolving values in certain extended attribute connections ## [2.31.0] - 2022-04-29 ### Changed - Passed graph prim for more targeted FlatCache initialization - Bumped file format to 1.4 - Made file format calls more tolerant of useSchemaPrims settings ## [2.30.3] - 2022-04-25 ### Changed - Only flush USD to flatcache when we are parsing the first root graph, otherwise previous changes to flatcache may be overwritten ## [2.30.2] - 2022-04-28 ### Fixed - Removed the obsolete parts of the unit tests ## [2.30.1] - 2022-04-26 ### Fixed - Fix situation with bad type resolution ## [2.30.0] - 2022-04-22 ### Added - `OmniGraphDatabase.getGraphTarget` - IGraphContext 3.1->3.2 - `IGraphContext.getGraphTarget` ## [2.30.0] - 2022-04-25 ### Removed - Removed the unimplemented IDataReference class - Removed the obsolete TestComputeGraph.cpp unit test ### Changed - Stopped building the obsolete nodes - Moved the generated substitutions.rst file to the build area ## [2.29.4] - 2022-04-21 ### Changed - "ui:"-prefixed attributes present on Node prims are no longer read as OG attributes ## [2.29.3] - 2022-04-19 ### Fixed - Rare crash that occurred when using string-based node attributes ## [2.29.2] - 2022-04-14 ### Fixed - __updateSimStepUsd__ disableUsdUpdates is respected ## [2.29.1] - 2022-04-08 ### Fixed - Auto conversion bug for native tuple ## [2.29.0] - 2022-04-08 ### Changed - Passed graph prim for more targeted FlatCache initialization - Bumped file format to 1.4 - Made file format calls more tolerant of useSchemaPrims settings ## [2.28.0] - 2022-04-08 ### Changed - input attribute types are no longer inferred from output attribute types. - type resolution and unresolution will no longer propagate upstream. ## [2.27.0] - 2022-04-08 ### Added - Added IGraphContext::getAbsoluteSimTime() function - Added ComputeGraph::updateV2() function which updates the absoluteSimTime ## [2.26.3] - 2022-04-07 ### Fixed - Graph::writeTokenSetting() was failing to update the token if it already existed but was empty. ### Changed - Graph::writeTokenSetting() no longer updates the token or issue a warning if the new value is the same as the existing one. ## [2.26.2] - 2022-04-05 ### Fixed - Fixes issues where ForceWriteBack token on newly created Nodes would not be respected unless the Prim of the Node was selected ## [2.26.1] - 2022-03-31 ### Fixed - Fixed issue when using OG in MGPU: forces use of Device 0 in StaticScheduler ## [2.26.0] - 2022-03-31 ### Added - `PrimHandle` and `ConstPrimHandle` renamed to `BundleHandle` and `ConstBundleHandle`. `PrimHandle` and `ConstPrimHandle` remain as aliases to `BundleHandle` and `ConstBundleHandle`. - `IConstBundle2` - ONI const bundle interface, successor of carbonite `IBundle`. - `IBundle2` - ONI bundle interface, successor of carbonite `IBundle`. - `IBundleFactory` - ONI factory to create instances of `IConstBundle2` and `IBundle2` interface. - Initial implementation of `IConstBundle2`, `IBundle2` and `IBundleFactory`. - `ComputeGraph` 2.6 -> 2.7. - `ComputeGraph::getBundleFactoryInterface` method added to instantiate bundle factory. - `IPath` new methods: `appendPath` and `getPathElementCount`. ## [2.25.2] - 2022-03-25 ### Fixed - Fixed issue where type resolution on node with coupled attribute would not work - Fixed auto type conversion not working on coupled attributes ## [2.25.1] - 2022-03-25 ### Fixed - dynamic scheduler will now evaluate execution subgraphs ## [2.25.0] - 2022-03-23 ### Added - IGraph 3.6 -> 3.7 - getEventStream - accessor to retrieve a graphs event stream - IGraphEvent enum type - IGraphEvent.eCreateVariable, raised when a variable is created through the ABI - IGraphEvent.eRemoveVariable, raised when a variable is removed through the ABI ## [2.24.0] - 2022-03-16 ### Added - Setting /persistent/omnigraph/enableLegacyPrimConnections. When enabled, this will restore legacy behavior for OG Prim nodes: - Entire stage is searched for connections between Nodes and Prims, any connected Prims will be brought into FC, and corresponding OG Prim nodes created with all attributes. - Terminal nodes will be automatically synced to FC every frame - This setting is not exposed in the UI. It is a temporary setting until legacy code can be migrated to no longer use Prim connections. ## [2.23.8] - 2022-03-15 ### Fixed - Fixed issue where ComputeGraphs in sublayers may not correctly load ## [2.23.7] - 2022-03-14 ### Fixed - Auto type conversion was not correctly computed on load ## [2.23.6] - 2022-03-14 ### Fixed - Bug in default string attribute initialization ## [2.23.5] - 2022-03-09 ### Added - Added a check to make sure that literalOnly attributes cannot be connected to other attributes ## [2.23.4] - 2022-03-08 ### Fixed - Cleanup of graph deletion ## [2.23.3] - 2022-03-08 ### Changed - Modified the node type registration/deregistration process to avoid static destructor ordering problems and allow multiple initialize/release calls ## [2.23.2] - 2022-03-07 ### Fixed - Removed unnecessary migration of bundle connection members to a copied bundle ## [2.23.1] - 2022-03-05 ### Fixed - __RenderVar__ prim data will be automatically loaded into FC when they are part of an OG network ## [2.23.0] - 2022-03-04 ### Changed - Removed the _updateTerminalNodesOnly_ setting, the default of _updateToUSD_ is now False. OG will now only sync Prims FC->USD with the _ForceWriteBack_ token when _updateToUSD_ is False. When the setting is True, it will sync all Prims. - Added _settingsVersion_ setting ## [2.22.3] - 2022-03-04 ### Changed - OG will no longer automatically load non-OG Prim data into FC during stage attach. ## [2.22.2] - 2022-03-02 ### Fixed - Added support for omni.graph.nodes.ReadTime to lazy (dirty_push) evaluator ## [2.22.1] - 2022-02-18 ### Changed - Bug fix in path attribute monitoring: properly retarget subpath when reparenting happens higher in the hierarchy ## [2.22.0] - 2022-02-18 ### Added - Added tests for schema-based prims - Added test case base class factory method ### Fixed - Fixed handling of the schema-based prims - Removed use of deprecated OmniGraphHelper from some scripts ## [2.21.4] - 2022-02-18 ### Changed - Bug fix accessing a deleted entry in a map ## [2.21.3] - 2022-02-17 ### Changed - Added proper support for path role (that keep track of the target) ## [2.21.2] - 2022-02-16 ### Changed - Changed Fabric Cache creation to new `create2` to allow RingBuffers to have CUDA enabled ## [2.21.1] - 2022-02-15 ### Fixed - Categories on several nodes ## [2.21.0] - 2022-02-15 ### Added - Added support for update_usd flag to the data_view and SetAttr command ### Fixed - Ignored the Expression node for the warning on nodes without namespaces - Avoided a crash when the fileFormatVersion attribute could not be found ## [2.20.0] - 2022-02-13 ### Changed - Prim nodes will no longer have OG attributes automatically added - Prim node authored USD attributes added to FC - Removed support for special attribute OGN_NonUSDConnections ## [2.19.0] - 2022-02-11 ### Added - Added OmniGraphDatabase.getVariable ## [2.18.0] - 2022-02-10 ### Added - Added setting for using schema prims for graphs and nodes. - Added use of the omniGraphSchema library for graph and node prims (protected by the setting). ## [2.17.0] - 2022-02-08 ### Changed - Added support for auto conversion between attributes. ## [2.16.1] - 2022-02-07 ### Changed - Moved carb logging out of Database.h and into Node::logComputeMessage. ## [2.16.0] - 2022-02-05 ### Added - IGraph 3.5 -> 3.6 - Added IGraph::createVariable - Added IGraph::removeVariable - Added IGraph::findVariable - IVariable - Added IVariable::getDisplayName and IVariable::setDisplayName - Added IVariable::getCategory and IVariable::setCategory - Added IVariable::getTooltip and IVariable::setTooltip - Added IVariable::getScope and IVariable::setScope - Added IVariable::isValid ## [2.15.1] - 2022-02-04 ### Fixed - Edge cases in action graph evaluator for fan-in and fan-out of execution attributes ## [2.15.0] - 2022-02-02 ### Added - IGatherPrototype 1.1 -> 2.0 - Changed the signature of _gatherPaths_ - Added _getGatheredRepeatedPaths_ ## [2.14.0] - 2022-02-01 ### Added - ComputeGraph 1.0 -> 1.1 - Added *IOmniGraphTest::setTestFailure* - Added *IOmniGraphTest::testFailureCount* - Python bindings at the module level - Added *set_test_failure* - Added *test_failure_count* - Added deregistration macro for earlier deregistration of node types (done in a backwards compatible way) ## [2.13.0] - 2022-01-31 ### Changed - IVariable.getPath renamed to IVariable.getSourcePath ## [2.12.0] - 2022-01-28 ### Fixed - Error status change callbacks weren't firing during normal evaluations. - Bumping the minor version # since features which use the callbacks will not work without this change. ## [2.11.0] - 2022-01-26 ### Added - INode 4.1 -> 4.2 - Added INode::logComputeMessage - Added INode::getComputeMessageCount - Added INode::getComputeMessage - Added INode::clearOldComputeMessages - IGraph 3.4 -> 3.5 - Added IGraph::registerErrorStatusChangeCallback - Added IGraph::deregisterErrorStatusChangeCallback - Added IGraph::nodeErrorStatusChanged - Added IGraph::getVariableCount - Added IGraph::getVariables - Created the IVariable type ### Changed - OmniGraphDatabase::logWarning and logError now log compute messages whenever they are different from the node's previous evaluation. Previously they would only log a given error once per session and node type. ## [2.10.1] - 2022-01-19 ### Changed - Fixed a bug in attribute resolution propagation logic ## [2.10.0] - 2022-01-18 ### Changed - Extended attributes will now be returned to an unresolved state upon disconnection if the topology of the graph does not prevent it. ## [2.9.0] - 2022-01-17 ### Added - INode 4.0 -> 4.1 - Added INode::getComputeCount - Added INode::incrementComputeCount ## [2.8.0] - 2022-01-13 ### Added - IGraphRegistry 1.1 -> 1.2 - Added _IGraphRegistry::getRegisteredType_ ## [2.7.0] - 2022-01-06 ### Modified - _GraphContextObj.context_ has been replaced with _GraphContextObj.contextHandle_. The old member was a pointer to an internal OG class. The new member is a POD handle which can be used with OG ABI functions. ## [2.6.1] - 2021-12-30 ### Modified - _INode::resolvePartiallyCoupledAttributes_ checks more type resolution error conditions. ## [2.6.0] - 2021-12-21 ### Added - IAttributeData 1.3 -> 1.4 - Added _IAttributeData::getDataRGpuAt_ - Added _IAttributeData::getDataWGpuAt_ - Added _IAttributeData::getDataReferenceRGpuAt_ - Added _IAttributeData::getDataReferenceWGpuAt_ ## [2.5.1] - 2021-12-16 ### Changed - Action Graph evaluator now uses `og.ExecutionAttributeState.LATENT_FINISH` to indicate when a latent node is finished. ## [2.5.0] - 2021-12-10 ### Added - Created the INodeCategories interface - ComputeGraph 2.4 -> 2.5 - Added _ComputeGraph::getNodeCategories_ ## [2.5.1] - 2021-12-08 ### Fixed - Fix RuntimeAttribute getXX templates to avoid an MSVC compiler bug ## [2.4.0] - 2021-12-07 ### Added - IGraph 3.3 -> 3.4 - Added _IGraph::isGlobalGraphPrim_ - Modified RuntimeAttribute to include PtrToPtrKind template, with default for backward compatibility ## [2.3.0] - 2021-12-06 ### Added - Added _INodeEvent::eAttributeTypeResolve_ ## [2.2.1] - 2021-12-02 ### Fixed - Fix bug where renaming a graph doesn't rename the wrapper node, resulting in new graphs overwriting old graphs ## [2.2.0] - 2021-11-26 ### Added - Python Bindings 2.1.0 -> 2.2.0 - Added Python api `Graph.get_parent_graph` - Ignore connections to ComputeGraph prims for the new OmniGraph UI. ## [2.1.0] - 2021-11-26 ### Added - IAttributeType 1.2 -> 1.3 - Added _IAttributeType::isLegalOgnType_ ## [2.0.3] - 2021-11-25 ### Added - INodeType 1.5 -> 1.6 - Added _INodeType::getName_ ## [2.0.2] - 2021-11-24 ### Fixed - Fix for handling of referenced OmniGraph Graphs ## [2.0.1] - 2021-11-18 Exposing attribute optional flag. ### Added - IAttribute 1.8 -> 1.9 - Added _IAttribute::getIsOptionalForCompute_ - Added _IAttribute::setIsOptionalForCompute_ ## [2.0.0] - 2021-11-12 Major change to deprecate functionality that has been on the chopping block for a while now. ### Removed - Removed _PlugFlags_ - Removed _kPlugFlagNone_ - Removed _kPlugFlagFollowUpstream_ - INode 3.1 -> 4.0 - Retired _getPlug_ - Retired _stashPlug_ - Retired _getStashedPlugCount_ - Retired _getStashedPlug_ - IGraphContext 2.1 -> 3.0 - Retired _getAttribute_ - Retired _getAttributeWithAttr_ - Retired _getAttributeGPU_ - Retired _getElementCount_ ## [1.4.1] - 2021-11-10 - Fixed bugs where renaming the global graph breaks connections and where bundles don't work in global graphs ## [1.4.0] - 2021-11-10 ### Added - New Interface ISchedulingHints - Added _ISchedulingHints::getComputeRule_ - Added _ISchedulingHints::setComputeRule_ ## [1.3.1] - 2021-11-08 ### Changed - ISchedulingHints 1.0 -> ONI - Kept same functionality, implemented as ONI interface instead of Carbonite interface ## [1.3.0] - 2021-11-04 ### Added - INode 3.1 -> 3.2 - Added _INode::requestCompute_ ## [1.3.0] - 2021-10-27 ### Added - IGraph 3.2 -> 3.3 - Added _IGraph::evaluate_ ## [1.2.0] - 2021-10-18 ### Changed - Prim nodes now not created unless attribute-connected to OG node ### Added - IGraph 3.1 -> 3.2 - Added _IGraph::getFlatCacheUserId_ - IAttribute 1.8 -> 1.9 - Added _IAttribute::ensurePortTypeInName_ - Added _IAttribute::getPortTypeFromName_ - Added _IAttribute::removePortTypeFromName_ ## [1.1.0] - 2021-10-13 ### Added - IAttribute 1.7 -> 1.8 - Added _IAttribute::isValid_ - INode 3.0 -> 3.1 - Added _INode::isValid_ - IGraph 3.0 -> 3.1 - Added _IGraph::isValid_ - IGraphContext 2.0 -> 2.1 - Added _IGraphContext::isValid_ ## [1.0.6] - 2021-10-08 ### Added - FileFormatVersion 1.1 -> 1.2 - Added support for scoped graphs in the editor ## [1.0.5] - 2021-10-07 ### Added - IBundle 1.3 -> 1.4 - Added _IBundle::addAttributes_ - Added _IBundle::removeAttributes_ ## [1.0.4] - 2021-09-30 ### Added - Created ISchedulingHints 1.0 - Added _ISchedulingHints::getThreadsafety_ - Added _ISchedulingHints::setThreadsafety_ - Added _ISchedulingHints::getDataAccess_ - Added _ISchedulingHints::setDataAccess_ - INodeType 1.4 -> 1.5 - Added _INodeType::getSchedulingHints_ - Added _INodeType::setSchedulingHints_ ## [1.0.3] - 2021-09-29 ### Added - ComputeGraph 2.3 -> 2.4 - Added _ComputeGraph::getGraphCountInPipelineStage_ - Added _ComputeGraph::getGraphsInPipelineStage_ - Added _GraphBackingType::kGraphBackingType_None_ ## [1.0.3] - 2021-09-23 ### Added - IGraph 2.1 -> 3.0 - Changed the signature of _IGraph::createGraphAsNode_ - Added _IGraph::getGraphBackingType_ - Added _IGraph::getPipelineStage_ ## [1.0.3] - 2021-09-21 ### Added - IGatherPrototype 1.0 -> 1.1 - Added _getGatherArray_ - Added _getGatherArrayGPU_ - Added _getGatherPathArray_ - Added _getGatherArrayAttributeSizes_ - Added _getGatherArrayAttributeSizesGPU_ - Added _getElementCount_ ## [1.0.3] - 2021-09-16 ### Added - IAttribute 1.6 --> 1.7 - Added _IAttribute::isDynamic()_ - Added _IAttribute::getUnionTypes()_ ## [1.0.3] - 2021-09-15 ### Added - IAttributeData 1.2 --> 1.3 - Added _IAttributeData::cpuValid()_ - Added _IAttributeData::gpuValid()_ ## [1.0.3] - 2021-08-30 ### Added - IGraph 2.0 --> 2.1 - Added _IGraph::reloadFromStage()_ ## [1.0.2] - 2021-08-18 ### Added - INode 2.0 -> 2.1 - Added _INode::getEventStream_ ## [1.0.2] - 2021-08-09 ### IGatherPrototype 1.0 - Added _IGatherPrototype::gatherPaths_ - Added _IGatherPrototype::getGatheredPaths_ - Added _IGatherPrototype::getGatheredBuckets_ - Added _IGatherPrototype::getGatheredType_ ## [1.0.2] - 2021-07-26 ### Changed - INode 1.6 --> 2.0 - Changed the signature of _INode::createAttribute_ ## [1.0.2] - 2021-07-16 ### Added - INodeType 1.3 -> 1.4 - Added _INodeType::removeSubNodeType()_ ## [1.0.2] - 2021-07-14 ### Changed - IGraph 1.3 -> 2.0 - Changed the signature of _IGraph::createSubgraph_ ## [1.0.2] - 2021-07-12 ### Added - IGraph 1.2 -> 1.3 - Added _IGraph::createGraphAsNode_ ## [1.0.2] - 2021-07-04 ### Added - INode 1.5 -> 1.6 - Added _INode::getWrappedGraph()_ ### Changed - ComputeGraph 2.2 -> 2.3 - Changed the semantics of getGraphCount, getGraphs, getGraphContextCount, getGraphContexts ## [1.0.2] - 2021-07-01 ### Added - INode 1.4 -> 1.5 - Added _INode::registerPathChangedCallback()_ - Added _INode::deregisterPathChangedCallback()_ ## [1.0.2] - 2021-06-21 ### Added - IAttribute 1.5 -> 1.6 - Added _IAttribute::getPortType()_ ## [1.0.2] - 2021-06-11 ### Added - IBundle 1.2 -> 1.3 - Added _IBundle::removeAttribute_ - IGraphContext 1.3 -> 1.4 - Added _IGraphContext::getTimeSinceStart()_ ## [1.0.2] - 2021-06-10 ### Added - INodeType 1.2 -> 1.3 - Added _INodeType::getSubNodeTypeCount_ - Added _INodeType::getAllSubNodeTypes_ - IDataStealinPrototype 1.0 - Added _IDataStealingPrototype::actualReference_ - Added _IDataStealingPrototype::moveReference_ - Added _IDataStealingPrototype::enabled_ - Added _IDataStealingPrototype::setEnabled_ ## [1.0.2] - 2021-06-01 ### Changed - INode 1.3 -> 1.4 - Modified _INode::registerConnectedCallback_ - Modified _INode::registerDisconnectedCallback_ - Modified _INode::deregisterConnectedCallback_ - Modified _INode::deregisterDisconnectedCallback_ ## [1.0.2] - 2021-05-31 ### Added - IGraph 1.1 -> 1.2 - Added _IGraph::registerPreLoadFileFormatUpgradeCallback_ - Added _IGraph::registerPostLoadFileFormatUpgradeCallback_ - Added _IGraph::deregisterPreLoadFileFormatUpgradeCallback_ - Added _IGraph::deregisterPostLoadFileFormatUpgradeCallback_ ## [1.0.2] - 2021-05-05 ### Added - IGraph 1.0 -> 1.1 - Added _IGraph::inspect()_ - IAttributeData 1.1 -> 1.2 - Added _IAttributeData::getDataReferenceR()_ - Added _IAttributeData::getDataReferenceRGpu()_ - Added _IAttributeData::getDataReferenceW()_ - Added _IAttributeData::getDataReferenceWGpu()_ - IAttributeType 1.0 -> 1.1 - Added _IAttributeType::inspect()_ - Added _IAttributeType::baseDataSize()_ - Added _IGraphRegistry::inspect()_ - Added _IGraphRegistry::registerNodeTypeAlias()_ - Added _INodeType::inspect()_ - INode 1.2 -> 1.3 - Added _INode::resolveCoupledAttributes()_ - Added _INode::resolvePartiallyCoupledAttributes()_ - INode 1.1 -> 1.2 - Added _INode::getNodeTypeObj()_ - IGraphContext 1.1 -> 1.2 - Added _IGraphContext::inspect()_ ## [1.0.1] - 2021-04-07 ### Added - Created the interface IAttributeType for working with the Type struct ## [1.0.0] - 2021-03-01 ### Initial Version - Started changelog with initial released version of the OmniGraph core
34,930
Markdown
29.29575
149
0.718752
omniverse-code/kit/exts/omni.graph.core/docs/versioning.rst
.. _omnigraph_versioning: OmniGraph Versioning #################### There are many facets to OmniGraph that can and will change over time as OmniGraph is still very much a work in progress. In order to minimize disruption to our users all of these types of changes have been enumerated and incremental deprecation plans have been created. .. _omnigraph_deprecation_communication: Deprecation Communication ************************* The first thing we will do when some functionality is to be deprecated is to communicate our intent in the #omni-graph Slack channel, and in the Slack channel of any groups we believe will be affected by the change. The intent of this initial communication is to coordinate with stakeholders to come to an agreement on a timeline for the deprecation. Once a date has been determined we will proceed with up to three phases of deprecation. The combination of phases will depend on the exact nature of the change and the timeline that has been decided. .. _omnigraph_soft_deprecation: Soft Deprecation ================ The soft deprecation phase is where a setting will be introduced to toggle between the old and new behaviors. The difference between the two could be as trivial as the availability of a deprecated function or as complex as a complete replacement of a commonly used data structure or algorithm. The setting will be a Carbonite setting under the tree `/persistent/omnigraph/deprecation/...`. At this phase the default value of the setting will be to take the original code paths, which will remain untouched. Communication of the change will take place in two ways: - An **@channel** announcement will be posted in the Slack channel(s) indicating the new behavior is available - A deprecation message is added to the original code paths as a one-time warning .. _omnigraph_default_deprecation: Default Deprecation =================== Once you have had a chance to migrate to the new behavior the default behavior will switch: - An **@channel** announcement will be posted in the Slack channel(s) indicating the new behavior is to be the default - The setting default will change to take the new code path - The settings manager will emit a deprecation warning whenever the setting is changed to specify the old code path .. _omnigraph_hard_deprecation: Hard Deprecation ================ In the rare case when old behavior must be completely removed, after the agreed on time has passed the old code path will be removed: - An **@channel** announcement will be posted in the Slack channel(s) indicating the old behavior is being removed - The setting and all of the old code paths will be physically deleted - The settings manager will emit an error whenever the now-deleted setting is attempted to be accessed .. _omnigraph_semantic_versioning: Semantic Versioning ******************* CHANGELOG.md:and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`_, mostly applied to changes made via the extension versions. Given a version number MAJOR.MINOR.PATCH, increment the: **MAJOR** version when you make incompatible API changes, **MINOR** version when you add functionality in a backwards compatible manner **PATCH** version when you make backwards compatible bug fixes. What this means to the C++ programmer is: **MAJOR** change: You must recompile and potentially refactor your code for compatibility **MINOR** change: You can use your code as-is in binary form, and optionally recompile for compatibility **PATCH** change: Your code works as-is in binary form, no need for recompiling What this means to the Python programmer is: **MAJOR** change: Your code may not work. You should refactor to restore correct execution. **MINOR** change: Your code will continue to work, however you may receive deprecation warnings and should refactor your code to use the latest interfaces. **PATCH** change: Your code will be mostly unaware of the change, other than corrections to previously incorrect behaviours. (You may need to refactor if your code relied on incorrect behaviour.) .. _omnigraph_public_python_api: The Public Python API ===================== We are using the `PEP8 Standard <https://peps.python.org/pep-0008/#public-and-internal-interfaces>`_ for defining the actual public API we are supporting. .. warning:: Although the nature of Python allows you to inspect and access pretty much anything if it doesn't appear as part of our "published" API then it is subject to change at any time without warning. If there is something that is not part of the interface you might find particular useful then request that it be surfaced. The model of import we use is similar to what is used by popular packages like `numpy`, `pandas`, and `scikit-learn`. You import the top level module as a simple prefix and use the API directly from there. .. code-block:: python # The core OmniGraph functionality import omni.graph.core as og og.get_all_graphs() There are two more modules we provide for interacting with OmniGraph: .. code-block:: python # A subset of the OmniGraph functionality that facilitates integration testing import omni.graph.core.tests as ogt # NOT YET AVAILABLE: A subset of the OmniGraph functionality that implements the AutoNode functionality import omni.graph.core.autonode as oga # NOT YET AVAILABLE: The code generator framework - for utilities, key/value constants, and typing import omni.graph.tools as ogn .. hint:: The Python bindings to our ABI are considered part of the published API and are available in the same way as all of the other Python functions. They are available in the `omni.graph.core` module. Getting Old Versions -------------------- By default you will always get the latest version of the module, however some level of backward compatibility will be provided through importing a version-specific module. This module will be frozen at the state of the API contents as of the specified version so that you can continue to access old functionality without warnings until such time as it is :ref:`hard deprecated<omnigraph_hard_deprecation>`. .. code-block:: python import omni.graph.core._1 as og og.the_deprecated_function() Other Types Of Versions ======================= OmniGraph Extension Versions ---------------------------- As with other parts of Kit the OmniGraph extensions have their own version number, and the interface definitions each have their own version number. These version numbers follow the general guidelines used by Kit. .. only:: internal Internal: link to Kit / exts-main-doc broken until kit_repo_docs migration completed (bidirectional dependency bad) .. _omnigraph_carbonite_versions: OmniGraph Carbonite Interface Versions -------------------------------------- A good portion of the OmniGraph interfaces are Carbonite style for historic reasons, so they will follow the Carbonite upgrade procedures. The primary rules are: - Existing functions in an interface always work as described - Functions are never removed from an interface - Add all new functions to the end of the interface - Increment the minor version of the interface whenever a new function is added .. hint:: Most Carbonite version changes will result in a corresponding minor version bump of the extension in which they live as it involves new functionality being added. .. _omnigraph_oni_versions: OmniGraph ONI Versions ---------------------- Some of the OmniGraph interfaces, and those developed in the future, will be ONI style, so they will follow the ONI upgrade procedures. The primary rules are: - Once an interface is published it can never be changed - New functionality in an interface is created by adding a new version that is a derived class (e.g. *IBundle2* and *IBundle3*) .. hint:: Most ONI version changes will result in a corresponding minor version bump of the extension in which they live as it involves new functionality being added. OmniGraph File Format Versions ------------------------------ The OmniGraph nodes also have a USD backing which itself contains a file format version number. For the most part this version number is strictly used to automatically migrate a USD scene to the latest version as it would be problematic to maintain multiple versions within the same code base. It appears as an attribute on the *OmniGraph* prim type. .. code-block:: USD :caption: OmniGraph prim using version 1.4 def OmniGraph "TestGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 4) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" token evaluationMode = "Automatic" } OGN Code Generator Versions --------------------------- There is also a version number for the .ogn node generator. It is equal to the version number of the extension containing it (*omni.graph.tools*) and is embedded into the generated code for version management. You should not need to worry about this version number unless you want to file a bug report, where it would be valuable information. Node Type Versions ------------------ Every node type definition has a version number with it. The number should be incremented every time there is a change in behavior of the node, such as adding or removing attributes or changing the computation algorithm. This applies to nodes you write as well as nodes you consume. A mismatch in version number between a node being created and the current node implementation will trigger a callback to the `updateNodeVersion` function, which your node can override if there is some cleanup you can do that will help maintain expected operation of the node. Protecting Yourself With Tests ****************************** OmniGraph uses something called the Extension Testing Matrix to validate any dangerous changes. The more tests you have written that typify your pattern of OmniGraph use the safer it will be for you when changes are made. We can't run tests we don't have so please help us help you; write more tests!
10,183
reStructuredText
41.789916
199
0.750172
omniverse-code/kit/exts/omni.graph.core/docs/core_concepts.rst
OmniGraph Core Concepts *********************** .. _omnigraph_concept_node: Node ==== The heart of any node graph system is of course, the node. The most important exposed method on the node is one to get an attribute, which houses all of the data the node uses for computing. The most import method you implement is the ``compute`` method, which performs the node's computation algorithm. .. _omnigraph_concept_context: GraphContext ============ The graph context contains things such as the current evaluation time and other information relevant to the current context of evaluation (and hence the name). Thus, we can ask it for the values on a particular attribute (as it will need to take things such as time into consideration when determining the value). .. _omnigraph_concept_attribute: Attribute ========= An attribute has a name and contains some data. This should be no surprise to anyone who has worked with graphs before. Attributes can be connected to other attributes on other nodes to form an evaluation network. In C++ an AttributeObj, which references a specific NodeObj, uniquely identifies a location in the graph. Once we have the attribute, we can ask the graph context for the value of that attribute. .. _omnigraph_concept_nodetype: NodeType ======== In order to register a new type of node with the system, we’ll need to fill the exposed ``INodeType`` interface with our own custom functions in order to register our new node type with the system. To simplify this process a descriptive format (.ogn files) has been created which is described in :ref:`ogn_user_guide`. Each node type has a unique implementation of the ``INodeType`` interface. This can be used for both C++ and Python node type implementations. Type ==== OmniGraph mostly relies on Fabric for data, and Fabric was designed to mostly just mirror the data in USD, but in more compute friendly form. That said, we did not want to literally use the USD data types, as that creates unnecessary dependencies. Instead, we create data types that are binary compatible to the USD data types (so can be cast to it), but can be defined independently. Also, our types capture some usefule metadata, such as the role of the data. For example, a float3 can be used both to describe a position as well as a normal. However, the way the code would want to deal with the data is very different depending on which of the two roles it plays. Our types have a *role* field to capture this sort of meta-data. Currently our data type strucuture captures the following: - Base Data Type: can be bool, uchar, int, uint, int64, uint64, half, float, double, token, relationship, asset, prim, connection, tag - Component Count: 1 for raw base types, 2 for things like vector2f, 3 for point3d, normal3f etc - Array Depth: 0 for single value, 1 for array, 2 for array of array (not yet supported) - Role: can be none, vector, normal, position, color, texcoord, quaternion, frame, time code, text, applied schema, prim type name, execution, matrix, object id, or unknown Bundle Attributes ================= To address the limitations of “regular” attributes, we introduced the notion of the “bundle”. As the name suggests, this is a flexible bundle of data, similar to a prim. One can dynamically create any number of attributes inside the bundle and transport that data down the graph. This serves two important purposes. First, the system becomes more flexible - we are no longer limited to pre-declared data. Second, the system becomes more usable. Instead of many connections in the graph, we have just a single connection, with all the necessary data that needs to be transported. .. _omnigraph_concept_registry: GraphRegistry ============= This is where we register new node types (and unregister, when our plugin is unloaded). The code generated through the descriptive .ogn format automatically handles interaction with the registry. .. _omnigraph_concept_fabric: Fabric DataModel ================ The data model for OmniGraph is based on the Fabric data manager. Fabric is used as a common location for all data within the nodes in OmniGraph. This common data location allows for many efficiencies. Further, the Fabric handles data synchronization between CPU data, GPU data, and USD data, offloading that task from OmniGraph.
4,330
reStructuredText
51.180722
578
0.764434
omniverse-code/kit/exts/omni.graph.core/docs/usd.rst
OmniGraph And USD ################# USD is used as a source of data for OmniGraph. Both can be described as a set of nodes, attributes, and connections, each with their own set of strengths and restrictions. USD is declarative - it has no system for procedurally generating attribute values (such as expression binding, keyframing, etc). Timesamples can give different values when requested at different times, however they too are declarative - they are fixed values at fixed times and are unaffected by any configuration of the USD stage outside of composition. OmniGraph adds a procedural engine to Omniverse on top of USD that does generate computed attribute values. OmniGraph is not constrained by the data values in its definition. It can create entirely new values at runtime based on the computation algorithms in its nodes. A USD stage can contain several layers forming "opinions" on what its declared values should be, which are composed together to form the final result. OmniGraph only operates on the composed USD stage in general, although it is possible for special purpose nodes to access the USD layer data through the USD APIs. .. _omnigraph_fabric_sync: In order to store and manage data efficiently, OmniGraph uses a data storage component called *Fabric*, which is a part of Omniverse. After the USD stage is composed, USD prim data is read into *Fabric*, where it can be efficiently accessed by OmniGraph for its computations. When appropriate, OmniGraph directs *Fabric* to synchronize with USD and the computed data becomes available to the USD stage. .. mermaid:: sequenceDiagram autonumber USD->>Fabric: Populate Node Data loop Computation Fabric->>OmniGraph: Read Data For Computation OmniGraph->>Fabric: Update With Results Of Computation end Fabric-->>USD: Sync Computed Data The nature of the computation being performed by OmniGraph will determine the interval for syncing computed data back to USD. If, for example, the graph is deforming a mesh for passing on to some external stress analysis software then the resulting mesh must be synced to USD on each playback frame so that each version of the deformed mesh is available for analysis. On the other hand if the graph is performing a large set of Machine Learning calculations for the purposes of training a model then it only needs to send the results back to USD when the training is complete and the resulting model needs to be stored. .. important:: While some nodes within OmniGraph access USD data, and most have a direct correspondence with a USD prim, neither of these is required for OmniGraph to work properly. If an OmniGraph node is only required temporarily to perform some intermediate calculation, for example, it might only be known to *Fabric* and never appear in the USD stage. .. note:: To avoid awkward wording the generic term "graph" will be used herein when discussing the component of the OmniGraph subsystem that represents a graph to be evaluated. OmniGraph as a whole comprises the collection of components required to perform runtime evaluation (graphs, evaluators, schedulers) and their interaction. How The Graph Appears In USD **************************** We'll start with a simple example of how a graph looks in the USD Ascii format and the progressively fill in the details of exactly what each part of it represents. The graph will contain two nodes connected together to perform the two-part computation of multiplying a value by four using two nodes whose computation multiplies a value by two. .. code-block:: usd def OmniGraph "Graph" { token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageOnDemand" def OmniGraphNode "times_2_node_1" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 2.5 custom double outputs:two_a = 5.0 } def OmniGraphNode "times_2_node_2" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 0.0 custom double inputs:a.connect = </Graph/times_2_node_1.outputs:two_a> custom double outputs:two_a = 10.0 } } The Graph ========= The graph itself is the top level USD prim of type **OmniGraph**. It serves to define the parameters of the graph definition in its attribute values, and as a scope for all of the nodes that are contained within the graph. .. important:: Nodes must all be contained within the scope of an **OmniGraph** prim, and no prims that are not of type **OmniGraph** or **OmniGraphNode** are allowed within that scope. .. code-block:: usd :emphasize-lines: 3-6 def OmniGraph "Graph" { token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageOnDemand" def OmniGraphNode "times_2_node_1" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 2.5 custom double outputs:two_a = 5.0 } def OmniGraphNode "times_2_node_2" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 0.0 custom double inputs:a.connect = </Graph/times_2_node_1.outputs:two_a> custom double outputs:two_a = 10.0 } } .. mermaid:: classDiagram class Graph Graph: token evaluator.type Graph: token fabricCacheBacking Graph: int2 fileFormatVersion Graph: token pipelineStage The predefined attributes in the OmniGraph prim come from the OmniGraph prim schema, generated using the standard `USD Schema Definition API <https://graphics.pixar.com/usd/release/tut_generating_new_schema.html>`_. This is the generated schema definition. .. code-block:: usd class OmniGraph "OmniGraph" ( doc = "Base class for OmniGraph primitives containing the graph settings." ) { token evaluationMode = "Automatic" ( allowedTokens = ["Automatic", "Standalone", "Instanced"] doc = """Token that describes under what circumstances the graph should be evaluated. \r Automatic mode will evaluate the graph in Standalone mode when \r no Prims having a relationship to it exist. Otherwise it will be \r evaluated in Instanced mode.\r Standalone mode evaluates the graph with itself as the graph\r target, and ignores any Prims having relationships to the graph Prim. \r Use this mode with graphs that are expected to run only once per frame\r and use explicit paths to Prims on the stage. \r Instanced graphs will only evaluate the graph when it is part of a \r relationship from an OmniGraphAPI interface. Each Prim with a \r relationship to the graph will cause a unique evaluation with the \r graph target set to the path of the Prim having the relationship. \r Use this mode when the graph represents an asset or template, and \r parameterizes Prim paths through the use of the GraphTarget node,\r variables, or similar mechanisms. """ ) token evaluator:type = "push" ( allowedTokens = ["dirty_push", "push", "pull", "execution", "execution_pull"] doc = "Type name for the evaluator used by the graph." ) token fabricCacheBacking = "Shared" ( allowedTokens = ["Shared", "StageWithHistory", "StageWithoutHistory"] doc = "Token that identifies the type of FabricCache backing used by the graph." ) int2 fileFormatVersion ( doc = """A pair of integers consisting of the major and minor versions of the\r file format under which the graph was saved.""" ) token pipelineStage = "pipelineStageSimulation" ( allowedTokens = ["pipelineStageSimulation", "pipelineStagePreRender", "pipelineStagePostRender", "pipelineStageOnDemand"] doc = """Optional token which is used to indicate the role of a vector\r valued field. This can drive the data type in which fields\r are made available in a renderer or whether the vector values\r are to be transformed.""" ) } .. note:: This schema is still in development and will most likely change in the upcoming releases. The Nodes ========= A graph is more than just a graph prim on its own. Within its scope are an interconnected set of nodes with attribute values that are a visual representation of the computation algorithm of the graph. Each of these nodes are represented in USD as prims with the schema type **OmniGraphNode**. .. code-block:: usd :emphasize-lines: 8-14,16-23 def OmniGraph "Graph" { token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageOnDemand" def OmniGraphNode "times_2_node_1" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 2.5 custom double outputs:two_a = 5.0 } def OmniGraphNode "times_2_node_2" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 0.0 custom double inputs:a.connect = </Graph/times_2_node_1.outputs:two_a> custom double outputs:two_a = 10.0 } } .. mermaid:: flowchart LR subgraph Graph times_2_node_1 --> times_2_node_2 end The predefined attributes in the **OmniGraphNode** prim come from the **OmniGraphNode** prim schema, also defined through the `USD Schema Definition API <https://graphics.pixar.com/usd/release/tut_generating_new_schema.html>`_. This is the generated schema for the node's prim type. .. code-block:: usd class OmniGraphNode "OmniGraphNode" ( doc = "Base class for OmniGraph nodes." ) { token node:type ( doc = "Unique identifier for the name of the registered type for this node." ) int node:typeVersion ( doc = """Each node type is versioned for enabling backward compatibility. This value indicates which version of\r the node type definition was used to create this node. By convention the version numbers start at 1.""" ) } Connections =========== Although OmniGraph connections between attributes are implemented and handled directly within OmniGraph they are published within USD as *UsdAttribute* connections. Imagine a "Times2" node with one input and one output whose value is computed as the input multiplied by two. Then you can connect two of these in a row to multiple the original input by four. In USD this would look like: .. code-block:: usd :emphasize-lines: 13,20-22 def OmniGraph "Graph" { token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageOnDemand" def OmniGraphNode "times_2_node_1" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 2.5 custom double outputs:two_a = 5.0 } def OmniGraphNode "times_2_node_2" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 0.0 custom double inputs:a.connect = </Graph/times_2_node_1.outputs:two_a> custom double outputs:two_a = 10.0 } } .. mermaid:: flowchart LR subgraph Graph times_2_node_1 --> times_2_node_2 end One thing worth mentioning here - in the second node */Graph/times_2_node_2* the value at *inputs:a* defines a value of 0.0, which is used in the event that a connection is not authored, or the connection is not evaluated (for example: outside an OmniGraph context), or an invalid connection is authored for the attribute. Where a valid connection is authored, it will take precedence during OmniGraph evaluation. In this example this is seen by the computation using the connected value of *5.0* as the multiplicand, not the authored value of *0.0*. Graph Extras ============ The graph evaluation type is a hint to OmniGraph on how a set of nodes should be evaluated. One of the more common variations is the type *execution*, which is usually referred to as an :ref:`Action Graph<ogn_omni_graph_action_overview>`. .. code-block:: usd :emphasize-lines: 3,9,14-16 def OmniGraph "ActionGraph" { token evaluator:type = "execution" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageOnDemand" def OmniGraphNode "DoNothingNode" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { token node:type = "omni.graph.nodes.Noop" int node:typeVersion = 1 uint inputs:execIn = 0 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-196.9863, 332.03223) } } .. mermaid:: flowchart LR subgraph ActionGraph DoNothingNode end The key differentiator of an :ref:`Action Graph<ogn_omni_graph_action_overview>` is its use of :ref:`execution attributes<omnigraph_usd_execution_attributes>` to trigger evaluation, rather than some external event such as the update of a USD stage. The additional two **ui:nodegraph** attributes shown in this example illustrate how extra information can be added to the node and be stored with the prim definition. In this case the Action Graph editor has added the information indicating the node's position and expansion state so that when the file is reloaded and the editor is opened the node will appear in the same location it was last edited. The node graph editor has added the API schema *NodeGraphNodeAPI* to help it in interpreting the extra data it has added. This is a standard Pixar USD schema that you can read more about in the `USD documentation <https://graphics.pixar.com/usd/dev/api/class_usd_shade_node_graph.html>`_. Custom Attributes ================= Every node type can define its own set of custom attributes, specified using the :ref:`.ogn format<ogn_reference_guide>`. These custom attributes are what an OmniGraph node uses for its computation. Although the attributes are represented in USD, the actual values OmniGraph nodes use are stored in *Fabric*. These are the values that need to be synchronized by OmniGraph as mentioned :ref:`above<omnigraph_fabric_sync>`. For the most part, every USD attribute type has a corresponding .ogn attribute type, though some may have some different interpretations. The full :ref:`type correspondence<ogn_attribute_types>` shows how the types relate. Here is how the definition of our "multiply by two" node might look in .ogn format: .. code-block:: json { "Times2": { "version": 1, "description": "Multiplies a double value by 2.0", "inputs": { "a": { "type": "double", "description": "The number to be doubled" } }, "outputs": { "two_a": { "type": "double", "description": "The input multiplied by 2.0" } } } When the graph creates an instance of this node type then it will publish it in the equivalent USD format. The data that can be recreated from the node type definition (i.e. the descriptions in this case) do not get published into USD. .. code-block:: usd :emphasize-lines: 12-13,20-22 def OmniGraph "Graph" { token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageOnDemand" def OmniGraphNode "times_2_node_1" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 2.5 custom double outputs:two_a = 5.0 } def OmniGraphNode "times_2_node_2" { token node:type = "omni.graph.nodes.Times2" int node:typeVersion = 1 custom double inputs:a = 0.0 custom double inputs:a.connect = </Graph/times_2_node_1.outputs:two_a> custom double outputs:two_a = 10.0 } } A few points of interest in this output: - OmniGraph attributes are published as *custom* attributes - The value of *node:typeVersion* must match the *"version"* value specified in the .ogn file - The value of *node:type* is an extended version of the name key specified in the .ogn file, with the extension prepended - Input attributes are put into the namespace *inputs:* and output attributes are put into the namespace *outputs:* Special Attribute Types ======================= There are some .ogn attribute types that do not have a direct equivalent in USD. They are implemented using existing USD concepts, relying on OmniGraph to interpret them properly. .. _omnigraph_usd_execution_attributes: Execution Attributes -------------------- Attributes of type *execution* are used by Action Graphs to trigger evaluation based on events. They are stored in USD as unsigned integer values, with some custom data to indicate to OmniGraph that they are an execution type, not a plain old value. Here is an example of the builtin **OnTick** node which has one such input. .. code-block:: usd :emphasize-lines: 11-15 def OmniGraphNode "on_tick" { custom uint inputs:framePeriod = 0 custom bool inputs:onlyPlayback = 1 custom token node:type = "omni.graph.action.OnTick" custom int node:typeVersion = 1 custom double outputs:absoluteSimTime = 0 custom double outputs:deltaSeconds = 0 custom double outputs:frame = 0 custom bool outputs:isPlaying = 0 custom uint outputs:tick = 0 ( customData = { bool isExecution = 1 } ) custom double outputs:time = 0 custom double outputs:timeSinceStart = 0 } .. note:: With execution attributes only the outputs require the **customData** values. .. _omnigraph_usd_bundle_attributes: Bundle Attributes ----------------- A *bundle* attribute in OmniGraph is simply a collection of other attributes. They are published differently in USD depending on whether they are inputs or outputs. Input bundles cannot be specified directly; they take their attribute members from an input connection. For this reason an input bundle attribute is represented as a USD *rel* type. Output bundles are generated or passed along by the node's compute function, so they do not have a permanent representation. Instead, a placeholder child prim is added to the node's prim in USD for it to populate when computing. Here is an example of a graph with two nodes, with an import of a cube prim to use for the extraction. .. code-block:: usd :linenos: :emphasize-lines: 21-22,31-33,38,48,54-56 def Xform "World" { def Mesh "Cube" { double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) string comment = "The rest of the cube data omitted for brevity" } def OmniGraph "PushGraph" { token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "read_prim_into_bundle" { custom bool inputs:computeBoundingBox = 0 custom rel inputs:prim prepend rel inputs:prim = </World/Cube> custom token inputs:primPath = "" custom timecode inputs:usdTimecode = -1 custom bool inputs:usePath = 0 token node:type = "omni.graph.nodes.ReadPrimBundle" int node:typeVersion = 1 custom uint64 state:target = 0 custom timecode state:usdTimecode = -1 def Output "outputs_primBundle" { } } def OmniGraphNode "extract_bundle" { custom rel inputs:bundle = </World/PushGraph/read_prim_into_bundle/outputs_primBundle> token node:type = "omni.graph.nodes.ExtractBundle" int node:typeVersion = 1 custom int[] outputs:faceVertexCounts custom int[] outputs:faceVertexIndices custom normal3f[] outputs:normals custom point3f[] outputs:points custom float2[] outputs:primvars:st custom token outputs:sourcePrimPath = "" custom token outputs:subdivisionScheme = "" custom matrix4d outputs:worldMatrix = ( (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0) ) custom double3 outputs:xformOp:rotateXYZ = (0, 0, 0) custom double3 outputs:xformOp:scale = (0, 0, 0) custom double3 outputs:xformOp:translate = (0, 0, 0) custom token[] outputs:xformOpOrder def Output "outputs_passThrough" { } } } } .. mermaid:: flowchart LR /World/Cube subgraph /World/PushGraph read_prim_into_bundle --> extract_bundle end /World/Cube -.-> read_prim_into_bundle The interpretation of the five highlighted sections is: 1. The import node is given a relationship to the prim it will be importing 2. The bundle it is creating is given a placeholder child prim of type "Output" 3. The generated bundle is passed along to the extract_bundle node via a connection 4. The *worldMatrix* value was extracted from the bundle containing the cube's definition 5. The bundle being extracted is also presented as an output via the passThrough placeholder Extended Attributes ------------------- An extended attribute is one that can take on any number of different types when it is part of an OmniGraph. For example it might be a double, float, or int value. The exact type will be determined by OmniGraph, either when a connection is made or a value is set. The actual attributes, however, are represented as token types in USD and it is only OmniGraph's interpretation that provides them with their "real" type. Here is an example of a node having its *inputs:floatOrToken* attribute type resolve to a *float* value at runtime since it has an incoming connection from a float type attribute. .. code-block:: usd :emphasize-lines: 12-15,18 def Xform "World" { def OmniGraph "ActionGraph" { token evaluator:type = "execution" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "tutorial_node_extended_attribute_types" { custom token inputs:flexible custom token inputs:floatOrToken custom token inputs:toNegate custom token inputs:tuple token node:type = "omni.graph.tutorials.ExtendedTypes" int node:typeVersion = 1 prepend token inputs:floatOrToken.connect = </World/ActionGraph/constant_float.inputs:value> custom token outputs:doubledResult custom token outputs:flexible custom token outputs:negatedResult custom token outputs:tuple } def OmniGraphNode "constant_float" { custom float inputs:value = 0 token node:type = "omni.graph.nodes.ConstantFloat" int node:typeVersion = 1 } } } .. mermaid:: flowchart LR subgraph /World/PushGraph constant_float --> tutorial_node_extended_attribute_types end .. _omnigraph_usd_path_attributes: Path Attributes --------------- The special OmniGraph attribute type *path* is used to represent USD paths, represented as token-type attributes in USD. To OmniGraph they are equivalent to an *Sdf.Path* that points to a prim or attribute that may or may not exist on the USD stage. When paths are modified, OmniGraph listens to the USD notices and attempts to fix up any path attributes that may have changed locations. To USD though they are simply strings and no updates are attempted when OmniGraph is not enabled and listening to the changes. See the attribute *inputs:primPath* in the example above for the representation of a path attribute in USD. Accessing USD Prims From Nodes ****************************** OmniGraph accesses USD scene data through special import and export nodes. Examples of each of these are the :ref:`ReadPrimBundle<GENERATED - Documentation _ognomni.graph.nodes.ReadPrimBundle>` node for importing a USD prim into an :ref:`OmniGraph bundle attribute<omnigraph_usd_bundle_attributes>` and a corresponding :ref:`WritePrim<GENERATED - Documentation _ognomni.graph.nodes.WritePrim>` node for exporting a computed bundle of attributes back onto a USD prim. Both of these node types use the :ref:`path attribute<omnigraph_usd_path_attributes>` type to specify the location of the prim on the USD stage that they will access. Once the nodes are connected to the prim they are importing or exporting, usually via specifying the *SdfPath* to that prim on the USD stage, they can be used the same as any other OmniGraph node, passing the extracted USD data through the graph for computation. See :ref:`above<omnigraph_usd_bundle_attributes>` for a detailed example. The USD API *********** OmniGraph listens the USD change notices, so it is able to update values when the USD API is used to modify them, or by proxy when UI elements that use the USD API modify them. However this is not an efficient way to set values as the notification process can be slow so it is best to avoid this if possible. .. code-block:: python import omni.usd import omni.graph.core as og from pxr import Usd # Slow Method prim_node = omni.usd.get_context().get_stage().GetPrimAtPath("/World/ActionGraph/constant_float") attribute = prim_node.GetAttribute("inputs:value") attribute.Set(5.0) # Fast Method og.Controller("/World/ActionGraph/constant_float.inputs:value").set(5.0)
27,539
reStructuredText
40.854103
133
0.663931
omniverse-code/kit/exts/omni.graph.core/docs/README.md
# OmniGraph [omni.graph.core] OmniGraph is a graph system that provides a compute framework for Omniverse through the use of nodes and graphs. In time, this computational framework will form the foundation of many other subsystems in Omniverse. This extension contains the core functionality of the OmniGraph.
313
Markdown
51.333325
112
0.814696
omniverse-code/kit/exts/omni.graph.core/docs/naming_conventions.rst
.. _omnigraph_naming_conventions: OmniGraph Naming Conventions ---------------------------- The mandatory naming conventions are noted where applicable. The rest of these conventions have been set up to make it as easy as possible for you to write your own nodes, and to be able to read the nodes that others have written. File And Class Names ++++++++++++++++++++ Class and file naming is ``InterCaps`` with the prefix ``Ogn``. For example, *OgnMyNode.ogn*, *OgnYourNode.py*, *class OgnMyNode*, and *OgnHerNode.cpp*. As with regular writing, active phrasing (verb-noun) is preferred over passive phrasing when a node name refers to its function. +---------------------+--------------------+ | Weak | Preferred | +=====================+====================+ | OgnSumOfTwoValues | OgnAddTwoValues | +---------------------+--------------------+ | OgnAttributeRemoval | OgnRemoveAttribute | +---------------------+--------------------+ | OgnTextGenerator | OgnGenerateText | +---------------------+--------------------+ .. tip:: Some of the automated processes use the ``Ogn`` prefix to more quickly recognize node files. Using it helps them work at peak efficiency. Node Names ++++++++++ Although the only real restriction on node names is that they consist of alphanumeric, underscore, or dot characters there are some conventions established to make it easier to work with nodes, both familiar and unfamiliar. A node will generally have two names - a unique name to identify it to OmniGraph, and a user-friendly name for viewing in the UI. The name of the node should be generally related to the name of the class, to make them easy to find. The name will be made unique within the larger space by prepending the extension as a namespace. The name specified in the file only need be unique within its extension, and by convention is in uppercase ``CamelCase``, also known as ``PascalCase``. It's a good idea to keep your name related to the class name so that you can correlate the two easily. .. warning:: You can override the prepending of the extension name if you want your node name to be something different, but if you do, you must be prepared to ensure its uniqueness. To override the name simply put it in a namespace by including a `.` character, e.g. `omni.deformer.Visualizer`. Note that the `omni.` prefix is reserved for NVIDIA developed extensions. The user-friendly name can be anything, even an entire phrase, in ``Title Case``. Although any name is acceptable always keep in mind that your node name will appear in the user interface and its function should be immediately identifiable from its name. If you do not specify a user-friendly name then the unique name will be used in the user interface instead. Here are a few examples from the OmniGraph extensions: +----------------------+------------------------+-------------------------------------------+----------------------------------+ | Class Name | Name in the .ogn file | Unique Extended Name | User Facing Node Name | +======================+========================+===========================================+==================================+ | OgnTutorialTupleData | TupleData | omni.graph.tutorials.TupleData | Tutorial Node: Tuple Attributes | +----------------------+------------------------+-------------------------------------------+----------------------------------+ | OgnVersionedDeformer | VersionedDeformer | omni.graph.examples.cpp.VersionedDeformer | Example Node: Versioned Deformer | +----------------------+------------------------+-------------------------------------------+----------------------------------+ | OgnAdd | Add | omni.graph.nodes.Add | Add | +----------------------+------------------------+-------------------------------------------+----------------------------------+ .. attention:: The unique node name is restricted to the alphanumeric characters, underscore (``_``), and dot (``.``). Any other characters in the node name will cause the code generation to fail with an error message. Attribute Names +++++++++++++++ As you will learn, every node has a set of attributes which describe the data it requires to perform its operations. The attributes also have naming conventions. The mandatory part is that attributes may only contain alphanumeric characters, underscore, and optional colon-separated namespacing. The preferred naming for attributes is ``camelCase`` and, as with nodes, both a unique name and a user-friendly name may be specified where the user-friendly name has no real restrictions. Attributes have some predefined namespaces depending on their location with the node as well (`inputs:`, `outputs:`, and `state:`) so you can use this to have inputs and outputs with the same name since they will be in different namespaces. Here is an example of attribute names on a node that adds two values together: +-------------+------------------+ | Full Name | User Facing Name | +=============+==================+ | inputs:a | First Addend | +-------------+------------------+ | inputs:b | Second Addend | +-------------+------------------+ | outputs:sum | Sum Of Inputs | +-------------+------------------+ .. attention:: The unique attribute name is restricted to the alphanumeric characters, underscore (``_``), and colon (``:``). Any other characters in the attribute name will cause the code generation to fail with an error message. .. tip:: You will find that use of your node will be easier if you minimize the use of attribute namespaces. It has some implications in generated code due to the special meaning of the colon in C++ and Python.
5,871
reStructuredText
54.923809
128
0.592744
omniverse-code/kit/exts/omni.graph.core/docs/index.rst
.. include:: ../../../../_build/ogn/docs/substitutions.rst .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension Version**: |omni.graph.core.version|,**Documentation Generated**: |today| What is it, and why are we doing it? ************************************ Omniverse will be made up of many extensions - from animations, to physics, to inferencing algorithms with DNNs, to name just a few. In order for all these systems to interact with each other, we need a graph framework to "glue" it all together - not only those prebuilt components, but also provide a compute framework where clients can integrate their own functionality as well. The framework is to be flexible enough to address all of the above range of use cases, and more, as well as handling a large range of granularity of compute - from sub-millisecond warp level to hours long training of neural networks as some examples. OmniGraph Overview ****************** Current Capabilities ==================== Currently OmniGraph is being used to define deformer pipelines, in particle and fluid simulations, as part of Drivesim for some of its nodes, and to trigger runtime logic based on the receipt of events, though it will grow into more use cases in the future. At present OmniGraph is already capable of a variety of things, although it still is very much a work in progress. We are able to: - Write nodes in C++, Python, and Cuda - Writes scripts in Python using commands and the OmniGraph API that is bound to Python - Employ a code synthesizing framework (OGN) to substantially simplify the development process by generating boilerplate and hiding it away from the developer - Provide an efficient, and flexible data model. Efficient, because the data model is built on top of Fabric, which in short takes USD data and puts into a vectorized, compute friendly form, with the data available on both CPU and GPU. The data model is flexible, because we employ constructs like bundles, which allows an arbitrary amount of data to be passed from node to node, without having to be pre-declared. We also employ constructs like extended and dynamic attributes. Extended attributes allows data of any type to be connected to an attribute, and it resolves at runtime to the correct type. This allows nodes to be created without accounting for an combinatorial explosion of possible types. Dynamic attributes allow new attributes to be tacked onto the node instance at runtime. - Last, but certainly not least, OmniGraph is not a single type of graph. One can create any type of graph, with any semantics with OmniGraph. We do this by clearly separating graph description from graph evaluation. Three graphs are already supported: busy evaluation graph (push), Lazy evaluation graph (dirty_push), and event handling graph (action), with more to come. Ready To Start? *************** .. toctree:: :maxdepth: 1 :caption: Let's Go Through Some Tutorials :glob: Getting Started Tutorials<https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph.html> Node Writing Guides<nodes> Bird's eye view of the OmniGraph Architecture<architecture> Core Concepts<core_concepts> OmniGraph and USD<usd> File, Class, Node, and Attribute Naming Conventions<naming_conventions> Directory Structure<directory_structure> Python Documentation<../../omni.graph/docs/index.rst> How-To Guides<how_to> Versioning<versioning> Categories<categories> Administrative Details ********************** .. toctree:: :maxdepth: 1 :caption: Administrivia :glob: CHANGELOG Roadmap<roadmap> .. ifconfig:: build_name in ('internal') OmniGraph developers can access :ref:`Internal Documentation<omnigraph_internal_development>` for more information. OmniGraph Architectural Decision Log ************************************ OmniGraphs Architectural decisions are tracked and logged. .. toctree:: :maxdepth: 1 OmniGraph Architectural Decision Log<omnigraph_arch_decisions>
4,037
reStructuredText
47.650602
798
0.744365
omniverse-code/kit/exts/omni.graph.core/docs/usd_representations.rst
******************************** OmniGraph Representations in USD ******************************** Each of the components of an OmniGraph are represented using native USD elements for maximum compatibility. Sometimes extra data will be encoded in metadata or ancillary attributes where functionality is needed that isn't provided by standard USD. This page only describes the representation of the elements and values in USD. See the full documentation for more detailed descriptions of what they are and what they do. OmniGraph Graphs In USD ======================= All graphs in OmniGraph are represented as a prim, using the `OmniGraph` schema. The schema adds five standard attributes to all graph prims that describe the settings used for evaluation of that graph. :: def OmniGraph "MyGraph" { token evaluator:type int2 fileFormatVersion token flatCacheBacking token pipelineStage token evaluationMode } **evaluator:type** is the type name for the evaluator the graph uses to run its computation. Legal values for the built-in evaluators are *dirty_push*, *push*, *pull*, *execution*, and *execution_pull*. **fileFormatVersion** is a pair of integers consisting of the major and minor versions of the file format under which the graph was saved. This allows graphs to be processed for backward compatibility. **flatCacheBacking** identifies the type of FlatCache backing used by the graph for its evaluation data. Legal values are *Shared*, *StagedWithHistory*, and *StagedWithoutHistory*. **pipelineStage** is used to indicate the section of the orchestration graph in which this graph lives. Legal values are *pipelineStageSimulation*, *pipelineStagePreRender*, *pipelineStagePostRender*, and *pipelineStageOnDemand*. **evaluationMode** is used to indicate whether the graph should evaluate standalone, or only when instanced. Legal values are *Automatic*, *Standalone* and *Instanced* These graph prims can appear at any level in the prim hierarchy, including the root level. :: def OmniGraph "MyGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 2) token flatCacheBacking = "Shared" token pipelineStage = "piplineStageSimulation" } .. note:: The only type of prims that can appear as a child of the **OmniGraph** prim are described below. OmniGraph Nodes in USD ====================== OmniGraph nodes always appear as the child of an **OmniGraph** prim in USD since all OmniGraph nodes must be children of a specific OmniGraph. They are constructed using the **OmniGraphNode** schema. :: def OmniGraphNode "SimpleNode" { token node:type int node:typeVersion } **node:type** is the unique identifier for the name of the registered type of the node. **node:typeVersion** is the node type version number. Each node type is versioned for enabling backward compatibility. This value indicates which version of the node type definition was used to create this node. By convention the version numbers start at 1.
2,986
reStructuredText
37.294871
120
0.754856
omniverse-code/kit/exts/omni.graph.core/docs/decisions/adr-template.rst
:orphan: --- Template for problem with solution --- ########################################## * Status: {proposed | rejected | accepted | deprecated | … | superseded by LINK_TO_OTHER_ADR} (OPTIONAL) * Deciders: {list everyone involved in the decision} (OPTIONAL) * Date: {YYYY-MM-DD when the decision was last updated} (OPTIONAL) Technical Story: {description | ticket/issue URL} (OPTIONAL) Context and Problem Statement ============================== {Describe the context and problem statement, e.g., in free form using two to three sentences. You may want to articulate the problem in form of a question.} Decision Drivers (OPTIONAL) =========================== * {driver 1, e.g., a force, facing concern, …} * {driver 2, e.g., a force, facing concern, …} * {numbers of drivers can vary} Considered Options ================== * {option 1} * {option 2} * {option 3} * {numbers of options can vary} Decision Outcome ================ Chosen option: "{option 1}", because {justification. e.g., only option, which meets k.o. criterion decision driver | which resolves force {force} | … | comes out best (see below)}. Positive Consequences (OPTIONAL) -------------------------------- * {e.g., improvement of quality attribute satisfaction, follow-up decisions required, …} * … Negative Consequences (OPTIONAL) -------------------------------- * {e.g., compromising quality attribute, follow-up decisions required, …} * … Pros and Cons of the Options (OPTIONAL) ======================================= {option 1} ---------- .. {example | description | pointer to more information | …} (OPTIONAL) * Good, because {argument a} * Good, because {argument b} * Bad, because {argument c} * {numbers of pros and cons can vary} {option 2} ---------- .. {example | description | pointer to more information | …} (OPTIONAL) * Good, because {argument a} * Good, because {argument b} * Bad, because {argument c} * {numbers of pros and cons can vary} {option 3} ---------- .. {example | description | pointer to more information | …} (OPTIONAL) * Good, because {argument a} * Good, because {argument b} * Bad, because {argument c} * {numbers of pros and cons can vary} Links (OPTIONAL) ================ * {Link type} {Link to ADR} * {numbers of links can vary} .. <!-- example: Refined by [ADR-0005](0005-example.md) -->
2,350
reStructuredText
24.27957
180
0.611064
omniverse-code/kit/exts/omni.graph.core/docs/decisions/0002-python-api-exposure.rst
Deciding What To Expose As The Python API In OmniGraph ###################################################### * Status: proposed * Deciders: kpicott, OmniGraph devs * Date: 2022-07-07 Technical Story: `OM-46154 <https://nvidia-omniverse.atlassian.net/browse/OM-46154>`_ Context and Problem Statement ============================= Once the Python API definition was decided there was the further decision of exactly what should go into the public API, what should be internal, and what should be completely deprecated. Considered Options ================== 1. **The Wild West** - everything that was already exposed continues to be exposed in exactly the same way 2. **Complete Lockdown** - only what is strictly necessary for current functionality to work is exposed, everything else is made inaccessible to the user 3. **Graceful Deprecation** - we define what we want exposed and make those the *__all__* exposed symbols, but we also include all of the previously available symbols in the module itself. Soft deprecation warnings are put in for anything we want to eventually completely hide from the user. Decision Outcome ================ **Option 3**: the users get full compatibility without any code changes but we have drawn our line in the sand denoting exactly what we will be supporting in the future. The exposure of symbols will be broken into different categories depending on the exposure desired: 1. **Full Exposure** the module imports the symbol and its name is added to the module's *__all__* list 2. **Internal Exposure** the symbol is renamed to have a leading underscore and the module imports the symbol. The name of the symbol is not added to the module's *__all__* list 3. **Hidden Exposure** for symbols that should be internal but for which the work to rename was too involved for now, create a new exposure list called *_HIDDEN* in the same location where *__all__* is defined and but all of the symbols that should be made internal into that list. Eventually this list will be empty as symbols are renamed to reflect the fact that they are only internal to OmniGraph 4. **Soft Deprecation** for symbols we no longer want to support. Their import and/or definition will be moved to a module file with the current version number, e.g. *_1_11.py*. The deprecated symbols will be added to that module's *__all__* list and the module will be imported into the main module but not added to the main module's *__all__* list 5. **Hard Deprecation** for symbols that were deprecated before that can simply be deleted. The file from which they were imported is replaced by a file that is empty except for a single *raise DeprecationError* statement explaining what action the user has to take to replace the deprecated functionality To reduce the size of the largest modules, submodules will be created to segment by grouped functionality. For example, **omni.graph.autonode** will contain all of the AutoNode-specific functionality. Lastly, in order to support this model some reorganization of files will be necessary. In particular, anything that is not part of the public API should be moved to an *_impl* subdirectory with imports from it being adjusted to match. Pros and Cons of the Options ============================ Option 1 -------- * **Good** - work required to define the API is minimal as it is just what we have * **Bad** - with the existing structure it's difficult to ascertain exactly what the API is, and as a consequence it would be harder to maintain in the future * **Ugly** - the current surface is organic anarchy; continuing to support all of it would be a development drag Option 2 -------- * **Good** - with everything well defined we make a strong statement as to what we are claiming to support. * **Bad** - we would have to rely on tests to find any missing exports, and we know we don't have 100% coverage even within Kit * **Ugly** - we are already at the stage where we don't know for sure what users are using, and the testing matrix is not yet populated enough to give us any confidence we will find the problems so there as an almost certainty that we would end up breaking somebody's code Option 3 -------- * **Good** - users's are happy because they have no immediate work to do, and we are happy because we have defined exactly what we are claiming to support. Because it's a smaller subset we can write a compatibility test for future changes. * **Bad** - we will end up exposing some things we don't want to, simply because it's too difficult to remove in one step * **Ugly** - everything is still wide open and users are free to make use of anything in our system. Despite any warnings to the contrary `Hyrum's Law <https://abseil.io/resources/swe-book/html/ch01.html#hyrumapostrophes_law>`_ dictates that it will be used anyway.
4,831
reStructuredText
57.926829
127
0.742703
omniverse-code/kit/exts/omni.graph.core/docs/decisions/0003-extension-locations.rst
OmniGraph Extension Locations In The Repo ######################################### * Status: proposed * Deciders: kpicott, OmniGraph devs * Date: 2022-08-12 Technical Story: `OM-50040 <https://nvidia-omniverse.atlassian.net/browse/OM-50040>`_ Context and Problem Statement ============================= All of the OmniGraph extensions were developed directly within Kit. As they grow, and Kit grows, the development velocity of both the OmniGraph and the larger Kit team are negatively impacted. Kit builds have to wait for all of the OmniGraph extensions and tests to build, and OmniGraph has to wait for the entire Kit SDK to build. In addition the Kit team has expressed a desire to move to a thin model where only code necessary to run what they call "Kit core" should be in the Kit repo, and OmniGraph is not considered part of that. Considered Options ================== 1. **Status Quo** - we just leave all of the extensions we have inside Kit and continue to develop that way 2. **Single Downstream Replacement** - move all of the extensions downstream of `omni.graph.core` to an extensions repo, removing the existing extensions from Kit 3. **Multi Downstream Replacement** - move each of the extensions downstream of `omni.graph.core` to their own individual extensions repo, removing the existing extension from Kit 4. **Downstream Copy** - move all of the extensions downstream from `omni.graph.core` to their own repo, bumping their major version, but leave the existing extensions in Kit at the previous version and have them be dormant Decision Outcome ================ **Option 2**: Single Downstream Replacement. Although none of these solutions is perfect this one affords the best balance of controlling our own destiny and administration overhead. There will be some changes in developer workflow required to support it, especially in the short term when extensions are transitioned out, and in the medium term when we have to backport across repos, but in the long run the workflow gains will outweigh the extra efforts. Moving Extensions ----------------- It's not practical to move every extension out in a single step so we'll have to move them in small subgroups. The extension dependency diagram will guide us on the ordering required to move an extension out. Generally speaking an extension can be moved as soon as nothing in Kit has a direct dependency on it. The :ref:`extension dependency graph<omnigraph_extension_dependency_graph>` that was extracted from the full list of dependencies will guide this. Any extension without an incoming arrow can be moved, starting with `omni.graph.bundle.action`. Pros and Cons of the Options ============================ Option 1 -------- * **Good** - Workflow is simple, we just build and run Kit and there's no overhead in managing our published versions * **Bad** - Kit build continues to be slow for all concerned * **Ugly** - We can't independently version our extensions, Kit becomes increasingly more complex as we add more, our tests continue to be subject to instability due to unrelated Kit problems Option 2 -------- * **Good** - Kit builds and our builds both get way faster, we can version our extension set indpendently of Kit, our tests don't rely as much on how the Kit app behaves, just Kit core * **Bad** - Some developers have to work in multiple repos during the transition, resulting in a clunky workflow for testing changes. There's extra overhead in deciding which apps get which versions of our extensions. * **Ugly** - Backport integration becomes more difficult as previous versions of extensions are not in a related repo. Option 3 -------- * **Good** - We gain full control over extension versioning, builds are even smaller and faster than Option 2, more flexible set of Kit SDK versioning gives us a wider variety of cross-version testing * **Bad** - It becomes more difficult to build tests as typically they will rely on nodes in multiple extensions * **Ugly** - Multiple repos mean multiple copies of the build to handle, multiple packman packages to wrangle, and the overhead reduction we gained by moving out of Kit is lost to administrivia Option 4 -------- * **Good** - Backward compatibility is easier to maintain as there are full "frozen" copies of the extensions available with Kit while we move forward in the separate repo. * **Bad** - Same as Option 2, plus the Kit builds continue to be slow as they still build our frozen extensions * **Ugly** - Random test failures will still occur in our code even though we aren't touching it, bugs that arise from apps using specific versions of the Kit SDK have to be addressed in the "frozen" copies, and it becomes more difficult for apps like Create to choose the correct versions of our extensions.
4,807
reStructuredText
53.022471
120
0.750364
omniverse-code/kit/exts/omni.graph.core/docs/decisions/0001-python-api-definition.rst
Definition of Python API Surface In OmniGraph ############################################# * Status: proposed * Deciders: kpicott, OmniGraph devs * Date: 2022-06-24 Technical Story: `OM-46154 <https://nvidia-omniverse.atlassian.net/browse/OM-46154>`_ Context and Problem Statement ============================= Although the C++ ABI is stable and backwards compatible all of the Python code supplied by OmniGraph is, by the nature of the language, public by default. This is causing problems with compatibility as much of the exposed code is implementation detail that we wish to be able to change without affecting downstream customers. After a few iterations we have run into many cases of unintentional dependencies, which will only grow more frequent as adoption grows. Considered Options ================== 1. **The Wild West** - we leave everything exposed and let people use what they find useful. Behind the scenes we attempt to maintain as much compatibility as we can, with deprecation notices where we cannot. 2. **Complete Lockdown** - we ship our Python modules as pre-interpreted bytecode (*.pyc* files), and tailor our documentation to the specific code we wish to expose. 3. **PEP8 Play Nice** - we follow the `PEP8 Standard <https://peps.python.org/pep-0008/#public-and-internal-interfaces>`_ for defining public interfaces, where nothing is truly hidden but we do have a well-defined way of identifying the interfaces we intend to support through multiple versions. Decision Outcome ================ Option 3: it strikes a good balance of ease of development and ease of use. Pros and Cons of the Options ============================ Option 1 -------- * **Good** - development is simpler as we don't have to worry about how to format or organize most Python code * **Bad** - there is extra work involved in explicitly deprecating things that change, and since everything is visible the need for deprecation will be quite frequent. * **Ugly** - if everything is fair game then users will start to make use of things that we either want to change or get rid of, making evolution of the interfaces much more difficult than they need to be Option 2 -------- * **Good** - with everything well defined we make a strong statement as to what we are claiming to support. * **Bad** - the code is still introspectable at the interface level even if the details are not. This makes it more likely that a mismatch in the code and the description will cause unreconcilable user confusion. * **Ugly** - locking everything is inherently un-Pythonic and puts up artificial barriers to our primary goal in using Python, which is widespread adoption. The fact that the definitive documentation is outside of the code also contributes to those barriers. Option 3 -------- * **Good** - we get a good balance of both worlds. The retained introspection makes it easier for seasoned programmers to understand how things are working and the API conventions make it clear where things are not meant to be relied on in future versions. * **Bad** - there's a bit more work to follow the guidelines and not much automatic help in doing so. Internal developers have to be diligent in what they are exposing. * **Ugly** - everything is still wide open and users are free to make use of anything in our system. Despite any warnings to the contrary `Hyrum's Law <https://abseil.io/resources/swe-book/html/ch01.html#hyrumapostrophes_law>`_ dictates that it will be used anyway.
3,497
reStructuredText
51.208954
121
0.740635
omniverse-code/kit/exts/omni.graph.core/docs/decisions/0000-use-markdown-any-decision-records.rst
Use Markdown Any Decision Records ################################# Context and Problem Statement ============================= We want to record any decisions made in this project independent whether decisions concern the architecture ("architectural decision record"), the code, or other fields. Which format and structure should these records follow? Considered Options ================== * `MADR <https://adr.github.io/madr/>`_ 3.0.0 – The Markdown Any Decision Records * Google Documents * Confluence Decision Outcome ================ Chosen option: "MADR 3.0.0", because * Implicit assumptions should be made explicit. Design documentation is important to enable people understanding the decisions later on. See also `A rational design process: How and why to fake it <https://doi.org/10.1109/TSE.1986.6312940>`_. * MADR allows for structured capturing of any decision. * The MADR format is lean and fits our development style. * The MADR structure is comprehensible and facilitates usage & maintenance. * The MADR project is vivid. * Google docs are not easily discoverable. * We already spend too much time explaining past decisions.
1,153
reStructuredText
36.225805
169
0.717259
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning_usd.rst
.. _omnigraph_versioning_usd: OmniGraph USD Versioning ######################## This type of versioning involves changes to the structure or content of the USD backing for OmniGraph. It should happen rarely. Two examples of changes of this type are the withdrawal of support for the global implicit graph, and the move from using plain prims to back the OmniGraph elements to using schema-based prims. In both cases the ABI remains unchanged, only the contents of the USD backing changed. This deprecation follows a three-step process to give users ample opportunity to modify any code they need to in order to support the new version that follows the standard :ref:`omnigraph_deprecation_approach`. .. hint:: Using the deprecation process ensures that each step only involves a minor version bump to the extension as existing code will continue to work. In the final phase of removal of the original behavior a major version bump may be required as existing scripts may not function without modification. Step 1 - Introduce A Deprecation Setting **************************************** For anything but the most trivial change there is always the possibility of existing code relying on the old way of doing things so the first step is to introduce a deprecation setting using the instructions in :ref:`omnigraph_versioning_settings`. Step 2 - Add In Automatic File Migration **************************************** Changes to the file format require a bump of the file format version, which can be found in the C++ file `omni.graph.core/plugins/Graph.cpp` in a line that looks like this: .. code-block:: cpp FileFormatVersion s_currentFileFormatVersion = { 1, 4 }; The first number is the major version, the second is the minor version, following the :ref:`omnigraph_semantic_versioning` guidelines. A major version bump is reserved for any changes that are incapable of having an automatic upgrade performed - e.g. adding mandatory metadata that identifies the time the file was created. Next step is to introduce some code that will take the USD structure in the previous file formats, going as far back as is reasonable, and modify it to conform to the desired new structure. Any USD-based modifications can be made at this point so it is quite flexible. One good way of doing this is to register a callback on a file format version update in the extension startup code, remembering to unregister it when the extension shuts down. .. literalinclude:: ../../../../../source/extensions/omni.graph/python/_impl/extension.py :language: python :start-after: begin-file-format-update :end-before: end-file-format-update The callback should be placed somewhere that indicates it is on a deprecation path. For the **useSchemaPrims** deprecation, for example, the deprecation code was added to a special directory `omni.graph/python/_impl/v1_5_0/` that contains code deprecated after version 1.5.0 of that extension. The callback code should check the version of the file being read and check it against the version that requires deprecation. Once you've found that the file format is one that would require conversion then issue a deprecation warning, and if the setting is configured to the new path then perform the conversion. .. code-block:: python :emphasize-lines: 15,21 def cb_for_my_deprecation( old_version: Optional[og.FileFormatVersion], new_version: Optional[og.FileFormatVersion], graph: Optional[og.Graph] ): if old_version is not None and\ (old_version.majorVersion > VERSION_BEFORE_MY_CHANGE.majorVersion or\ (old_version.majorVersion == VERSION_BEFORE_MY_CHANGE.majorVersion and\ old_version.minorVersion > VERSION_BEFORE_MY_CHANGE.minorVersion)): # No conversion needed, the file format is updated return # If the setting to automatically migrate is not on then there is nothing to do here carb.log_warn(f"Old format {old_version} automatically migrating to {new_version}") # If the setting to automatically migrate is not on then there is nothing to do here if not og.Settings().(og.Settings.MY_SETTING_NAME): return update_the_scene() Step 3 - Enable The New Code Path By Default ******************************************** Once the deprecation time has been reached then modify the default value of the setting in `omni.graph.core/plugins/OmniGraphSettings.cpp` and announce that the deprecation is happening. Step 4 - Remove The Old Code Path ********************************* In the rare case where full removal is required then you can remove the support code for the old code path. - Delete the deprecation setting - Delete all code paths that only execute when the setting is configured to use the deprecated code path - Change the file format conversion callback to issue and error and fail - Bump the major version of the file format to indicate older ones are no longer compatible USD Version Effects On Python Scripting *************************************** The automatic file migration provides a flexible upgrade path to making old files use the new way of doing things, however there may still be incompatibilities lurking in the Python files. Simple examples include scripts that assume the existence of deprecated prim types or attributes, or files containing script nodes that do the same. The only way to handle these is to ensure that you have good test coverage so that when the default value of the setting is reversed the test will fail and can be fixed.
5,621
reStructuredText
50.10909
120
0.736702
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning_extensions.rst
.. _omnigraph_versioning_extensions: Versioning OmniGraph Extensions ############################### The version numbers used by our extensions will follow the :ref:`omnigraph_semantic_versioning` model. Updates to the version numbers will occur in every MR that modifies the extension. This will entail two changes. The first is an update to the *config/extension.toml* file with the appropriate portion of the semantic version updated. The second is an update to the *docs/CHANGELOG.md* file with a description of the changes that appear in that update. For example if a new node was added to the `omni.graph.nodes` extension then it's *extension.toml* file would change this section: .. code-block:: toml [package] title = "OmniGraph Nodes" version = "1.23.8" to this, as an addition is a MINOR version change: .. code-block:: toml :emphasize-lines: 3 [package] title = "OmniGraph Nodes" version = "1.24.0" And these lines would be added at the top of the *CHANGELOG.md*: .. code-block:: md ## [1.24.0] - 2112-03-04 ### Added - Added the node type "Rush" Inter-Extension Versions ************************ For now all of the extensions that live inside of Kit will always be set to use the "latest" version, so in an `extension.toml` file they will appear like this: .. code-block:: toml [dependencies] "omni.graph" = {} "omni.graph.scriptnode" = {} "omni.graph.tools" = {} Extensions that live downstream of the Kit repo will be versioned explicitly. For example in the `kit-extensions/kit-graphs` repo there is the extension *omni.graph.window.action* whose .toml includes this, where the version of dependent extensions are explicit. .. code-block:: toml [dependencies] "omni.graph.window.core" = {version="1.16"} "omni.graph.ui" = {version="1.5"}
1,839
reStructuredText
30.18644
117
0.695487
omniverse-code/kit/exts/omni.graph.core/docs/internal/deprecation.rst
.. _omnigraph_deprecation: OmniGraph Code Deprecation ========================== This is a guide to the deprecation of Python classes, functions, and objects to support backward compatibility. C++ deprecation is left to the ABI functions. Before You Deprecate -------------------- Unlike C++, Python is totally transparent to the user. At least it is in the way in which we are currently using it. That means there is no fixed ABI that you can safely code to, knowing that all incompatible changes will be localized to that set of functions. In order to mitigate this, it is a best practice to provide a published Python API through explicit imports in your main module's `__init__.py` file. Then you can make a statement that only things that appear at the top level of that module are guaranteed to remain compatible through minor and patch version changes. Here's a sample directory structure that allows hiding of the implementation details in a Pythonic way, using a leading underscore to hint that the contents are not meant to be visible. .. code-block:: text omni.my.extension/ python/ __init__.py _impl/ MyClass.py my_function.py Then inside the `__init__.py` file you might see something like this: .. code-block:: python """Interface for the omni.my.extension module. Only components explicitly imported through this file are to be considered part of the API, guaranteed to remain backwardly compatible through all minor and patch version changes. Recommended import usage is as follows: .. code-block:: python import omni.my.extension as ome ome.my_function() """ from ._impl/my_function import my_function from ._impl/MyClass import MyClass A good documentation approach is still being worked out. For now using docstrings in your functions, modules, and classes will suffice. .. warning:: By default Git will ignore anything starting with an underscore, so you might have to add a .gitignore file in the `python/` directory containing something like this: # Although directories starting with _ are globally ignored, this one is intentional, # to follow the Python convention of internal implementation details starting with underscore !_impl/ When To Deprecate ----------------- Now that an API is established the deprecation choice can be limited to times when that API must be changed. Python code is very flexible so very large changes can be made without losing existing functionality. Examples of such changes are: - Adding new methods to classes - Adding new parameters to existing class methods, if they have default values and appear last in the parameter list - Adding new functions - Adding new parameters to existing class methods, if they have default values and appear last in the parameter list - Adding new constant objects Each of these changes would be considered additional functionality, requiring a bump to the minor version of the extension. Each of these changes could also be done by wholesale deprecation of the entity in question, with a replacement that uses a new name using the `Deprecation Process` below. Some changes require full deprecation of the existing functionality due to potential incompatibility. Examples of such changes are: - Removing a parameter from a class method or function - Deleting a class method, function, or object - Renaming an object - Changing an implementation - An ABI function with a Python binding has been deprecated Deprecation Process ------------------- Deprecation In Place ++++++++++++++++++++ The first line of defence for easy deprecation when adding new features to existing code is to provide defaults that replicate existing functionality. For example, let's say you have this function that adds two integers together: .. code-block:: python def add(value_1: int, value_2: int) -> int: return value1 + value_2 New functionality is added that lets you add three numbers. Rather than creating a new function you can use the existing one, adding a default third parameter: .. code-block:: python def add(value_1: int, value_2: int, value_3: int = 0) -> int: return value1 + value_2 + value_3 The key feature here is that all code written against the original API will continue to function without changes. You can be creative about how you do this as well. You can instead use flexible arguments to add an arbitrary number of values: .. code-block:: python def add(value_1: int, value_2: int, *args) -> int: return value1 + value_2 + sum(args) Or you can use the typing system to generalize the function (assuming you are not using static type checkers): .. code-block:: python def add(value_1: Union[int, float], value_2: Union[int, float]) -> Union[int, float]: return value1 + value_2 Or even allow different object types to use the same pattern: .. code-block:: python Add_t = Union[int, Tuple[float, float]] def add(value_1: Add_t, value_2: Add_t) -> Add_t: if isinstance(value_1, tuple): if isinstance(value_2, tuple): return value_1 + value_2 else: return value_1 + tuple([value_2] * len(value_1)) else: if isinstance(value_2, tuple): return value_2 + tuple([value_1] * len(value_2) else: return value_1 + value_2 .. tip:: A good deprecation strategy prevents the remaining code from becoming overly complex. If you start to see the parameter type checking code outweigh the actual functioning code it's time to think about deprecating the original function and introducing a new one. Deprecation By Renaming +++++++++++++++++++++++ If you really do need incompatible features then you can make your new function the primary interface and relegate the old one to the deprecated section. One easy way to do this is to create a new subdirectory that contains all of the deprecated functionality. This makes it both easy to find and easy to eliminate once a few releases have passed and you can no longer support it. For example if you want to create completely new versions of your class and function you can modify the directory structure to look like this: .. code-block:: text omni.my.extension/ python/ __init__.py _impl/ MyNewClass.py my_new_function.py v_1/ MyClass.py my_function.py Then inside the `__init__.py` file you might see something like this: .. code-block:: python """Interface for the omni.my.extension module. Only components explicitly imported through this file are to be considered part of the API, guaranteed to remain backwardly compatible through all minor and patch version changes. Recommended import usage is as follows: .. code-block:: python import omni.my.extension as ome ome.my_new_function() """ from ._impl/my_new_function import my_new_function from ._impl/MyNewClass import MyNewClass r"""Deprecated - everything below here is deprecated as of version 1.1. _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ """ from .impl.v_1.my_functon import my_function from .impl.v_1.MyClass import MyClass Now, as before, existing code continues to work as it is still calling the old code which it accesses with the same imported module, however the new versions are clearly marked as the main API. So what happens if the user is using the deprecated versions? With just this change they remain blissfuly unaware that progress has happened. Instead we would prefer if they were notified so that they have a chance to upgrade their code to take advantage of new features and avoid the shortcomings of the old ones. To this end some decorators can be used to provide some messaging to the user when they are using deprecated features. Deprecation Messaging --------------------- Messaging can be added in deprecation situations by using one of the functions and decorators that support it. All deprecation functions can be accessed from the top `omni.graph.tools` module level. The :py:class:`omni.graph.tools.DeprecateMessage` class provides a simple way of logging a message that will only show up once per session. .. literalinclude:: ../../../../../source/extensions/omni.graph.tools/python/_impl/deprecate.py :language: python :start-after: begin-deprecate-message :end-before: end-deprecate-message The :py:class:`omni.graph.tools.DeprecateClass` decorator provides a method to emit a deprecation message when the deprecated class is accessed. .. literalinclude:: ../../../../../source/extensions/omni.graph.tools/python/_impl/deprecate.py :language: python :start-after: begin-deprecated-class :end-before: end-deprecated-class The :py:class:`omni.graph.tools.RenamedClass` decorator is a slightly more sophisticated method of deprecating a class when the deprecation is simply a name change. .. literalinclude:: ../../../../../source/extensions/omni.graph.tools/python/_impl/deprecate.py :language: python :start-after: begin-renamed-class :end-before: end-renamed-class The :py:func:`omni.graph.tools.deprecated_function` decorator provides a method to emit a deprecation message when the old function is called. .. literalinclude:: ../../../../../source/extensions/omni.graph.tools/python/_impl/deprecate.py :language: python :start-after: begin-deprecated-function :end-before: end-deprecated-function The :py:func:`omni.graph.tools.DeprecatedImport` decorator provides a method to emit a deprecation message when an entire deprecated file is imported for use. This should not be used for imports that will be included in the API for backward compatibility, nor should these files be moved as they must continue to exist at the same import location in order to remain compatible. .. literalinclude:: ../../../../../source/extensions/omni.graph.tools/python/_impl/deprecate.py :language: python :start-after: begin-deprecated-import :end-before: end-deprecated-import The :py:func:`omni.graph.core.Attribute.is_deprecated` method provides a way to determine if an attribute has been deprecated, and :py:func:`omni.graph.core.Attribute.deprecation_message` returns the associated text from the .ogn file. For The Future -------------- If deprecations become too difficult to manage a more structured approach can be implemented. This would involve using a namespaced versioning for a module so that you can import a more precise version to maintain compatibility. For example, the directory structure might be arranged as follows to support version 1 and version 2 of a module: .. code-block:: text omni.my.extension/ python/ __init__.py v1.py v2.py _impl/ v1/ MyClass.py my_function.py v1/ MyClass.py my_function.py With this structure the imports can be selectively added to the top level files to make explicit versioning decisions for the available APIs. .. code-block:: python import omni.graph.tools as og # Always use the latest version of the interfaces, potentially breaking on upgrade import omni.graph.tools.v1 as og # Lock yourself to version 1, requiring explicit change to upgrade import omni.graph.tools.v2 as og # Lock yourself to version 2, requiring explicit change to upgrade The main files might contain something like this to support that import structure: .. code-block:: python # __init__.py from .v1 import * # v1.py from ._impl/v1/MyClass import MyClass from ._impl/v1/my_function import my_function # v2.py from ._impl/v2/MyClass import MyClass from ._impl/v2/my_function import my_function You can see how version selection redirects you to the matching versions of the classes and functions without any renaming necessary. The deprecation messaging can then be applied to older versions as before. It might also be desirable to apply versioning information to class implementations so that their version can be checked in a standard way where it is important. .. code-block:: python @version(1) @deprecated("Use omni.graph.tools.v2.MyClass instead") class MyClass: pass More sophisticated mechanisms could provide version conversions as well, so that you can always get a certain version of a class if you require it, even if it was created using the old API by providing a function with a standard name: .. code-block:: python @version(1) @deprecated("Use omni.graph.tools.v2.MyClass instead") class MyClass: @classmethod @version_compatibility(1) def upgrade_version(cls, old_version) -> MyClass: return MyClass(old_version.parameters)
13,499
reStructuredText
39.178571
123
0.691681
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning_nodes.rst
.. _omnigraph_versioning_nodes: Node Type Versioning #################### Although it will probably not happen too frequently, the implementation of node types will occasionally change in such a way that makes them incompatible with existing uses. In extreme cases the best course of action might be to create an entirely new node type with the new functionality. For less intrusive changes these are the types of modifications for which OmniGraph supports backward compatibility. - :ref:`omnigraph_versioning_nodes_abi` - :ref:`omnigraph_versioning_nodes_renaming` - :ref:`omnigraph_versioning_nodes_removing` - :ref:`omnigraph_versioning_nodes_modifying` - :ref:`omnigraph_versioning_nodes_collisions` .. hint:: Most node type version changes will result in a corresponding minor version bump of the extension in which they live. .. _omnigraph_versioning_nodes_abi: ABI Versioning ************** ABI versioning for node types should follow the basic Carbonite guidelines. `INodeType` is a Carbonite interface, so its backward compatibiliy is assured by following the update guidelines for it described in :ref:`omnigraph_versioning_carbonite`. .. _omnigraph_versioning_nodes_renaming: Renaming A Node Type ******************** From time to time users may wish to change the name of their node without changing the node itself, perhaps because they came across a better name, to fix a misspelling, or to prevent conflicts with an existing name. The functionality to do this is currently hardcoded in the Node.cpp file but should be surfaced to the ABI. Here’s a potential addition to the INodeType interface to make it happen: .. code-block:: cpp /** * Create an alternate name for a node type, most often used to support renaming a node type. * When the node type is deregistered the alternate name will be automatically removed as well. * * @param[in] alternateName Secondary name that can be used interchangeably with nodeTypeName * @param[in] nodeTypeName Name of the node type for which an alternate is to be created * @return True if the alternate name was successfully set up, false if the node type name could * not be found or the alternateName was already in use (both issue a warning) */ bool(CARB_ABI* createNodeTypeAlias)(char const* alternateName, char const* nodeTypeName); The alternate name(s) will be specified in the .ogn file so that the node definition can control them directly. .. code-block:: json { "MySpiffyNode": { "$comment": "...other stuff...", "alias": "MySpifyNode" } } .. warning:: This feature is not yet implemented. Move to user-side documentation once it is. .. _omnigraph_versioning_nodes_removing: Removing A Node Type ******************** From time to time a user may wish to withdraw support for a node, perhaps because they have a more functional replacement, or the function it provided is no longer relevant. Support will be added to support our soft deprecation path whereby the node first starts issuing deprecation warnings when it is instantiated and then later will be removed entirely. The second phase just involves deletion of the node from the extension, which still retains some measure of backward compatibility as the user can always enable an earlier version of the extension to bring it back. The first phase will be supported in a standard way with this ABI function on INodeType: .. code-block:: cpp /** * Mark a node type as being deprecated with a message for the user on action they should take. * * @param[in] nodeObj Node to which this function applies * @param[in] deprecationMsg Message to the user describing what to do before the deprecation happens */ void(CARB_ABI* deprecate)(NodeObj& nodeObj, char const* deprecationMsg); /** * Return the deprecation message for an node. * * @param[in] nodeObj node to which this function applies * @return String containing the node deprecation message (nullptr if the node is not deprecated) */ char const*(CARB_ABI* deprecationMessage)(NodeObj const& nodeObj); The soft deprecation is enabled through a new .ogn keyword: .. code-block:: json { "MySpiffyNode": { "$comment": "...other stuff...", "deprecate": "This node will be removed in the next release" } } .. warning:: This feature is not yet implemented. Move to user-side documentation once it is. .. _omnigraph_versioning_nodes_modifying: Modifying Attributes ******************** Currently the `updateNodeVersion` method can be overridden on the node type implementation to support arbitrary changes to attributes or internal node state, however it happens after the node initialization and therefore cannot support things like moving connections. We've already seen several examples of desired upgrades, including the ability to have a soft deprecation where old attributes remain in place, so this mechanism needs to be extended to be more robust. The changes to a node type that we will have a built-in upgrade path for are: - Renaming an attribute - Soft deprecation of an attribute Things that are not planned to be handled directly include: - Removal of an attribute - Replacement of an attribute with another attribute or attributes .. _omnigraph_renaming_attributes: Renaming Attributes =================== Renaming an attribute can only be done if the attribute keeps all of the defining properties and only the name changes. This includes the port type, data type, default value, and memory type. The metadata, such as UI name, hidden state, etc. can be changed if required without affecting the attribute renaming. This is what the attribute renaming would look like in the .ogn file, where an input named "x" changes its name to "red". .. code-block:: json :caption: Before the renaming { "MyNode": { "version": 1, "description": "This is my node", "inputs": { "x": { "type": "float", "description": "The first value", "uiName": "First Value" } } } } .. code-block:: json :caption: After the renaming :emphasize-lines: 3,7,9,10 { "MyNode": { "version": 2, "description": "This is my node", "inputs": { "red": { "oldName": ["x", 1], "type": "float", "description": "The red value", "uiName": "Red Value" } } } } The **oldName** keyword takes a pair of values consisting of the old attribute name and the last node version before it was renamed. There can be multiple pairs on the off chance that you rename the same attribute more than once. Notice how the node type version number was incremented as well, to tell OmniGraph that this implementation is different from the previous version. In order to support this there must be an addition to the `IAttribute` interface in the ABI that can remember this information for processing. This is what it might look like: .. code-block:: cpp /** * Define an old name by which an attribute was known. * * @param[in] attributeObj Attribute to which this function applies * @param[in] oldName Old name by which the attribute was known * @param[in] lastVersion Last node type version in which the old name was valid */ void(CARB_ABI* renamedFrom)(AttributeObj& attributeObj, char const* oldName, int lastVersion); .. warning:: This feature is not yet implemented. Move to user-side documentation once it is. Soft Deprecation Of Attributes ============================== In order to respect our :ref:`omnigraph_soft_deprecation`, when an attribute is to be removed it must be flagged as deprecated in its .ogn file, along with a message telling users what they must do to prepare for the loss of the attribute, if possible. The node type version does not yet need to be bumped as nothing has really changed for it at this point. .. code-block:: json :emphasize-lines: 3,7,9,10 { "MyNode": { "version": 1, "description": "This is my node", "inputs": { "x": { "type": "float", "description": "The first value", "uiName": "First Value", "deprecated": "Use 'offset' instead." }, "offset": { "type": "float", "description": "This will be added to all values." } } } } This flag is set on the Attribute using `IInternal::deprecateAttribute()` but there should be no need to call this method outside of the node generator tool. `IAttribute::isDeprecated()` can be called to retrieve the flag and `IAttribute::deprecationMessage()` will return the associated message. When actual deprecation occurs then the appropriate action will take the place of the deprecation message - renaming, removing, or replacing the attribute. Modifying Node Behaviour ======================== In addition to changes in attributes, there may also be a change in attribute interpretation or of computational algorithm. A simple example might be the switch to a more numerically stable integration method, or the addition of an extra parameter that can switch computation type. For any change that affects how the node is computed you must bump the node type version number. A mismatch in version number for a node being created and the current node implementation will trigger a callback to the `updateNodeVersion` function, which your node can override if there is some cleanup you can do that will help maintain expected operation of the node. .. _omnigraph_versioning_nodes_collisions: Generated Code Rearrangement **************************** As the number of nodes and variety of use cases has grown some weaknesses in the structure of the generated code directories has been found. This section will describe the problems to be solved without yet any proposed solutions. Node Collisions =============== The generated OgnXXDatabase.h files are all stored in a single directory `_build/ogn/include`, which opens the possibility of name collisions as well as keeping the contents of an extension self-contained. Global Documentation ==================== The generated OgnXX.rst files are all stored in a single directory `_build/ogn/docs`, which while allowing creation of an index that lists all available nodes opens the possibility of collisions as above, and does not tie the documentation of individual nodes to the extensions that implement them. This problem is even more apparent with external/downstream extensions which aren't included in the Kit build and which therefore will not appear in documentation anywhere. There is also a lack of ability for a user to jump from a node type definition or node instantiation to the documentation for that node type, which would be helpful in understanding how to use a node type. Bits and pieces appear throughout the UI (descriptions, attribute types, etc. as tooltips) but this is not the same as a single source of everything related to the node type. Python Builds ============= The Python node types can be built at runtime so while it's helpful to have the prebuilt OgnXXDatabase.py files available it's not strictly necessary. A user should be able to include a Python node type in an extension simply by linking the directory to which it belongs to their build module directory, or even in their extension's directory if they are using the local Python extension approach. Getting in the way of this are first the lack of versioning support in the generated code, especially for local extensions, so that if a user loads their extension using multiple versions of the Kit SDK the generated code will only match one of them. Ideally they would like to support both and the generated code would be a cache, similar to how packman works. The Warp team has implemented something like this already for their own code generator. The Symlinked ogn Directory =========================== Also a problem in the Python generation is how the extension is expecting an `/ogn/` directory in their Python module that has a `nodes/` subdirectory symlinked back to the source for their nodes. The latter is to support hot reload, however the method of doing that breaks the standard method in the build system. If, as above, the generated files appeared elsewhere then there would be no need for the `/ogn/` directory and any `nodes/` subdirectory could be linked directly by the build for hot reload support. The ogn/tests Directory ======================= Similarly to the above the generated tests appear in the `/ogn/tests` subdirectory and the .usda files used for the tests appear in the `/ogn/tests/usd` subdirectory below that. These directories may also vary based on the version of the code generator and the version of the node type. They may also be generated at runtime rather than at build time, making the current mechanism for locating and registering the tests ineffective. Similarly, if outdated versions exist then they should not be registered and run, so the whole test registration mechanism may need rethinking. Supporting Multiple Node Type Versions ====================================== At the moment although there is ABI support for creating multiple versions of the same node type at the same time there is no API support, so that is a necessary addition to make before the code generator can fully support them. Setting that aside, for the code generation there is currently no support for multiple versions of the same node type. The paths and object names are hardcoded to just the node type and/or class name without a version number attached to it. This would also suffer from the same file collisions cited above, exacerbated by the fact that the names for multiple versions would currently be exactly the same. Other Possible Node Type Changes ******************************** This is a catch-all to mention any types of node modifications that won't have intrinsic support. They are listed here to make note of the fact that they have been considered, and if they occur often may merit more direct support. - Node type consolidation. e.g. we had a vertical stack node type and a horizontal node stack type and they were replaced by a single stack node type with an attribute defining the direction. - Node language conversion. A node that was implemented in Python that is changed to be implemented in C++. Ideally both might be available to the user as the Python one is easier to debug but the C++ one is faster. - Device targeting. A node might wish to be implemented on both the CPU and the GPU so that an intelligent scheduler can choose where to execute the node at runtime. Or a node type implementation may just switch from one to the other between versions for other reasons.
15,237
reStructuredText
45.742331
126
0.717792
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning_behavior.rst
.. _omnigraph_versioning_behavior: Code Behavior Versioning ######################## Modifying code behavior is a little trickier than modifying interfaces as the change is invisible to the user writing code. They can only see it at runtime. One example of this is the deprecation of support for the global implicit graph. The ABI does not change to remove support for it, just the behavior of the graph construction. This follows the standard :ref:`omnigraph_deprecation_approach` to give users ample opportunity to modify their code use. The key here is strategic identification of reliance on the old code behaviour so that the user can be properly notified of the need to handle the deprecation. .. hint:: Using the deprecation process ensures that each step only involves a minor version bump to the extension as existing code will continue to work. In the final phase of removal of the original behavior a major version bump may be required.
967
reStructuredText
47.399998
116
0.77456
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning_python.rst
.. _omnigraph_versioning_python: Python Support Versioning ######################### Python has the simultaneous strength and weakness of introspection, where users can access anything that appears in the Python scripts, making all of the Python deliverables a potential part of the API. This is not a reasonable amount of code to support so part of the Python versioning involves defining the API "surface" that versioning support will be provided for. Python Bindings Support *********************** Python bindings can be versioned in parallel with the ABI since for the most part they all correspond to ABI functions. There are exceptions where bindings functions are made as variations of ABI functions to make them more Pythonic, or to provide missing functionality like creation of Python class wrappers. These should be versioned in exactly the same way as the ABI functions so in any given extension version the set of bindings will be consistent. Defining The Python API Surface ******************************* To support proper versioning we first have to be able to define what constitutes "a version" of a set of Python scripts. The easiest way to do this is to use the import system to define the specific set of Python objects that will be supported as part of a version in the way that many popular packages such as *numpy* and *pandas* do. .. code-block:: python import omni.graph.core as og The officially supported Python API "surface" is everything that can be imported in this way. There also might be some submodules that have separate import support in the same way you can use both *import os* and *import os.path*. The extension will provide the set of support imports in its help information. Hiding Implementation Definitions ================================= Python programmers have an understanding that elements with a leading underscore or double underscore ("dunder") are not meant to be public so this can be used to signal this fact to anyone looking through the import structure. This is done at a high level using a module structure that looks like this: .. code-block:: text omni.my.extension/ └── python/ ├── __init__.py ├── _impl/ | extension.py | my_script.py └── tests/ └── test_my_extension.py With this structure then anyone trying to import anything that's not officially supported would be faced with something like this: .. code-block:: python import omni.my.extension._impl.my_script my_script.my_script() It's still possible to do this kind of thing but any Python programmer will realize there is something wrong with that. The method for accessing this same function in an officially supported way would be this: .. code-block:: python import omni.my.extension as me me.my_script() Inside the *__init__.py* file the officially supported API surface is all imported from wherever it happens to be defined so that it can be accessed in this way. .. code-block:: python :caption: __init__.py """Define the API surface for omni.my.extension To access the API for this extension use this import: import omni.my.extension as me To access the testing support for this extension use this import: import omni.my.extension.tests as met """ from ._impl.extension import PublicExtension # Necessary for automatic extension initialization from ._impl.my_script import my_script .. code-block:: python :caption: tests/__init__.py """Define the API surface for omni.my.extension.tests To access the testing support for this extension use this import: import omni.my.extension.tests as met """ from ._impl.test_support import load_test_file .. note:: For future examples the comments will be elided for clarity but the API should always be commented. Adding Version Support ********************** After the soft deprecation period is over the deprecated features will move out of the main imports and into a new location that is version-specific. This will allow continue support for deprecated functions without cluttering up the active code. .. warning:: This is one approach to making a version-specific API layer, to be vetted. A deprecated version should be presented to the user as a fully intact entity so that it can be used pretty much as it was before deprecation. For example if I have upgraded my extension from version 1, which contained a function *old_function()* to version 2, which deprecates that function and adds *new_function()* then the module structure will be altered to this: .. code-block:: text omni.my.extension/ └── python/ ├── __init__.py ├── _impl/ | extension.py | my_script.py └── _1/ __init__.py my_script.py Only the new function will be exposed in the main API definition: .. code-block:: python :caption: __init__.py from ._impl.extension import PublicExtension from ._impl.my_script import new_function .. code-block:: python :caption: _1/__init__.py from .my_script import old_function A-La Carte Access ================= The most flexible method of access is to use a mix-and-match approach to pick up the exact versions of everything you want. This is intentionally difficult to do as it's not a usage pattern we want to encourage, more of a back door that allows users to revert to previous behaviour in very specific places. .. code-block:: python :caption: user_code.py import omni.my.extension as me import omni.my.extension._1 as me1 if some_condition: me.new_function() else: me1.old_function() Always-Latest Access ==================== The most desired type of access is to use the latest API only so that when a new version is added your code will already be using it. So long as we keep the top level *__init__.py* updated to define the latest API this is also the easiest to use: .. code-block:: python :caption: user_code.py import omni.my.extension as me me.new_function() Fixed Version Access ==================== If users wish to lock to a specific version so that they can rely on a stable base they can lock to a specific version. This will only affect them at some point in the future when something in that version is hard-deprecated. .. code-block:: python :caption: user_code.py # Note the leading underscore on the version, hinting that it should not be accessed directly import omni.my.extension._1 as me me.old_function() Module Constant Gated Access ============================ We also want to support a hybrid approach where the users can enable the new interface if they want in order to check whether they need to modify any code for compatibility, while not being locked into it if any work required cannot happen all at once. A Pythonic approach to this problem is to modify the interface definition to have a module-level constant that can be set to different values in order to dynamically flip between different versions using the same import statement. .. code-block:: python :caption: __init__.py import os __version = os.getenv("omni.my.extension", 2) if __version == 1: from ._1 import * elif __version == 2: from ._impl.my_script import new_function else: raise VersionError(f"Environment variable omni.my.extension must be in [1, 2] - got {__version}) .. note:: This is intentionally not something that can change at runtime as that would have unpredictable effects. Something more sophisticated like a sequence of **unload module** --> **edit environment variable** --> **reload module** would be required to support that. Deprecation Of Python Objects ***************************** In order to follow the :ref:`omnigraph_deprecation_approach` for Python objects there has to be different treatment for different types of Python objects so as to provide the deprecation information to the user in an informative but non-intrusive manner. The soft deprecation stage is especially import in Python as the things that can be deprecated can be small and change at a relatively high frequency. To make it easier to deprecate Python code a number of decorators have been created which can be accessed through this import: .. code-block:: python import omni.graph.tools.deprecate as ogd help(ogd) You can see the details of how to deprecate everything in the :ref:`Python deprecation documentation<omnigraph_deprecation>`.
8,587
reStructuredText
37
125
0.718412
omniverse-code/kit/exts/omni.graph.core/docs/internal/internal.rst
:orphan: .. _omnigraph_internal_development: Kit Internal Documentation ########################## .. note:: This documentation is used internally and is intended for Kit developers, though it may provide some insights to Kit SDK users as well. .. toctree:: :maxdepth: 1 :glob: Deprecated Code For Schema Prim<SchemaPrimSetting> Versioning and Deprecation <versioning>
395
reStructuredText
19.842104
113
0.686076
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning.rst
.. _omnigraph_internal_versioning: OmniGraph Versioning And Deprecation #################################### There are many ways in which the OmniGraph code can change from one release to another. This document sets out to enumerate all of them and provide guidelines on how to handle each of them. .. important:: The overall philosophy of versioning in OmniGraph is "First do no harm". Many internal and external customers will be relying on many different versions of OmniGraph so it is up to us to minimize their disruption by providing backward compatibility for as long as possible. Breaking changes should be rare, and vital for future development. .. _omnigraph_deprecation_approach: Deprecation Approach ******************** On those rare occasions where it is necessary to deprecate and eventually remove existing functionality the deprecation should always follow a safe process. This is the generic set of steps to follow for any kind of deprecation. You can see what it should look like to the user in :ref:`omnigraph_deprecation_communication` If there is a significant amount of code to deprecate then you should move it into a separate location for easier removal later. External functions follow the Carbonite ABI versioning :ref:`omnigraph_versioning_carbonite`. If an internal function call is significantly different between the two behaviors then introduce a new version of the function and move the old implementation to a `deprecated/` subdirectory. .. code-block:: c++ :caption: Pre-Deprecation Version struct MyStruct { void mySnazzyFunction(); }; .. code-block:: c++ :caption: Post-Deprecation Version struct MyStruct { void mySnazzyFunction(); private: // Deprecated functions void mySnazzyFunctionV1(); }; void MyStruct::mySnazzyFunction() { if (OmniGraphSettings::myDeprecationFlag()) { mySnazzyFunctionV1(); return; } // do the new stuff }; Code Notices ************ It's a good idea for the deprecation path to clearly mark all of the deprecated code paths. Here is a simple but effective comment that can be inserted before any deprecated code. .. code-block:: cpp // ============================================================================================================== // _____ ______ _____ _____ ______ _____ _______ ______ _____ // | __ | | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ | // | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | // | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | // | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | // |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ // // Code below here is no longer recommended for use in new code. // // ============================================================================================================== Specific Versioning Information ******************************* These documents illustrate versioning and deprecation information that is specific to the modification of particular facets of OmniGraph. .. toctree:: :maxdepth: 1 :glob: Carbonite ABIs <versioning_carbonite> ONI ABIs <versioning_oni> Existing Node Types <versioning_nodes> Code Behavior <versioning_behavior> Extension Numbering <versioning_extensions> Using Settings For Deprecation<versioning_settings> USD File Format<versioning_usd> Python Support<versioning_python> Python Deprecation<deprecation> Compatibility Testing<versioning_testing>
3,750
reStructuredText
36.51
119
0.5744
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning_testing.rst
.. _omnigraph_versioning_testing: Testing Version Upgrades ######################## In order to properly support backward compatibility we need tests in our own code that verify that any code that has not been fully deprecated continues to be accessible and, if possible, functions as intended. In an ideal world we would have tests that have full code coverage and when we deprecate some code we would move the tests exercising that old functionality to the deprecated section and new tests would be added to exercise the new code. Practically speaking this isn't possible so there will be a compromise between thoroughness and test time. These are some of the areas to consider when designing tests for versioning: - Use the ETM (Extension Test Matrix) to verify our new extension versions against existing users of our extensions - For Python code, create "button tests" where every import in our API surface is checked for type and existence - For C++ code create "ABI tests" whose only job is to exercise every function in the ABI - For Python bindings create some combination of the above two that verify every function in the ABI Creating these tests will require some test scaffolding that allows us to confirm coverage. Ideally this would take the form of a code-coverage tool so that we don't have to write our own as that is prone to omissions. .. note:: Performance testing is an important part of compatibility however it will be handled in a separate effort.
1,485
reStructuredText
56.153844
120
0.786532
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning_settings.rst
.. _omnigraph_versioning_settings: OmniGraph Settings For Deprecation ################################## The OmniGraph settings are instantions of `carb::settings` that are specific to OmniGraph. They are used to put in temporary settings for deprecation that follows the standard :ref:`omnigraph_deprecation_approach`. The settings for deprecation will use the namespace `/persistent/omnigraph/deprecation/` to emphasize the fact that these are temporary and meant to control deprecated code. Add The Deprecation Setting *************************** The settings are all controlled through `omni.graph.core/plugins/OmniGraphSettings.{h,cpp}` so the first thing to do is go there and create a new setting with the deprecation name and set up its default value to be the one that will take the original code path. You may need to add some compatibility code if two or more of the settings have illegal combinations. Add an accessor method as well so that your code can read it to decide which path to take. It will also be helpful to add a Python constant containing the path to the new setting in the file `omni.graph/python/_impl/settings.py` Add UI Access Of The Setting **************************** For testing and test migrations it's useful to add access to the setting through the standard settings UI. You can do this by going to `omni.graph.ui/python/scripts/omnigraph_settings_editor.py` and adding a new settings widget that is customized to the path of your new setting. Modify C++ Code Paths Using The Setting *************************************** If you've added an access method for your setting then you can switch code paths by checking that setting. This example is how you do it if you are within the core where the settings object is accessible. .. code-block:: cpp #include "OmniGraphSettings.h" void someCode() { if (OmniGraphSettings::myDeprecationIsActive()) { doTheNewThing(); } else { // It's important to only warn once to avoid spamming the user's console CARB_LOG_WARNING_ONCE("The old thing is deprecated, use the new thing instead"); doTheDeprecatedThing(); } } If you have code that does not live in the core but changes behaviour based on the setting then you have to use the settings ABI to access it. The most common reason for this would be changing behavior within the core Python bindings. .. code-block:: cpp #include <carb/settings/ISettings.h> void someCode() { auto iSettings = carb::getCachedInterface<carb::settings::ISettings>(); if (! iSettings) { CARB_LOG_ERROR_ONCE("Unable to access the iSettings interface"); } // If the settings interface isn't available assume the default. // The hardcoded name is here to avoid exposing the string in the API when we know it will go away soon. if (iSettings && iSettings->getAsBool("/persistent/omnigraph/deprecation/myNewThing")) { doTheNewThing(); } else { // It's important to only warn once to avoid spamming the user's console CARB_LOG_WARNING_ONCE("The old thing is deprecated, use the new thing instead"); doTheDeprecatedThing(); } } Modify Python Code Paths Using The Setting ****************************************** After adding the new setting to the Python *og.Settings* class you can use it to select code paths based on its value. As the Python API is always visible there will be direct access to it and you won't have to drop down to the Carbonite settings bindings. You can see its definition at :py:class:`omni.graph.core.Settings` .. code-block:: python import omni.graph.core as og def some_code(): if og.Settings()(og.Settings.MY_SETTING_NAME): do_the_new_thing() else: do_the_old_thing() You can also use the class as a context manager to temporarily modify the setting, most useful in compatibility tests: .. code-block:: python import omni.graph.core as og while og.Settings.temporary(og.Settings.MY_SETTING_NAME, False): do_the_old_thing()
4,223
reStructuredText
40.009708
118
0.682216
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning_oni.rst
.. _omnigraph_versioning_oni: OmniGraph Versioning For ONI Interfaces ####################################### See the description of the :ref:`omnigraph_oni_versions`. For this example this sample interface will be used, shown in its initial form. .. code-block:: cpp OMNI_DECLARE_INTERFACE(ITestInterface); class ITestInterface_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.ITestInterface")> { protected: /** * Does the old thing * * @param[in] value The value of the old thing */ virtual void oldThing_abi(int value) noexcept = 0; }; class TestInterface : public omni::Implements<ITestInterface> { public: TestInterface() = default; ~TestInterface() = default; protected: void oldThing_abi(int value) noexcept override { doSomething(value); return; } }; void getInterfaceImplementations(const omni::InterfaceImplementation** out, uint32_t* outCount) { static const char* interfacesImplemented[] = { "ITestInterface" }; static omni::InterfaceImplementation impls[] = { { "omni.graph.core.ITestInterface", []() { return static_cast<omni::IObject*>(new ITestInterface); }, 1, interfacesImplemented, CARB_COUNTOF32(interfacesImplemented) } }; *out = impls; *outCount = CARB_COUNTOF32(impls); } To call the interface code you instantiate one of them and call an interface function: .. code-block:: cpp auto iTestOld = omni::core::createType<ITestInterface>(); iTest.oldThing(1); Adding A Function ***************** A new function is added by creating a new interface that derives from the old interface and implements the new function. .. code-block:: cpp :emphasize-lines: 2,13,30,38-43 class ITestInterface2_abi : public omni::core::Inherits<omni::graph::core::ITestInterface, OMNI_TYPE_ID("omni.graph.core.ITestInterface2")> { protected: /** * Does the new thing * * @param[in] value The value of the new thing */ virtual void newThing_abi(int value) noexcept = 0; }; class TestInterface2 : public omni::Implements<ITestInterface2> { public: TestInterface2() = default; ~TestInterface2() = default; protected: void newThing_abi(int value) noexcept override { doSomethingNew(value); return; } }; void getInterfaceImplementations(const omni::InterfaceImplementation** out, uint32_t* outCount) { static const char* interfacesImplemented[] = { "ITestInterface" }; static const char* interfacesImplemented2[] = { "ITestInterface2" }; static omni::InterfaceImplementation impls[] = { { "omni.graph.core.ITestInterface", []() { return static_cast<omni::IObject*>(new ITestInterface); }, 1, interfacesImplemented, CARB_COUNTOF32(interfacesImplemented) }, { "omni.graph.core.ITestInterface2", []() { return static_cast<omni::IObject*>(new ITestInterface2); }, 1, interfacesImplemented2, CARB_COUNTOF32(interfacesImplemented) } }; *out = impls; *outCount = CARB_COUNTOF32(impls); } The old code is untouched by this and continues to function as usual. Any code wishing to use the new function has to instantiate the new interface. .. code-block:: cpp auto iTestOld = omni::core::createType<ITestInterface>(); iTest.oldThing(1); // iTest.newThing(2); // Would fail - this behaves as the old interface only auto iTestNew = omni::core::createType<ITestInterface2>(); iTestNew.oldThing(1); // Still works iTestNew.newThing(2); Deprecating Functions ********************* In the rare occasion where you want to deprecate a function entirely you must follow this process to ensure maximum compatibility and notification to affected users. Step 1: Add a Deprecation Notice ================================ The team should decide exactly when a deprecation will happen, as it is beneficial to group deprecations together to minimize the work required on the user end to deal with the deprecations. Once that's decided the first thing to do is to communicate the deprecation intent through the decided-upon channels. Once that has happend the implementation of the interface function will add a warning message that the function is deprecated and will be going away. .. code-block:: cpp :emphasize-lines: 8,26 OMNI_DECLARE_INTERFACE(ITestInterface); class ITestInterface_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.ITestInterface")> { protected: /** * This function is deprecated - use newFunction() instead * * Does the old thing * * @param[in] value The value of the old thing */ virtual void oldThing_abi(int value) noexcept = 0; }; class TestInterface : public omni::Implements<ITestInterface> { public: TestInterface() = default; ~TestInterface() = default; protected: void oldThing_abi(int value) noexcept override { CARB_LOG_WARNING("ITestInterface::oldFunction() is deprecated - use ITestInterface::newFunction() instead"); doSomething(value); return; } }; Step 2: Make The Deprecated Path An Error ========================================= To ensure the use of the deprecated path is highly visible in this phase the warning is upgraded to an error and the comments on the function make it more clear that it is not to be used in new code. .. code-block:: cpp :emphasize-lines: 8,22 OMNI_DECLARE_INTERFACE(ITestInterface); class ITestInterface_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.ITestInterface")> { protected: /** * This function is deprecated - use newFunction() instead */ virtual void oldThing_abi(int value) noexcept = 0; }; class TestInterface : public omni::Implements<ITestInterface> { public: TestInterface() = default; ~TestInterface() = default; protected: void oldThing_abi(int value) noexcept override { CARB_LOG_ERROR("ITestInterface::oldFunction() is deprecated - use ITestInterface::newFunction() instead"); doSomething(value); return; } }; .. note:: You can choose to make the deprecation even more emphatic if calling the function could do something bad like create instability in the code. You can do so by using a `throw` instead of just `CARB_LOG_ERROR`. Step 3: Hard Deprecation Of The Function ======================================== When the final step is necessary you must bump the major version number of the extension as this is a breaking change. You must also bump the version of the interface so that in those cases where an extension has access to both the old and new versions of the interface it will prefer the new one. The interface class remains though, even if the last function has been taken from it. .. important:: This type of hard deprecation is extremely disruptive as it will require extensions to be rebuilt and possibly modified to conform to the new interface. It should only be used when there is something in the interface that is intrinsically dangerous or difficult to continue supporting. .. code-block:: cpp :emphasize-lines: 5-6,14-15,25 OMNI_DECLARE_INTERFACE(ITestInterface); class ITestInterface_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.graph.core.ITestInterface")> { }; class TestInterface : public omni::Implements<ITestInterface> { public: TestInterface() = default; ~TestInterface() = default; protected: }; void getInterfaceImplementations(const omni::InterfaceImplementation** out, uint32_t* outCount) { static const char* interfacesImplemented[] = { "ITestInterface" }; static const char* interfacesImplemented2[] = { "ITestInterface2" }; static omni::InterfaceImplementation impls[] = { { "omni.graph.core.ITestInterface", []() { return static_cast<omni::IObject*>(new ITestInterface); }, 2, interfacesImplemented, CARB_COUNTOF32(interfacesImplemented) }, { "omni.graph.core.ITestInterface2", []() { return static_cast<omni::IObject*>(new ITestInterface2); }, 1, interfacesImplemented2, CARB_COUNTOF32(interfacesImplemented) } }; *out = impls; *outCount = CARB_COUNTOF32(impls); }
9,179
reStructuredText
31.210526
121
0.628718
omniverse-code/kit/exts/omni.graph.core/docs/internal/SchemaPrimSetting.rst
Schema Prim Setting Flow ######################## The **useSchemaPrim** setting controls how the graph is backed by USD. The code was refactored to divert as much of the old code as possible into the *deprecated/* directory so that it is isolated and won't change until such time as the setting is made permanent and it can be deleted. The graph is divided into three sections - code that was converted fully to use the schema approach, hybrid code that uses the setting to switch between schema and non-schema behaviours, and deprecated code that is only used by the non-schema code paths. .. _omnigraph_extension_dependency_graph: .. mermaid:: flowchart LR subgraph Converted ComputeGraphImpl::parseGraph Graph::attachToStage Graph::changePipelineStage Graph::initFromStage Graph::onNodeTypeRegistered Graph::postLoadUpgradeFileFormatVersion Graph::rangeContainsOGNodes Graph::writeSettingsInUSD GraphContext::addPrimToCache GraphContext::attachToStage GraphContext::createNeededNodesForPrim GraphContext::createNewNode GraphContext::createNewSubgraph GraphContext::initializeFabric GraphContext::updateChangeProcessing end subgraph Uses Setting Graph::couldPrimBelongToGraph Graph::createGraphAsNode Graph::findFileFormatVersionInRange Graph::initContextAndFabric Graph::isGlobalGraphPrim Graph::isOmniGraphPrim Graph::isPrimAnOmniGraphMember Graph::reloadFromStage Graph::requiresFileFormatCallback Graph::setNodeInstance Graph::setPathToGraph Graph::writeFileFormatVersion Graph::writeSettingsToUSD Graph::writeTokenSetting GraphContext::_::getPrimsNodeTypeAttribute GraphContext::_addGatherPrimToFlatCacheIndex GraphContext::_addPrimToFlatCacheIndex GraphContext::checkForDynamicAttributes GraphContext::createNewNodeWithUSD GraphContext::createNewSubgraph GraphContext::createNodeFromPrim GraphContext::createNodesAndSubgraphs GraphContext::initializeNode GraphContext::getUpstreamPrims GraphContext::reloadGraphSettings Node::isPrimAnOmniGraphNode Node::getPrimsNodeTypeAttribute Node::Node OmniGraphUsdNoticeListener::processNewAndDeletedGraphs PluginInterface::attach end subgraph Deprecated ComputeGraphImpl::parseGraphNoSchema Graph::attachToStageNoSchema Graph::couldPrimBelongToGraphNoSchema Graph::createGraphAsNodeNoSchema Graph::findFileFormatVersionInRangeNoSchema Graph::initContextAndFlatCache Graph::initContextAndFlatCacheNoSchema Graph::initFromStageNoSchema Graph::isGlobalGraphPrimNoSchema Graph::reloadFromStageNoSchema Graph::writeFileFormatVersionNoSchema Graph::writeSettingsToUSDNoSchema GraphContext::_addPrimToFlatCacheIndexNoSchema GraphContext::attachToStageNoSchema GraphContext::checkForDynamicAttributesNoSchema GraphContext::createNewSubgraphNoSchema GraphContext::createNodesAndSubgraphsNoSchema GraphContext::initializeFlatcacheNoSchema GraphContext::reloadGraphSettingsNoSchema NoSchemaSupport::writeEvaluatorTypeToSettings NoSchemaSupport::writeGraphBackingTypeToSettings NoSchemaSupport::writeGraphPipelineStageToSettings NoSchemaSupport::writeEvaluationModeToSettings NoSchemaSupport::writeTokenSetting PluginInterface::attachNoSchema end ComputeGraphImpl::parseGraph --> ComputeGraphImpl::parseGraphNoSchema ComputeGraphImpl::parseGraph --> Graph::attachToStage ComputeGraphImpl::parseGraph --> Graph::findFileFormatVersionInRange ComputeGraphImpl::parseGraph --> Graph::initFromStage ComputeGraphImpl::parseGraph --> Graph::setNodeInstance ComputeGraphImpl::parseGraph --> GraphContext::initializeFabric ComputeGraphImpl::parseGraph --> Node::Node GraphContext::addPrimToCache --> GraphContext::_addPrimToFlatCacheIndex GraphContext::attachToStage --> Graph::writeSettingsInUSD GraphContext::attachToStage --> GraphContext::createNodesAndSubgraphs GraphContext::createNeededNodesForPrim --> GraphContext::createNodeFromPrim GraphContext::createNewNode --> Graph::setNodeInstance GraphContext::createNewNodeWithUSD --> GraphContext::_addPrimToFlatCacheIndex GraphContext::createNodeFromPrim --> Graph::setNodeInstance GraphContext::createNodeFromPrim --> GraphContext::initializeNode GraphContext::createNodesAndSubgraphs --> Graph::writeSettingsInUSD GraphContext::createNodesAndSubgraphs --> GraphContext::createNeededNodesForPrim GraphContext::createNodesAndSubgraphs --> GraphContext::createNodesAndSubgraphs GraphContext::initializeFabric --> GraphContext::_addGatherPrimToFlatCacheIndex GraphContext::initializeFabric --> GraphContext::_addGatherPrimToFlatCacheIndex GraphContext::initializeFabric --> GraphContext::_addPrimToFlatCacheIndex GraphContext::initializeFabric --> GraphContext::_addPrimToFlatCacheIndex GraphContext::initializeNode --> GraphContext::_::getPrimsNodeTypeAttribute GraphContext::initializeNode --> GraphContext::checkForDynamicAttributes GraphContext::initializeNode --> Node::getPrimsNodeTypeAttribute GraphContext::updateChangeProcessing --> GraphContext::_::getPrimsNodeTypeAttribute GraphContext::updateChangeProcessing --> GraphContext::_addPrimToFlatCacheIndex GraphContext::updateChangeProcessing --> GraphContext::createNodesAndSubgraphs GraphContext::updateChangeProcessing --> Node::getPrimsNodeTypeAttribute GraphContext::_addPrimToFlatCacheIndex --> GraphContext::_addPrimToFlatCacheIndexNoSchema GraphContext::attachToStage --> GraphContext::attachToStageNoSchema GraphContext::checkForDynamicAttributes --> GraphContext::checkForDynamicAttributesNoSchema GraphContext::createNewSubgraph --> GraphContext::createNewSubgraphNoSchema GraphContext::createNodesAndSubgraphs --> GraphContext::createNodesAndSubgraphsNoSchema GraphContext::initializeFabric --> GraphContext::initializeFlatcacheNoSchema GraphContext::reloadGraphSettings --> GraphContext::reloadGraphSettingsNoSchema Graph::attachToStage --> Graph::attachToStageNoSchema Graph::attachToStage --> GraphContext::attachToStage Graph::changePipelineStage --> Graph::setNodeInstance Graph::couldPrimBelongToGraph --> Graph::couldPrimBelongToGraphNoSchema Graph::couldPrimBelongToGraph --> Graph::isGlobalGraphPrim Graph::couldPrimBelongToGraph --> Graph::isPrimAnOmniGraphMember Graph::createGraphAsNode --> Graph::createGraphAsNodeNoSchema Graph::createGraphAsNode --> Graph::setNodeInstance Graph::createGraphAsNode --> GraphContext::initializeFabric Graph::findFileFormatVersionInRange --> Graph::findFileFormatVersionInRangeNoSchema Graph::initContextAndFabric --> GraphContext::initializeFabric Graph::initContextAndFlatCache --> Graph::initContextAndFlatCacheNoSchema Graph::initFromStage --> Graph::attachToStage Graph::initFromStage --> Graph::initContextAndFabric Graph::initFromStage --> Graph::initFromStageNoSchema Graph::isGlobalGraphPrim --> Graph::isGlobalGraphPrimNoSchema Graph::postLoadUpgradeFileFormatVersion --> Graph::writeFileFormatVersion Graph::reloadFromStage --> Graph::attachToStage Graph::reloadFromStage --> Graph::rangeContainsOGNodes Graph::reloadFromStage --> Graph::reloadFromStageNoSchema Graph::reloadFromStage --> GraphContext::initializeFabric Graph::writeFileFormatVersion --> Graph::writeFileFormatVersionNoSchema Graph::writeSettingsToUSD --> Graph::writeFileFormatVersionNoSchema Graph::writeSettingsToUSD --> Graph::writeSettingsToUSDNoSchema Graph::writeSettingsToUSDNoSchema --> NoSchemaSupport::writeEvaluatorTypeToSettings Graph::writeSettingsToUSDNoSchema --> NoSchemaSupport::writeGraphBackingTypeToSettings Graph::writeSettingsToUSDNoSchema --> NoSchemaSupport::writeGraphPipelineStageToSettings NoSchemaSupport::writeEvaluatorTypeToSettings --> NoSchemaSupport::writeTokenSetting NoSchemaSupport::writeGraphBackingTypeToSettings --> NoSchemaSupport::writeTokenSetting NoSchemaSupport::writeGraphPipelineStageToSettings --> NoSchemaSupport::writeTokenSetting NoSchemaSupport::writeEvaluationModeToSettings --> NoSchemaSupport::writeTokenSetting Node::Node --> Node::isPrimAnOmniGraphNode PluginInterface::attach --> ComputeGraphImpl::parseGraph PluginInterface::attach --> Graph::findFileFormatVersionInRange PluginInterface::attach --> Graph::initContextAndFabric PluginInterface::attach --> Graph::rangeContainsOGNodes PluginInterface::attach --> PluginInterface::attachNoSchema OmniGraphUsdNoticeListener::processNewAndDeletedGraphs --> ComputeGraphImpl::parseGraph OmniGraphUsdNoticeListener::processNewAndDeletedGraphs --> Graph::isGlobalGraphPrim
9,752
reStructuredText
54.731428
119
0.728158
omniverse-code/kit/exts/omni.graph.core/docs/internal/versioning_carbonite.rst
.. _omnigraph_versioning_carbonite: OmniGraph Versioning For Carbonite Interfaces ############################################# See the description of the :ref:`omnigraph_carbonite_versions`. For this example this sample interface will be used, shown in its initial form. Note the structure integrity check at the end, designed to catch situations where a new function is unintentionally added to the middle of the interface. .. code-block:: cpp class ITestInterface { CARB_PLUGIN_INTERFACE("omni::graph::core::ITestInterface", 1, 0); /** * Does the old thing * * @param[in] value The value of the old thing */ void (CARB_ABI* oldFunction)(int value); }; // Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle STRUCT_INTEGRITY_CHECK(IAttribute, oldFunction, 1) void oldFunction_impl(int value) { doSomething(value); return; } Adding A Function ***************** A new function is added. The version number is bumped and the structural integrity check is updated. .. code-block:: cpp :emphasize-lines: 3,12-17,20,28-32 class ITestInterface { CARB_PLUGIN_INTERFACE("omni::graph::core::ITestInterface", 1, 1); /** * Does the old thing * * @param[in] value The value of the old thing */ void (CARB_ABI* oldFunction)(int value); /** * Does the new thing * * @param[in] value The value of the new thing */ void (CARB_ABI* newFunction)(int value); }; // Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle STRUCT_INTEGRITY_CHECK(IAttribute, newFunction, 2) void oldFunction_impl(int value) { doSomething(value); return; } void newFunction_impl(int value) { doSomethingNew(value); return; } Deprecating Functions ********************* In the rare occasion where you want to deprecate a function entirely you must follow this three-step process to ensure maximum compatibility and notification to affected users. Step 1: Add a Deprecation Notice ================================ The team should decide exactly when a deprecation will happen, as it is beneficial to group deprecations together to minimize the work required on the user end to deal with the deprecations. Once that's decided the first thing to do is to communicate the deprecation intent through the decided-upon channels. Once that has happend the implementation of the interface function will add a warning message that the function is deprecated and will be going away. .. code-block:: cpp :emphasize-lines: 6,26 class ITestInterface { CARB_PLUGIN_INTERFACE("omni::graph::core::ITestInterface", 1, 1); /** * This function is deprecated - use newFunction() instead * * Does the old thing * * @param[in] value The value of the old thing */ void (CARB_ABI* oldFunction)(int value); /** * Does the new thing * * @param[in] value The value of the new thing */ void (CARB_ABI* newFunction)(int value); }; // Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle STRUCT_INTEGRITY_CHECK(IAttribute, newFunction, 2) void oldFunction_impl(int value) { CARB_LOG_WARNING("ITestInterface::oldFunction() is deprecated - use ITestInterface::newFunction() instead"); doSomething(value); return; } void newFunction_impl(int value) { doSomethingNew(value); return; } Step 2: Make The Deprecated Path An Error ========================================= To ensure the use of the deprecated path is highly visible in this phase the warning is upgraded to an error and the comments on the function make it more clear that it is not to be used in new code. .. code-block:: cpp :emphasize-lines: 6-7,22 class ITestInterface { CARB_PLUGIN_INTERFACE("omni::graph::core::ITestInterface", 1, 1); /** * This function is deprecated - use newFunction() instead */ void (CARB_ABI* oldFunction)(int value); /** * Does the new thing * * @param[in] value The value of the new thing */ void (CARB_ABI* newFunction)(int value); }; // Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle STRUCT_INTEGRITY_CHECK(IAttribute, newFunction, 2) void oldFunction_impl(int value) { CARB_LOG_ERROR("ITestInterface::oldFunction() is deprecated - use ITestInterface::newFunction() instead"); doSomething(value); return; } void newFunction_impl(int value) { doSomethingNew(value); return; } Step 3: Hard Deprecation Of The Function ======================================== To ensure the ABI integrity functions may not be removed from the interface, however they can be renamed and all information about what they once were can be removed. At this point calls to them will no longer function. They will only issue an error. The function signatures remain the same to avoid type errors. The implementation of the deprecated function can be moved to a common graveyard of deprecated functions. .. code-block:: cpp :emphasize-lines: 5,23-27 class ITestInterface { CARB_PLUGIN_INTERFACE("omni::graph::core::ITestInterface", 1, 1); /* DEPRECATED */ void (CARB_ABI* deprecated_1)(int); /** * Does the new thing * * @param[in] value The value of the new thing */ void (CARB_ABI* newFunction)(int value); }; // Update this every time a new ABI function is added, to ensure one isn't accidentally added in the middle STRUCT_INTEGRITY_CHECK(IAttribute, newFunction, 2) void newFunction_impl(int value) { doSomethingNew(value); return; } void oldFunction_impl(int) { CARB_LOG_ERROR("ITestInterface::oldFunction() is deprecated - use ITestInterface::newFunction() instead"); return; }
6,382
reStructuredText
29.395238
119
0.63256
omniverse-code/kit/exts/omni.kit.widget.text_editor/config/extension.toml
[package] title = "Text Editor" category = "Internal" description = "Bindings to ImGuiColorTextEdit" version = "1.0.2" changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} [[native.library]] path = "bin/${lib_prefix}omni.kit.widget.text_editor${lib_ext}" [[python.module]] name = "omni.kit.widget.text_editor" [[test]] dependencies = [ "omni.kit.renderer.capture", "omni.kit.ui_test", ] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] stdoutFailPatterns.exclude = [ "*omniclient: Initialization failed*", ]
657
TOML
18.352941
63
0.669711
omniverse-code/kit/exts/omni.kit.widget.text_editor/omni/kit/widget/text_editor/tests/test_text_editor.py
## Copyright (c) 2018-2019, 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__ = ["TestTextEditor"] import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import omni.kit.app from .._text_editor import TextEditor EXTENSION_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) GOLDEN_PATH = EXTENSION_PATH.joinpath("data/golden") STYLE = {"Field": {"background_color": 0xFF24211F, "border_radius": 2}} class TestTextEditor(OmniUiTest): async def test_general(self): """Testing general look of TextEditor""" window = await self.create_test_window() lines = ["The quick brown fox jumps over the lazy dog."] * 20 with window.frame: TextEditor(text_lines=lines) for i in range(2): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=GOLDEN_PATH, golden_img_name=f"test_general.png") async def test_syntax(self): """Testing languages of TextEditor""" import inspect window = await self.create_test_window() with window.frame: TextEditor(text_lines=inspect.getsource(self.test_syntax).splitlines(), syntax=TextEditor.Syntax.PYTHON) for i in range(2): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=GOLDEN_PATH, golden_img_name=f"test_syntax.png") async def test_text_changed_flag(self): """Testing TextEditor text edited callback""" from omni.kit import ui_test window = await self.create_test_window(block_devices=False) window.focus() text = "Lorem ipsum" text_new = "dolor sit amet" with window.frame: text_editor = TextEditor(text=text) await ui_test.wait_n_updates(2) self.text_changed = False def on_text_changed(text_changed): self.text_changed = text_changed text_editor.set_edited_fn(on_text_changed) self.assertFalse(self.text_changed) await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(100, 100)) await ui_test.wait_n_updates(2) await ui_test.emulate_char_press("A") await ui_test.wait_n_updates(2) self.assertTrue(self.text_changed) await ui_test.emulate_key_combo("BACKSPACE") await ui_test.wait_n_updates(2) self.assertFalse(self.text_changed) text_editor.text = text_new await ui_test.wait_n_updates(2) # Only user input will trigger the callback self.assertFalse(self.text_changed) await ui_test.emulate_char_press("A") await ui_test.wait_n_updates(2) self.assertTrue(self.text_changed) text_editor.set_edited_fn(None)
3,199
Python
31.98969
116
0.666458
omniverse-code/kit/exts/omni.kit.widget.text_editor/docs/CHANGELOG.md
# Changelog ## [1.0.2] - 2022-07-28 ### Added - Callback passing a bool that user has edited the text ## [1.0.1] - 2022-06-29 ### Added - Syntax highlighting ## [1.0.0] - 2022-04-30 ### Added - Initial commit
212
Markdown
14.214285
55
0.622642