file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/style.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 omni.ui as ui
from omni.kit.widget.versioning import get_icons_path
def get_style():
style = carb.settings.get_settings().get("/persistent/app/window/uiStyle")
if not style:
style = "NvidiaDark"
FONT_SIZE = 14.0
if style == "NvidiaLight": # pragma: no cover -- unused style
WIDGET_BACKGROUND_COLOR = 0xFF454545
BUTTON_BACKGROUND_COLOR = 0xFF545454
BUTTON_FONT_COLOR = 0xFFD6D6D6
INPUT_BACKGROUND_COLOR = 0xFF454545
INPUT_FONT_COLOR = 0xFFD6D6D6
INPUT_HINT_COLOR = 0xFF9E9E9E
CARD_BACKGROUND_COLOR = 0xFF545454
CARD_HOVERED_COLOR = 0xFF6E6E6E
CARD_SELECTED_COLOR = 0xFFBEBBAE
CARD_FONT_COLOR = 0xFFD6D6D6
CARD_SEPARATOR_COLOR = 0x44D6D6D6
MENU_BACKGROUND_COLOR = 0xFF454545
MENU_FONT_COLOR = 0xFFD6D6D6
MENU_SEPARATOR_COLOR = 0x44D6D6D6
NOTIFICATION_BACKGROUND_COLOR = 0xFF545454
NOTIFICATION_FONT_COLOR = 0xFFD6D6D6
TREEVIEW_BACKGROUND_COLOR = 0xFF545454
TREEVIEW_ITEM_COLOR = 0xFFD6D6D6
TREEVIEW_HEADER_BACKGROUND_COLOR = 0xFF545454
TREEVIEW_HEADER_COLOR = 0xFFD6D6D6
TREEVIEW_SELECTED_COLOR = 0x109D905C
else:
WIDGET_BACKGROUND_COLOR = 0xFF343432
BUTTON_BACKGROUND_COLOR = 0xFF23211F
BUTTON_FONT_COLOR = 0xFF9E9E9E
INPUT_BACKGROUND_COLOR = 0xFF23211F
INPUT_FONT_COLOR = 0xFF9E9E9E
INPUT_HINT_COLOR = 0xFF4A4A4A
CARD_BACKGROUND_COLOR = 0xFF23211F
CARD_HOVERED_COLOR = 0xFF3A3A3A
CARD_SELECTED_COLOR = 0xFF8A8777
CARD_FONT_COLOR = 0xFF9E9E9E
CARD_SEPARATOR_COLOR = 0x449E9E9E
MENU_BACKGROUND_COLOR = 0xFF343432
MENU_FONT_COLOR = 0xFF9E9E9E
MENU_SEPARATOR_COLOR = 0x449E9E9E
NOTIFICATION_BACKGROUND_COLOR = 0xFF343432
NOTIFICATION_FONT_COLOR = 0xFF9E9E9E
TREEVIEW_BACKGROUND_COLOR = 0xFF23211F
TREEVIEW_ITEM_COLOR = 0xFF9E9E9E
TREEVIEW_HEADER_BACKGROUND_COLOR = 0xFF343432
TREEVIEW_HEADER_COLOR = 0xFF9E9E9E
TREEVIEW_SELECTED_COLOR = 0x664F4D43
style = {
"Window": {"secondary_background_color": 0},
"ScrollingFrame": {"background_color": WIDGET_BACKGROUND_COLOR, "margin_width": 0},
"ComboBox": {"background_color": BUTTON_BACKGROUND_COLOR, "color": BUTTON_FONT_COLOR},
"ComboBox.Field": {"background_color": INPUT_BACKGROUND_COLOR, "color": INPUT_FONT_COLOR},
"ComboBox.Field::hint": {"background_color": 0x0, "color": INPUT_HINT_COLOR},
"Card": {"background_color": CARD_BACKGROUND_COLOR, "color": CARD_FONT_COLOR, "margin_height": 1, "border_width": 2},
"Card:hovered": {"background_color": CARD_HOVERED_COLOR, "border_color": CARD_HOVERED_COLOR, "border_width": 2},
"Card:pressed": {"background_color": CARD_HOVERED_COLOR, "border_color": CARD_HOVERED_COLOR, "border_width": 2},
"Card:selected": {"background_color": CARD_SELECTED_COLOR, "border_color": CARD_SELECTED_COLOR, "border_width": 2},
"Card.Label": {"background_color": 0x0, "color": CARD_FONT_COLOR, "margin_width": 4},
"Card.Label:selected": {"background_color": 0x0, "color": CARD_BACKGROUND_COLOR, "margin_width": 4},
"Card.Separator": {"background_color": 0x0, "color": CARD_SEPARATOR_COLOR},
"Menu": {"background_color": MENU_BACKGROUND_COLOR, "color": MENU_FONT_COLOR, "border_radius": 2},
"Menu.Item": {"background_color": 0x0, "margin": 0},
"Menu.Separator": {"background_color": 0x0, "color": MENU_SEPARATOR_COLOR, "alignment": ui.Alignment.CENTER},
"Notification": {"background_color": NOTIFICATION_BACKGROUND_COLOR, "margin_width": 0},
"Notification.Label": {"background_color": 0x0, "color": NOTIFICATION_FONT_COLOR, "alignment": ui.Alignment.CENTER_TOP},
"TreeView": {"background_color": 0x0},
"TreeView.Background": {"background_color": TREEVIEW_BACKGROUND_COLOR},
"TreeView.Header": {"background_color": TREEVIEW_HEADER_BACKGROUND_COLOR, "color": TREEVIEW_HEADER_COLOR},
"TreeView.Header::label": {"margin": 4},
"TreeView.Item": {"margin":4, "background_color": 0x0, "color": TREEVIEW_ITEM_COLOR},
"TreeView.Item:selected": {"margin":4, "color": TREEVIEW_SELECTED_COLOR},
}
return style
| 4,783 | Python | 49.357894 | 128 | 0.673218 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/extension.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.ext
from functools import lru_cache
from pathlib import Path
ICON_PATH = ""
@lru_cache()
def get_icons_path() -> str:
return ICON_PATH
class VerioningExtension(omni.ext.IExt):
def on_startup(self, ext_id):
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global ICON_PATH
ICON_PATH = Path(extension_path).joinpath("data").joinpath("icons")
def on_shutdown(self):
pass
| 927 | Python | 28.935483 | 76 | 0.731392 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
LAYOUT_SLIM_VIEW = 1
LAYOUT_TABLE_VIEW = 2
LAYOUT_DEFAULT = 3
from .extension import *
from .widget import CheckpointWidget
from .checkpoints_model import CheckpointModel, CheckpointItem
from .checkpoint_combobox import CheckpointCombobox
from .checkpoint_helper import CheckpointHelper
| 722 | Python | 37.05263 | 76 | 0.815789 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/context_menu.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
from typing import Callable, List
from functools import partial
from carb import log_warn
from .checkpoints_model import CheckpointItem
from .style import get_style
class ContextMenu:
"""
Creates popup menu for the hovered CheckpointItem. In addition to the set of default actions below,
users can add more via the add_menu_item API.
"""
def __init__(self):
self._context_menu: ui.Menu = None
self._menu_dict: list = []
self._context: dict = None
self._build_ui()
@property
def menu(self) -> ui.Menu:
""":obj:`omni.ui.Menu` The menu widget"""
return self._context_menu
@property
def context(self) -> dict:
"""dict: Provides data to the callback. Available keys are {'item', 'is_bookmark', 'is_connection', 'selected'}"""
return self._context
def show(self, item: CheckpointItem, selected: List[CheckpointItem] = []):
"""
Creates the popup menu from definition for immediate display. Receives as input, information about the
item. These values are made available to the callback via the 'context' dictionary.
Args:
item (CheckpointItem): Item for which to create menu.,
selected (List[CheckpointItem]): List of currently selected items. Default [].
"""
self._context = {}
self._context["item"] = item
self._context["selected"] = selected
self._context_menu = ui.Menu("Context menu", style=get_style(), style_type_name_override="Menu")
with self._context_menu:
prev_entry = None
for i, menu_entry in enumerate(self._menu_dict):
if i == len(self._menu_dict) - 1 and not menu_entry.get("name"):
# Don't draw separator as last item
break
if menu_entry.get("name") or (prev_entry and prev_entry.get("name")):
# Don't draw 2 separators in a row
self._build_menu(menu_entry, self._context)
prev_entry = menu_entry
# Show it
if len(self._menu_dict) > 0:
self._context_menu.show()
def _build_ui(self):
pass
def _build_menu(self, menu_entry, context):
from omni.kit.ui import get_custom_glyph_code
enabled = 1
if "enable_fn" in menu_entry and menu_entry["enable_fn"]:
enabled = menu_entry["enable_fn"](context)
if enabled < 0:
return
if menu_entry["name"] == "":
ui.Separator(style_type_name_override="Menu.Separator")
else:
menu_name = ""
if "glyph" in menu_entry:
menu_name = " " + get_custom_glyph_code("${glyphs}/" + menu_entry["glyph"]) + " "
if "onclick_fn" in menu_entry and menu_entry["onclick_fn"]:
menu_item = ui.MenuItem(
menu_name + menu_entry["name"],
triggered_fn=partial(menu_entry["onclick_fn"], context),
enabled=bool(enabled),
style_type_name_override="Menu.Item",
)
else:
menu_item = ui.MenuItem(menu_name + menu_entry["name"], enabled=False, style_type_name_override="Menu.Item")
def add_menu_item(self, name: str, glyph: str, onclick_fn: Callable, enable_fn: Callable, index: int = -1) -> str:
"""
Adds menu item, with corresponding callbacks, to this context menu.
Args:
name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the context menu.
glyph (str): Associated glyph to display for this menu item.
onclick_fn (Callable): This callback function is executed when the menu item is clicked. Function signature:
void fn(name: str, item: CheckpointItem), where name is menu name.
enable_fn (Callable): Returns 1 to enable this menu item, 0 to disable, -1 to hide.
Function signature: bool fn(name: str, item: CheckpointItem).
index (int): The position that this menu item will be inserted to.
Returns:
str: Name of menu item if successful, None otherwise.
"""
if name and name in [item.get("name", None) for item in self._menu_dict]:
# Reject duplicates
return None
menu_item = {"name": name, "glyph": glyph or ""}
if onclick_fn:
menu_item["onclick_fn"] = lambda context, name=name: onclick_fn(name, context["item"])
if enable_fn:
menu_item["enable_fn"] = lambda context, name=name: enable_fn(name, context["item"])
if index < 0 or index >= len(self._menu_dict):
index = len(self._menu_dict)
self._menu_dict.insert(index, menu_item)
return name
def delete_menu_item(self, name: str):
"""
Deletes the menu item, with the given name, from this context menu.
Args:
name (str): Name of the menu item (e.g. 'Open').
"""
if not name:
return
found = (i for i, item in enumerate(self._menu_dict) if name == item.get("name", None))
for j in sorted([i for i in found], reverse=True):
del self._menu_dict[j]
def _build_ui(self):
'''
Example:
self._menu_dict = [
{
"name": "Test",
"glyph": "pencil.svg",
"onclick_fn": lambda context: print(">>> TESTING"),
},
]
'''
pass
def _on_copy_to_clipboard(self, item: CheckpointItem):
try:
import omni.kit.clipboard
omni.kit.clipboard.copy(item.path)
except ImportError:
log_warn("Warning: Could not import omni.kit.clipboard.")
def destroy(self):
self._context_menu = None
self._menu_dict = None
self._context = None
| 6,430 | Python | 36.389535 | 124 | 0.580093 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/checkpoint_helper.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 asyncio
import omni.client
from typing import Callable
class CheckpointHelper:
server_cache = {}
@staticmethod
def extract_server_from_url(url: str) -> str:
server_url = ""
if url:
client_url = omni.client.break_url(url)
server_url = omni.client.make_url(scheme=client_url.scheme, host=client_url.host, port=client_url.port)
return server_url
@staticmethod
async def is_checkpoint_enabled_async(url: str) -> bool:
server_url = CheckpointHelper.extract_server_from_url(url)
if not server_url:
enabled = False
elif server_url in CheckpointHelper.server_cache:
enabled = CheckpointHelper.server_cache[server_url]
else:
result, server_info = await omni.client.get_server_info_async(server_url)
supports_checkpoint = result and server_info and server_info.checkpoints_enabled
CheckpointHelper.server_cache[server_url] = supports_checkpoint
enabled = supports_checkpoint
return enabled
@staticmethod
def is_checkpoint_enabled_with_callback(url: str, callback: Callable):
async def is_checkpoint_enabled_async(url: str, callback: Callable):
enabled = await CheckpointHelper.is_checkpoint_enabled_async(url)
if callback:
callback(CheckpointHelper.extract_server_from_url(url), enabled)
asyncio.ensure_future(is_checkpoint_enabled_async(url, callback)) | 1,937 | Python | 40.234042 | 115 | 0.694373 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/checkpoint_widget.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 asyncio
import weakref
import omni.kit.app
import omni.ui as ui
from .checkpoints_model import CheckpointsModel
from .checkpoints_delegate import CheckpointsDelegate
from .style import get_style
class CheckpointWidget:
def __init__(self, url: str = "", width=700, show_none_entry=False, **kwargs):
"""
Build a CheckpointWidget. Called while constructing UI layout.
Args:
url (str): The url of the file to list checkpoints from.
width (str): Width of the checkpoint widget.
show_none_entry (bool): Whether to show a dummy "head" entry to represent not using checkpoint.
"""
self._checkpoint_model = CheckpointsModel(show_none_entry)
self._checkpoint_model.set_on_list_checkpoint_fn(self._on_list_checkpoint)
self._checkpoint_delegate = CheckpointsDelegate(kwargs.get("open_file", None))
self._tree_view = None
self._labels = {}
self._on_selection_changed_fn = []
self._on_list_checkpoint_fn = kwargs.get("on_list_checkpoint_fn", None)
self._build_layout(width)
self.set_url(url)
self.set_multi_select(False)
self._on_list_checkpoint(supports_checkpointing=True,
has_checkpoints=True,
current_checkpoint=None,
multi_select=False)
def __del__(self):
self.destroy()
def destroy(self):
self._tree_view = None
self._labels = None
self._checkpoint_stack = None
self._root_frame = None
if self._checkpoint_model:
self._checkpoint_model.destroy()
self._checkpoint_model = None
self._checkpoint_delegate = None
self._on_selection_changed_fn.clear()
def set_multi_select(self, state:bool):
self._checkpoint_model.set_multi_select(state)
def set_url(self, url: str):
self._checkpoint_model.set_url(url)
def set_search(self, keywords):
self._checkpoint_model.set_search(keywords)
def add_on_selection_changed_fn(self, fn):
self._on_selection_changed_fn.append(fn)
def set_on_list_checkpoint_fn(self, fn):
self._on_list_checkpoint_fn = fn
def empty(self):
return self._checkpoint_model.empty()
def _build_layout(self, width):
self._root_frame = ui.Frame(visible=True, width=width)
with self._root_frame:
with ui.ZStack():
self._labels["cp_not_suppored"] = ui.Label("Checkpoints Not Supported.", style={"font_size": 18})
self._labels["multi_select"] = ui.Label("Checkpoints Cannot Be Displayed For Multiple Items.", style={"font_size": 18})
with ui.VStack():
self._checkpoint_stack = ui.VStack(visible=False, style=get_style())
with self._checkpoint_stack:
with ui.ScrollingFrame(
height=ui.Fraction(1),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="TreeView",
):
self._tree_view = ui.TreeView(
self._checkpoint_model,
root_visible=False,
header_visible=True,
delegate=self._checkpoint_delegate,
column_widths=[80, ui.Fraction(1), 20, 120, 100, 150],
)
# only allow selecting one checkpoint
def on_selection_changed(weak_self, selection):
weak_self = weak_self()
if not weak_self:
return
if len(selection) > 1:
selection = [selection[-1]]
if weak_self._tree_view.selection != selection:
weak_self._tree_view.selection = selection
for fn in weak_self._on_selection_changed_fn:
fn(selection[0] if selection else None)
self._tree_view.set_selection_changed_fn(
lambda selection, weak_self=weakref.ref(self): on_selection_changed(weak_self, selection)
)
self._labels["no_checkpoint"] = ui.Label("No Checkpoint")
def _on_list_checkpoint(self, supports_checkpointing, has_checkpoints, current_checkpoint, multi_select):
if multi_select:
self._root_frame.visible = True
self._checkpoint_stack.visible = False
self._labels["no_checkpoint"].visible = False
self._labels["cp_not_suppored"].visible = False
self._labels["multi_select"].visible = True
elif not supports_checkpointing:
self._checkpoint_stack.visible = False
self._root_frame.visible = True
self._labels["no_checkpoint"].visible = False
self._labels["cp_not_suppored"].visible = True
self._labels["multi_select"].visible = False
else:
self._checkpoint_stack.visible = has_checkpoints
self._root_frame.visible = has_checkpoints
self._labels["cp_not_suppored"].visible = False
self._labels["multi_select"].visible = False
self._labels["no_checkpoint"].visible = not has_checkpoints
# Must delay the selection for one frame so that treeview is synced with model for scroll to selection to work.
async def delayed_selection(weak_tree_view, callback):
tree_view = weak_tree_view()
if not tree_view:
return
await omni.kit.app.get_app().next_update_async()
if current_checkpoint:
tree_view.selection = [current_checkpoint]
else:
tree_view.selection = []
if callback:
callback(tree_view.selection)
asyncio.ensure_future(delayed_selection(weakref.ref(self._tree_view), self._on_list_checkpoint_fn))
| 6,876 | Python | 42.251572 | 135 | 0.566172 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/widget.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 asyncio
import weakref
import omni.kit.app
import omni.ui as ui
import carb
from typing import List, Callable
from . import LAYOUT_SLIM_VIEW, LAYOUT_TABLE_VIEW, LAYOUT_DEFAULT
from .checkpoints_model import CheckpointModel, CheckpointItem
from .table_view import CheckpointTableView
from .slim_view import CheckpointSlimView
from .context_menu import ContextMenu
from .style import get_style
class CheckpointWidget:
def __init__(self, url: str = "", show_none_entry=False, **kwargs):
"""
Build a CheckpointWidget. Called while constructing UI layout.
Args:
url (str): The url of the file to list checkpoints from.
show_none_entry (bool): Whether to show a dummy "head" entry to represent not using checkpoint.
"""
self._model = CheckpointModel(show_none_entry)
self._model.set_on_list_checkpoint_fn(self._on_list_checkpoint)
self._view = None
self._checkpoint_stack = None
self._notify_stack = None
self._labels = {}
self._context_menu = None
self._theme = carb.settings.get_settings().get("/persistent/app/window/uiStyle") or "NvidiaDark"
self._layout = kwargs.get("layout", LAYOUT_DEFAULT)
self._on_selection_changed_fn = []
self._on_list_checkpoint_fn = kwargs.get("on_list_checkpoint_fn", None)
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
self._build_ui()
self.set_url(url)
def __del__(self):
self.destroy()
def destroy(self):
self._view = None
self._labels = None
self._checkpoint_stack = None
self._notify_stack = None
if self._model:
self._model.destroy()
self._model = None
if self._context_menu:
self._context_menu.destroy()
self._content_menu = None
self._on_selection_changed_fn.clear()
def set_mouse_pressed_fn(self, mouse_pressed_fn: Callable):
self._mouse_pressed_fn = mouse_pressed_fn
def set_mouse_double_clicked_fn(self, mouse_double_clicked_fn: Callable):
self._mouse_double_clicked_fn = mouse_double_clicked_fn
def set_multi_select(self, state:bool):
self._model.set_multi_select(state)
def set_url(self, url: str):
self._model.set_url(url)
def set_search(self, keywords):
self._model.set_search(keywords)
def add_on_selection_changed_fn(self, fn):
self._on_selection_changed_fn.append(fn)
def set_on_list_checkpoint_fn(self, fn):
self._on_list_checkpoint_fn = fn
def empty(self):
return self._model.empty()
def _build_ui(self):
with ui.Frame(visible=True, style=get_style()):
with ui.ZStack():
self._notify_stack = ui.VStack(style_type_name_override="Notification", visible=False)
with self._notify_stack:
ui.Spacer(height=20)
with ui.HStack(height=0):
ui.Spacer()
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
thumbnail = f"{ext_path}/data/icons/{self._theme}/select_file.png"
ui.ImageWithProvider(thumbnail,
width=100, height=100,
fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT)
ui.Spacer()
ui.Spacer(height=20)
with ui.HStack(height=0):
ui.Spacer()
with ui.HStack(width=150):
self._labels["default"] = ui.Label(
"Select a file to see Checkpoints.",
word_wrap=True, style_type_name_override="Notification.Label", visible=True)
self._labels["cp_not_suppored"] = ui.Label(
"Location does not support Checkpoints.",
word_wrap=True, style_type_name_override="Notification.Label", visible=False)
self._labels["multi_select"] = ui.Label(
"Checkpoints Cannot Be Displayed For Multiple Items.",
word_wrap=True, style_type_name_override="Notification.Label", visible=False)
self._labels["no_checkpoint"] = ui.Label(
"Selected file has no Checkpoints.",
word_wrap=True, style_type_name_override="Notification.Label", visible=False)
ui.Spacer()
ui.Spacer()
self._checkpoint_stack = ui.VStack(visible=False)
with self._checkpoint_stack:
if self._layout in [LAYOUT_SLIM_VIEW, LAYOUT_DEFAULT]:
self._model.single_column = True
self._view = CheckpointSlimView(
self._model,
selection_changed_fn=self._on_selection_changed,
mouse_pressed_fn=self._on_mouse_pressed,
mouse_double_clicked_fn=self._on_mouse_double_clicked
)
else:
self._view = CheckpointTableView(
self._model,
selection_changed_fn=self._on_selection_changed,
mouse_pressed_fn=self._on_mouse_pressed,
mouse_double_clicked_fn=self._on_mouse_double_clicked
)
# Create popup menus
self._context_menu = ContextMenu()
self._on_list_checkpoint(supports_checkpointing=False,
has_checkpoints=False,
current_checkpoint=None,
multi_select=False)
def _on_selection_changed(self, selections: List[CheckpointItem]):
for selection_changed_fn in self._on_selection_changed_fn:
selection_changed_fn(selections[0] if selections else None)
def _on_mouse_pressed(self, button: int, key_mod: int, item: CheckpointItem):
if button == 1:
# Right mouse button: display context menu
self._context_menu.show(item)
if self._mouse_pressed_fn:
self.mouse_pressed_fn(button, key_mod, item)
def _on_mouse_double_clicked(self, button: int, key_mod: int, item: CheckpointItem):
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(button, key_mod, item)
def _on_list_checkpoint(self, supports_checkpointing, has_checkpoints, current_checkpoint, multi_select):
if has_checkpoints and not multi_select:
self._checkpoint_stack.visible = True
self._notify_stack.visible = False
else:
self._checkpoint_stack.visible = False
self._notify_stack.visible = True
if self._notify_stack.visible:
self._labels["default"].visible = False
if multi_select:
self._labels["no_checkpoint"].visible = False
self._labels["cp_not_suppored"].visible = False
self._labels["multi_select"].visible = True
elif not supports_checkpointing:
self._labels["no_checkpoint"].visible = False
self._labels["cp_not_suppored"].visible = True
self._labels["multi_select"].visible = False
else:
self._labels["no_checkpoint"].visible = not has_checkpoints
self._labels["cp_not_suppored"].visible = False
self._labels["multi_select"].visible = False
# Must delay the selection for one frame so that treeview is synced with model for scroll to selection to work.
async def delayed_selection(weak_view, callback):
view = weak_view()
if not view:
return
await omni.kit.app.get_app().next_update_async()
if current_checkpoint:
view.selection = [current_checkpoint]
else:
view.selection = []
if callback:
callback(view.selection)
asyncio.ensure_future(delayed_selection(weakref.ref(self._view), self._on_list_checkpoint_fn))
@staticmethod
def create_checkpoint_widget() -> 'CheckpointWidget':
widget = CheckpointWidget(show_none_entry=True)
return widget
@staticmethod
def on_model_url_changed(widget: 'CheckpointWidget', urls: List[str]):
if not widget:
return
if urls:
widget.set_url(urls[-1] or None)
widget.set_multi_select(len(urls) > 1)
else:
widget.set_url(None)
widget.set_multi_select(False)
@staticmethod
def delete_checkpoint_widget(widget: 'CheckpointWidget'):
if widget:
widget.destroy()
def add_context_menu(self, name: str, glyph: str, click_fn: Callable, enable_fn: Callable, index: int = -1) -> str:
"""
Adds menu item, with corresponding callbacks, to the context menu.
Args:
name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the context menu.
glyph (str): Associated glyph to display for this menu item.
click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature:
void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item.
enable_fn (Callable): Returns 1 to enable this menu item, 0 to disable, -1 to hide.
Function signature: bool fn(name: str, item: CheckpointItem).
index (int): The position that this menu item will be inserted to.
Returns:
str: Name of menu item if successful, None otherwise.
"""
if self._context_menu:
return self._context_menu.add_menu_item(name, glyph, click_fn, enable_fn, index=index)
return None
def delete_context_menu(self, name: str):
"""
Deletes the menu item, with the given name, from the context menu.
Args:
name (str): Name of the menu item (e.g. 'Open').
"""
if self._context_menu:
self._context_menu.delete_menu_item(name)
| 11,060 | Python | 42.03891 | 120 | 0.576582 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/checkpoint_combobox.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 asyncio
from functools import lru_cache
from typing import Optional
import omni.client
import omni.kit.app
import omni.ui as ui
import carb
from .widget import CheckpointWidget
from .style import get_style
from .checkpoints_model import CheckpointItem
@lru_cache()
def _get_down_arrow_icon_path(theme: str) -> str:
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
return f"{ext_path}/data/icons/{theme}/down_arrow.svg"
class CheckpointCombobox:
def __init__(
self,
absolute_asset_path,
on_selection_changed_fn,
width: ui.Length=ui.Pixel(100),
has_pre_spacer: bool=True,
popup_width: int=450,
visible: bool=True,
modal: bool=False,
):
self._get_comment_task = None
self._theme = carb.settings.get_settings().get("/persistent/app/window/uiStyle") or "NvidiaDark"
self._url = absolute_asset_path
self._width = width
self._has_pre_spacer = has_pre_spacer
self._popup_width = popup_width
self._visible = visible
self._modal = modal
self.__on_selection_changed_fn = on_selection_changed_fn
self.__container: Optional[ui.ZStack] = None
self.__checkpoint_field: Optional[ui.StringField] = None
self._build_checkpoint_combobox()
def destroy(self):
self._checkpoint_list_popup = None
self._search_field_value_change_sub = None
self._search_field_begin_edit_sub = None
self._search_field_end_edit_sub = None
if self._get_comment_task:
self._get_comment_task.cancel()
self._get_comment_task = None
@property
def visible(self) -> bool:
return self._visible
@visible.setter
def visible(self, value: bool) -> None:
self._visible = value
if self.__container:
self.__container.visible = value
@property
def url(self) -> str:
return self._url
@url.setter
def url(self, value: str) -> None:
self._url = value
if self.__checkpoint_field:
self.__config_field()
def _build_checkpoint_combobox(self):
self.__container = ui.ZStack(visible=self._visible, style=get_style())
with self.__container:
with ui.HStack():
if self._has_pre_spacer:
ui.Spacer()
with ui.ZStack(width=self._width):
self.__checkpoint_field = ui.StringField(read_only=True, enabled=False, style_type_name_override="ComboBox")
self.__config_field()
arrow_outer_size = 14
arrow_size = 10
with ui.HStack():
ui.Spacer()
with ui.VStack(width=arrow_outer_size):
ui.Spacer(height=6)
ui.Image(_get_down_arrow_icon_path(self._theme), width=arrow_size, height=arrow_size)
def on_mouse_pressed(field):
popup_width = self._popup_width if self._popup_width > 0 else field.computed_width
popup_height = 200
self._show_checkpoint_widget(
self._url,
field.screen_position_x - popup_width + field.computed_content_width,
field.screen_position_y,
field.computed_content_height,
popup_width,
popup_height,
)
self.__checkpoint_field.set_mouse_pressed_fn(
lambda x, y, b, m, field=self.__checkpoint_field: on_mouse_pressed(field)
)
return None
def __config_field(self):
(client_url, checkpoint) = self.__get_current_checkpoint()
self.__checkpoint_field.model.set_value(str(checkpoint) if checkpoint else "<head>")
if checkpoint:
async def get_comment():
result, entries = await omni.client.list_checkpoints_async(self._url)
if result:
for entry in entries:
if entry.relative_path == client_url.query:
self.__checkpoint_field.set_tooltip(entry.comment)
break
self._get_comment_task = asyncio.ensure_future(get_comment())
else:
self.__checkpoint_field.set_tooltip("<Not using Checkpoint>")
def __get_current_checkpoint(self):
checkpoint = 0
client_url = omni.client.break_url(self._url)
if client_url.query:
_, checkpoint = omni.client.get_branch_and_checkpoint_from_query(client_url.query)
return (client_url, checkpoint)
def __on_checkpoint_selection_changed(self, item: CheckpointItem):
if item:
self.url = item.get_full_url()
self._checkpoint_list_popup.visible = False
if self.__on_selection_changed_fn:
self.__on_selection_changed_fn(item)
def _build_list_popup(self, url):
with ui.VStack():
with ui.ZStack(height=0):
search_field = ui.StringField(style_type_name_override="ComboBox.Field")
search_label = ui.Label(" Search", name="hint", enabled=False, style_type_name_override="ComboBox.Field")
checkpoint_widget = CheckpointWidget(url, show_none_entry=True)
self._search_field_value_change_sub = search_field.model.subscribe_value_changed_fn(
lambda model: checkpoint_widget.set_search(model.get_value_as_string())
)
def begin_search(model):
search_label.visible = False
self._search_field_begin_edit_sub = search_field.model.subscribe_begin_edit_fn(begin_search)
def end_search(model):
if model.get_value_as_string() != "":
search_label.visible = True
self._search_field_end_edit_sub = search_field.model.subscribe_end_edit_fn(end_search)
checkpoint_widget.add_on_selection_changed_fn(self.__on_checkpoint_selection_changed)
def on_visibility_changed(visible):
checkpoint_widget.destroy()
self._checkpoint_list_popup.set_visibility_changed_fn(on_visibility_changed)
def _show_checkpoint_widget(self, url, pos_x, pos_y, pos_y_offset, width, height):
# If there is not enough space to expand the list downward, expand it upward instead
# TODO multi OS window?
window_height = ui.Workspace.get_main_window_height()
window_width = ui.Workspace.get_main_window_width()
if pos_y + height > window_height:
pos_y -= height
else:
pos_y += pos_y_offset
if self._modal:
flags = (ui.WINDOW_FLAGS_MODAL | ui.WINDOW_FLAGS_NO_BACKGROUND)
else:
flags = ui.WINDOW_FLAGS_POPUP
flags = (
flags
| ui.WINDOW_FLAGS_NO_TITLE_BAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
)
self._checkpoint_list_popup = ui.Window(
"Checkpoint Widget Window",
flags=flags,
padding_x=1,
padding_y=1,
width= window_width if self._modal else width,
height=window_height if self._modal else height,
)
self._checkpoint_list_popup.frame.set_style(get_style())
if self._modal:
# Modal window, simulate a popup window
# - background transparent
# - mouse press outside list will hide window
def __hide_list_popup():
self._checkpoint_list_popup.visible = False
with self._checkpoint_list_popup.frame:
with ui.HStack():
ui.Spacer(width=pos_x, mouse_pressed_fn=lambda x, y, b, a: __hide_list_popup())
with ui.VStack():
ui.Spacer(height=pos_y, mouse_pressed_fn=lambda x, y, b, a: __hide_list_popup())
self._build_list_popup(url)
ui.Spacer(height=window_height-pos_y-height, mouse_pressed_fn=lambda x, y, b, a: __hide_list_popup())
ui.Spacer(width=window_width-pos_x-width, mouse_pressed_fn=lambda x, y, b, a: __hide_list_popup())
else:
self._checkpoint_list_popup.position_x = pos_x
self._checkpoint_list_popup.position_y = pos_y
with self._checkpoint_list_popup.frame:
self._build_list_popup(url)
| 9,158 | Python | 39.171052 | 128 | 0.575126 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/tests/test_versioning.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
import omni.kit.app
import omni.client
from datetime import datetime
from unittest.mock import patch, Mock
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit.test_suite.helpers import get_test_data_path
from omni.kit.window.content_browser import get_content_window
import omni.ui as ui
import omni.kit.ui_test as ui_test
from omni.kit.widget.versioning import CheckpointWidget, CheckpointCombobox, LAYOUT_TABLE_VIEW, LAYOUT_SLIM_VIEW
from ..checkpoint_helper import CheckpointHelper
from ..checkpoints_model import CheckpointModel
class MockServer:
def __init__(self, cache_enabled=False, checkpoints_enabled=False, omniojects_enabled=False, username="", version=""):
self.cache_enabled = cache_enabled
self.checkpoints_enabled = checkpoints_enabled
self.omniojects_enabled = omniojects_enabled
self.username = username
self.version = version
class MockFileEntry:
def __init__(self, relative_path="", access="", flags="", size=0, modified_time="", created_time="", modified_by="", created_by="", version="", comment="<Test Node>"):
self.relative_path = relative_path
self.access = access
self.flags = flags
self.size = size
self.modified_time = modified_time
self.created_time = created_time
self.modified_by = modified_by
self.created_by = created_by
self.version = version
self.comment = comment
class _TestBase(AsyncTestCase):
# Before running each test
async def setUp(self):
self._mock_server = MockServer(
cache_enabled=False,
checkpoints_enabled=True,
omniojects_enabled=True,
username="[email protected]",
version="TestServer"
)
self._mock_file_entries = [
MockFileEntry(
access=1,
created_by="[email protected]",
created_time=datetime.min.time(),
flags=513,
modified_by="[email protected]",
modified_time=datetime.min.time(),
relative_path="&1",
size=160,
version=12023408,
comment="<1>"
),
MockFileEntry(
access=1,
created_by="[email protected]",
created_time=datetime.min.time(),
flags=513,
modified_by="[email protected]",
modified_time=datetime.min.time(),
relative_path="&2",
size=260,
version=12023408,
comment="<2>"
)
]
# After running each test
async def tearDown(self):
pass
async def _mock_get_server_info_async(self, url: str):
return omni.client.Result.OK, self._mock_server
async def _mock_list_checkpoints_async(self, query: str):
return omni.client.Result.OK, self._mock_file_entries
def _mock_checkpoint_query(self, query: str):
return (None, 1)
def _mock_copy_async(self, path, filepath, message=""):
return omni.client.Result.OK
def _mock_on_file_change(self, result):
pass
def _mock_resolve_subscribe(self, url, urls, cb1, cb2):
cb2(omni.client.Result.OK, None, self._mock_file_entries[0], None)
class TestVersioningWindow(_TestBase):
async def test_versioning_widget(self):
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async),\
patch("omni.client.list_checkpoints_async", side_effect=self._mock_list_checkpoints_async),\
patch("omni.client.copy_async", side_effect=self._mock_copy_async) as _mock,\
patch("omni.client.resolve_subscribe_with_callback", side_effect=self._mock_resolve_subscribe),\
patch.object(CheckpointModel, "_on_file_change_event", side_effect=self._mock_on_file_change) as _mock_file_change:
under_test = get_content_window()
# TODO: Filebrowser file selection not working for grid_view
under_test.toggle_grid_view(False)
test_path = get_test_data_path(__name__, "4Lights.usda")
await under_test.select_items_async(test_path)
await ui_test.wait_n_updates(2)
# Confirm that checkpoint widget displays the expected checkpoint entry
cp_widget = under_test.get_checkpoint_widget()
cp_model = cp_widget._model
cp_items = cp_model.get_item_children(None)
self.assertTrue(len(cp_items))
# Last item is the latest
self.assertEqual(cp_items[-1].entry, self._mock_file_entries[0])
# test restore
cp_model.restore_checkpoint("omniverse://dummy.usd", "omniverse://dummy.usd?&2")
await ui_test.wait_n_updates(5)
_mock.assert_called_once_with("omniverse://dummy.usd?&2", "omniverse://dummy.usd",
message="Restored checkpoint #2")
# OMFP-3807: restore should trigger file change,check here
_mock_file_change.assert_called()
async def test_versioning_widget_table_view(self):
mock_double_click = Mock()
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async),\
patch("omni.client.list_checkpoints_async", side_effect=self._mock_list_checkpoints_async):
url = get_test_data_path(__name__, "4Lights.usda")
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
window = ui.Window("TestTableView", width=800, height=500, flags=window_flags)
with window.frame:
with ui.VStack():
widget = CheckpointWidget(url, layout=LAYOUT_TABLE_VIEW)
widget.set_url(url)
widget.add_context_menu(
"Foo",
"pencil.svg",
Mock(),
None,
)
widget.add_context_menu(
"Bar",
"pencil.svg",
Mock(),
None,
)
widget.set_mouse_double_clicked_fn(lambda b, k, cp: mock_double_click(cp))
window.focus()
await ui_test.wait_n_updates(5)
cp_items = widget._model.get_item_children(None)
# test that table view displays our test file entry correctly
self.assertFalse(widget.empty())
item = cp_items[-1]
# Last item is the latest
self.assertEqual(item.entry, self._mock_file_entries[0])
self.assertEqual(item.comment, "<1>")
self.assertTrue(item.get_full_url().endswith(f"4Lights.usda?&1"))
self.assertEqual(item.get_relative_path(), "&1")
# test search filtering
treeview_item = ui_test.find("TestTableView//Frame/**/Label[*].text=='1'")
self.assertIsNotNone(treeview_item)
widget.set_search("2")
await ui_test.human_delay()
treeview_item = ui_test.find("TestTableView//Frame/**/Label[*].text=='1'")
self.assertIsNone(treeview_item)
# restore keywords back
widget.set_search("")
# test double click
treeview_item = ui_test.find("TestTableView//Frame/**/Label[*].text=='1'")
self.assertIsNotNone(treeview_item)
await treeview_item.double_click()
mock_double_click.assert_called_once_with(item)
# test context menu
await treeview_item.right_click()
await ui_test.human_delay()
await ui_test.select_context_menu("Foo")
# test delete context menu
widget.delete_context_menu("Foo")
await ui_test.human_delay()
await treeview_item.right_click()
menu = await ui_test.get_context_menu()
self.assertEqual(menu['_'], ['Bar'])
async def test_checkpoint_combo_box(self):
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async),\
patch("omni.client.list_checkpoints_async", side_effect=self._mock_list_checkpoints_async),\
patch("omni.client.get_branch_and_checkpoint_from_query", side_effect=self._mock_checkpoint_query):
url = "omniverse://dummy.usd"
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
window = ui.Window("TestComboBox", width=800, height=500, flags=window_flags)
with window.frame:
with ui.VStack():
combo_box = CheckpointCombobox(url, lambda sel: print(f"Selected: {sel.get_full_url()}"))
window.focus()
await ui_test.wait_n_updates(5)
# test visible
self.assertTrue(combo_box.visible)
combo_box.visible = False
self.assertFalse(combo_box.visible)
combo_box.visible = True
# test url
self.assertEqual(url, combo_box.url)
url = "omniverse://dummy.usd?1"
combo_box.url = url
self.assertEqual(url, combo_box.url)
# test show checkpoints
field = ui_test.find_all("TestComboBox//Frame/**/StringField[*]")[0]
self.assertIsNotNone(field)
await field.click()
await ui_test.human_delay()
self.assertTrue(combo_box._checkpoint_list_popup.visible)
class TestCheckpointHelper(_TestBase):
async def test_extract_server_from_url(self):
self.assertFalse(CheckpointHelper.extract_server_from_url(""))
self.assertEqual(CheckpointHelper.extract_server_from_url("omniverse://dummy/foo.bar"), "omniverse://dummy")
async def test_is_checkpoint_enabled(self):
enabled = await CheckpointHelper.is_checkpoint_enabled_async("")
self.assertFalse(enabled)
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async) as _mock:
enabled = await CheckpointHelper.is_checkpoint_enabled_async("omniverse://dummy/foo.bar")
self.assertTrue(enabled)
_mock.assert_called_once()
_mock.reset_mock()
# test that server result is cached
self.assertTrue("omniverse://dummy" in CheckpointHelper.server_cache)
enabled = await CheckpointHelper.is_checkpoint_enabled_async("omniverse://dummy/baz.abc")
self.assertTrue(enabled)
_mock.assert_not_called()
async def test_is_checkpoint_enabled_with_callback(self):
callback = Mock()
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async):
CheckpointHelper.is_checkpoint_enabled_with_callback("omniverse://dummy/foo.bar", callback)
await ui_test.wait_n_updates(2)
callback.assert_called_once_with("omniverse://dummy", True)
| 11,526 | Python | 41.692592 | 171 | 0.603418 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/tests/__init__.py | from .test_versioning import TestCheckpointHelper, TestVersioningWindow
| 72 | Python | 35.499982 | 71 | 0.888889 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_examples.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestDocExamples(TestClass):
@tc_logger
def test_usdrt_one_property(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example one property RT
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
path = "/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"
prim = stage.GetPrimAtPath(path)
attr = prim.GetAttribute(UsdGeom.Tokens.primvarsDisplayColor)
# Get the value of displayColor on White_Wall_Back,
# which is mid-gray on this stage
result = attr.Get()
self.assertEqual(len(result), 1)
self.assertEqual(result[0], Gf.Vec3f(0.5, 0.5, 0.5))
# Set the value of displayColor to red,
# and verify the change by getting the value
attr.Set(Vt.Vec3fArray([Gf.Vec3f(1, 0, 0)]))
result = attr.Get()
self.assertEqual(len(result), 1)
self.assertEqual(result[0], Gf.Vec3f(1, 0, 0))
# End example one property RT
@tc_logger
def test_usd_one_property(self):
from pxr import Gf, Sdf, Usd, UsdUtils, Vt
# FIXME - Fabric is holding notices to a stage in the cache
# and gets hung here if the cache isn't cleared first - How?
UsdUtils.StageCache.Get().Clear()
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example one property USD
from pxr import Gf, Sdf, Usd, Vt
path = "/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"
prim = stage.GetPrimAtPath(path)
attr = prim.GetAttribute("primvars:displayColor")
# Get the value of displayColor on White_Wall_Back,
# which is mid-gray on this stage
result = attr.Get()
self.assertEqual(len(result), 1)
self.assertEqual(result[0], Gf.Vec3f(0.5, 0.5, 0.5))
# Set the value of displayColor to red,
# and verify the change by getting the value
attr.Set(Vt.Vec3fArray([Gf.Vec3f(1, 0, 0)]))
result = attr.Get()
self.assertEqual(len(result), 1)
self.assertEqual(result[0], Gf.Vec3f(1, 0, 0))
# End example one property USD
@tc_logger
def test_usdrt_many_property(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example many prims RT
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
red = Vt.Vec3fArray([Gf.Vec3f(1, 0, 0)])
meshPaths = stage.GetPrimsWithTypeName("Mesh")
for meshPath in meshPaths:
prim = stage.GetPrimAtPath(meshPath)
if prim.HasAttribute(UsdGeom.Tokens.primvarsDisplayColor):
prim.GetAttribute(UsdGeom.Tokens.primvarsDisplayColor).Set(red)
# End example many prims RT
@tc_logger
def test_usdrt_abstract_schema_query(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example abstract query
from usdrt import Gf, Sdf, Usd, UsdGeom
gPrimPaths = stage.GetPrimsWithTypeName("Gprim")
attr = UsdGeom.Tokens.doubleSided
doubleSided = []
for gPrimPath in gPrimPaths:
prim = stage.GetPrimAtPath(gPrimPath)
if prim.HasAttribute(attr) and prim.GetAttribute(attr).Get():
doubleSided.append(prim)
@tc_logger
def test_usd_many_property(self):
from pxr import Gf, Sdf, Usd, UsdUtils
# FIXME - Fabric is holding notices to a stage in the cache
# and gets hung here if the cache isn't cleared first - How?
UsdUtils.StageCache.Get().Clear()
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example many prims USD
from pxr import Gf, Usd, UsdGeom, Vt
red = Vt.Vec3fArray([Gf.Vec3f(1, 0, 0)])
for prim in stage.Traverse():
if prim.GetTypeName() == "Mesh":
prim.GetAttribute(UsdGeom.Tokens.primvarsDisplayColor).Set(red)
# End example many prims USD
@tc_logger
def test_usdrt_one_relationship(self):
from usdrt import Gf, Sdf, Usd, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example relationship RT
from usdrt import Gf, Sdf, Usd, UsdGeom
path = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"
prim = stage.GetPrimAtPath(path)
rel = prim.GetRelationship(UsdShade.Tokens.materialBinding)
# The currently bound Material prim, and a new
# Material prim to bind
old_mtl = "/Cornell_Box/Root/Looks/Green1SG"
new_mtl = "/Cornell_Box/Root/Looks/Red1SG"
# Get the first target
self.assertTrue(rel.HasAuthoredTargets())
mtl_path = rel.GetTargets()[0]
self.assertEqual(mtl_path, old_mtl)
# Update the relationship to target a different material
rel.SetTargets([new_mtl])
updated_path = rel.GetTargets()[0]
self.assertEqual(updated_path, new_mtl)
# End example relationship RT
@tc_logger
def test_usd_one_relationship(self):
from pxr import Gf, Sdf, Usd, UsdUtils, Vt
# FIXME - Fabric is holding notices to a stage in the cache
# and gets hung here if the cache isn't cleared first - How?
UsdUtils.StageCache.Get().Clear()
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# Begin example relationship USD
from pxr import Gf, Sdf, Usd
path = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"
prim = stage.GetPrimAtPath(path)
rel = prim.GetRelationship("material:binding")
# The currently bound Material prim, and a new
# Material prim to bind
old_mtl = "/Cornell_Box/Root/Looks/Green1SG"
new_mtl = "/Cornell_Box/Root/Looks/Red1SG"
# Get the first target
self.assertTrue(rel.HasAuthoredTargets())
mtl_path = rel.GetTargets()[0]
self.assertEqual(mtl_path, old_mtl)
# Update the relationship to target a different material
rel.SetTargets([new_mtl])
updated_path = rel.GetTargets()[0]
self.assertEqual(updated_path, new_mtl)
# End example relationship USD
@tc_logger
def test_usd_usdrt_interop(self):
if True:
# FIXME - crash on Linux here on TC why?
return
from pxr import UsdUtils
# Paranoia - see above test
UsdUtils.StageCache.Get().Clear()
# Begin example interop
from pxr import Sdf, Usd, UsdUtils
from usdrt import Usd as RtUsd
usd_stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage_id = UsdUtils.StageCache.Get().Insert(usd_stage)
stage = RtUsd.Stage.Attach(usd_stage_id.ToLongInt())
mesh_paths = stage.GetPrimsWithTypeName("Mesh")
for mesh_path in mesh_paths:
# strings can be implicitly converted to SdfPath in Python
usd_prim = usd_stage.GetPrimAtPath(str(mesh_path))
if usd_prim.HasVariantSets():
print(f"Found Mesh with variantSet: {mesh_path}")
# End example interop
@tc_logger
def test_vt_array_gpu(self):
if platform.processor() == "aarch64":
return
import weakref
try:
import warp as wp
except ImportError:
if TestClass is omni.kit.test.AsyncTestCase:
# warp not available for testing in kit at this time
return
raise
# Begin example GPU
import numpy as np
import warp as wp
from usdrt import Gf, Sdf, Usd, Vt
def warp_array_from_cuda_array_interface(a):
cai = a.__cuda_array_interface__
return wp.types.array(
dtype=wp.vec3,
length=cai["shape"][0],
capacity=cai["shape"][0] * wp.types.type_size_in_bytes(wp.vec3),
ptr=cai["data"][0],
device="cuda",
owner=False,
requires_grad=False,
)
stage = Usd.Stage.CreateInMemory("test.usda")
prim = stage.DefinePrim(Sdf.Path("/prim"))
attr = prim.CreateAttribute("points", Sdf.ValueTypeNames.Point3fArray, True)
# First create a warp array from numpy
points = np.zeros(shape=(1024, 3), dtype=np.float32)
for i in range(1024):
for j in range(3):
points[i][j] = i * 3 + j
warp_points = wp.array(points, device="cpu")
with wp.ScopedCudaGuard():
gpu_warp_points = warp_points.to("cuda")
warp_ref = weakref.ref(gpu_warp_points)
# Create a VtArray from a warp array
vt_points = Vt.Vec3fArray(gpu_warp_points)
# Set the Fabric attribute which will make a CUDA copy
# from warp to Fabric
attr.Set(vt_points)
wp.synchronize()
# Retrieve a new Fabric VtArray from USDRT
new_vt_points = attr.Get()
self.assertTrue(new_vt_points.HasFabricGpuData())
# Create a warp array from the VtArray
new_warp_points = warp_array_from_cuda_array_interface(new_vt_points)
# Delete the fabric VtArray to ensure the data was
# really copied into warp
del new_vt_points
# Convert warp points back to numpy
new_points = new_warp_points.numpy()
# Now compare the round-trip through USDRT and GPU was a success
self.assertEqual(points.shape, new_points.shape)
for i in range(1024):
for j in range(3):
self.assertEqual(points[i][j], new_points[i][j])
# End example GPU
| 11,265 | Python | 30.915014 | 84 | 0.613848 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_path.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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.
"""
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
import os
import pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
def get_path_parts():
from usdrt import Sdf
parts = [
Sdf.Path("/Cornell_Box"),
Sdf.Path("/Cornell_Box/Root"),
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"),
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall"),
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"),
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices"),
]
return parts
class TestSdfPath(TestClass):
@tc_logger
def test_get_prefixes(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = get_path_parts()
prefixes = path.GetPrefixes()
self.assertEqual(prefixes, expected)
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = "Sdf.Path('/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices')"
self.assertEqual(repr(path), expected)
@tc_logger
def test_str_representation(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices"
self.assertEqual(str(path), expected)
@tc_logger
def test_implicit_string_conversion(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
primFromString = stage.GetPrimAtPath("/Cornell_Box")
self.assertTrue(primFromString)
@tc_logger
def test_get_string(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices"
self.assertEqual(path.GetString(), expected)
self.assertEqual(path.pathString, expected)
@tc_logger
def test_get_text(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = "/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices"
self.assertEqual(path.GetText(), expected)
@tc_logger
def test_get_name_token(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/foo/bar/baz").name, "baz")
self.assertEqual(Sdf.Path("/foo").name, "foo")
self.assertEqual(Sdf.Path.emptyPath.name, "")
self.assertEqual(Sdf.Path("/foo/bar/baz.prop").name, "prop")
self.assertEqual(Sdf.Path("/foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
self.assertEqual(Sdf.Path("foo/bar/baz").name, "baz")
self.assertEqual(Sdf.Path("foo").name, "foo")
self.assertEqual(Sdf.Path("foo/bar/baz.prop").name, "prop")
self.assertEqual(Sdf.Path("foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
@tc_logger
def test_get_prim_path(self):
from usdrt import Sdf, Usd
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG")
self.assertEqual(path.GetPrimPath(), expected)
@tc_logger
def test_path_element_count(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/").pathElementCount, 0)
self.assertEqual(Sdf.Path("/abc").pathElementCount, 1)
self.assertEqual(Sdf.Path("/abc/xyz").pathElementCount, 2)
@tc_logger
def test_get_name(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/foo/bar/baz").name, "baz")
self.assertEqual(Sdf.Path("/foo").name, "foo")
self.assertEqual(Sdf.Path.emptyPath.name, "")
self.assertEqual(Sdf.Path("/foo/bar/baz.prop").name, "prop")
self.assertEqual(Sdf.Path("/foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
self.assertEqual(Sdf.Path("foo/bar/baz").name, "baz")
self.assertEqual(Sdf.Path("foo").name, "foo")
self.assertEqual(Sdf.Path("foo/bar/baz.prop").name, "prop")
self.assertEqual(Sdf.Path("foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
@tc_logger
def test_path_queries(self):
from usdrt import Sdf
absRoot = Sdf.Path("/")
absolute = Sdf.Path("/absolute/path/test")
relative = Sdf.Path("../relative/path/test")
prim = Sdf.Path("/this/is/a/prim/path")
rootPrim = Sdf.Path("/root")
propPath = Sdf.Path("/this/path/has.propPart")
namespaceProp = Sdf.Path("/this/path/has.namespaced(self):propPart")
self.assertTrue(absolute.IsAbsolutePath())
self.assertFalse(relative.IsAbsolutePath())
self.assertTrue(absRoot.IsAbsoluteRootPath())
self.assertFalse(absolute.IsAbsoluteRootPath())
self.assertFalse(Sdf.Path.emptyPath.IsAbsoluteRootPath())
self.assertTrue(prim.IsPrimPath())
self.assertFalse(propPath.IsPrimPath())
self.assertFalse(Sdf.Path.emptyPath.IsPrimPath())
self.assertTrue(absolute.IsAbsoluteRootOrPrimPath())
self.assertTrue(prim.IsAbsoluteRootOrPrimPath())
self.assertFalse(relative.IsAbsoluteRootOrPrimPath())
self.assertFalse(propPath.IsAbsoluteRootOrPrimPath())
self.assertFalse(Sdf.Path.emptyPath.IsAbsoluteRootOrPrimPath())
self.assertTrue(rootPrim.IsRootPrimPath())
self.assertFalse(prim.IsRootPrimPath())
self.assertFalse(Sdf.Path.emptyPath.IsRootPrimPath())
self.assertTrue(propPath.IsPropertyPath())
self.assertFalse(prim.IsPropertyPath())
self.assertFalse(Sdf.Path.emptyPath.IsPropertyPath())
self.assertTrue(propPath.IsPrimPropertyPath())
self.assertFalse(prim.IsPrimPropertyPath())
self.assertFalse(Sdf.Path.emptyPath.IsPrimPropertyPath())
self.assertTrue(namespaceProp.IsNamespacedPropertyPath())
self.assertFalse(propPath.IsNamespacedPropertyPath())
self.assertFalse(prim.IsNamespacedPropertyPath())
self.assertFalse(Sdf.Path.emptyPath.IsNamespacedPropertyPath())
self.assertTrue(Sdf.Path.emptyPath.IsEmpty())
self.assertFalse(propPath.IsEmpty())
self.assertFalse(prim.IsEmpty())
@tc_logger
def test_operators(self):
from usdrt import Sdf
# Test lessthan
self.assertTrue(Sdf.Path("aaa") < Sdf.Path("aab"))
self.assertTrue(not Sdf.Path("aaa") < Sdf.Path())
self.assertTrue(Sdf.Path("/") < Sdf.Path("/a"))
# string conversion
self.assertEqual(Sdf.Path("foo"), "foo")
self.assertEqual("foo", Sdf.Path("foo"))
self.assertNotEqual(Sdf.Path("foo"), "bar")
self.assertNotEqual("bar", Sdf.Path("foo"))
@tc_logger
def test_contains_property_elements(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
self.assertTrue(path.ContainsPropertyElements())
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG")
self.assertFalse(path.ContainsPropertyElements())
@tc_logger
def test_get_parent_path(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/foo/bar/baz").GetParentPath(), Sdf.Path("/foo/bar"))
self.assertEqual(Sdf.Path("/foo").GetParentPath(), Sdf.Path("/"))
self.assertEqual(Sdf.Path.emptyPath.GetParentPath(), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path("/foo/bar/baz.prop").GetParentPath(), Sdf.Path("/foo/bar/baz"))
self.assertEqual(Sdf.Path("foo/bar/baz").GetParentPath(), Sdf.Path("foo/bar"))
# self.assertEqual(Sdf.Path("foo").GetParentPath(), Sdf.Path("."))
self.assertEqual(Sdf.Path("foo/bar/baz.prop").GetParentPath(), Sdf.Path("foo/bar/baz"))
@tc_logger
def test_get_prim_path(self):
from usdrt import Sdf
primPath = Sdf.Path("/A/B/C").GetPrimPath()
self.assertEqual(primPath, Sdf.Path("/A/B/C"))
primPath = Sdf.Path("/A/B/C.foo").GetPrimPath()
self.assertEqual(primPath, Sdf.Path("/A/B/C"))
primPath = Sdf.Path("/A/B/C.foo:bar:baz").GetPrimPath()
self.assertEqual(primPath, Sdf.Path("/A/B/C"))
@tc_logger
def test_get_absolute_root_or_prim_path(self):
from usdrt import Sdf
self.assertTrue(Sdf.Path.absoluteRootPath, Sdf.Path("/"))
@tc_logger
def test_append_path(self):
from usdrt import Sdf
# append to empty path -> empty path
# with self.assertRaises(Tf.ErrorException):
# Sdf.Path().AppendPath( Sdf.Path() )
# with self.assertRaises(Tf.ErrorException):
# Sdf.Path().AppendPath( Sdf.Path('A') )
# append to root/prim path
self.assertEqual(Sdf.Path("/").AppendPath(Sdf.Path("A")), Sdf.Path("/A"))
self.assertEqual(Sdf.Path("/A").AppendPath(Sdf.Path("B")), Sdf.Path("/A/B"))
# append empty to root/prim path -> no change
# with self.assertRaises(Tf.ErrorException):
# Sdf.Path('/').AppendPath( Sdf.Path() )
# with self.assertRaises(Tf.ErrorException):
# Sdf.Path('/A').AppendPath( Sdf.Path() )
@tc_logger
def test_append_child(self):
from usdrt import Sdf
aPath = Sdf.Path("/foo")
self.assertEqual(aPath.AppendChild("bar"), Sdf.Path("/foo/bar"))
aPath = Sdf.Path("foo")
self.assertEqual(aPath.AppendChild("bar"), Sdf.Path("foo/bar"))
aPath = Sdf.Path("/foo.prop")
self.assertEqual(aPath.AppendChild("bar"), Sdf.Path.emptyPath)
@tc_logger
def test_append_property(self):
from usdrt import Sdf
aPath = Sdf.Path("/foo")
self.assertEqual(aPath.AppendProperty("prop"), Sdf.Path("/foo.prop"))
self.assertEqual(aPath.AppendProperty("prop:foo:bar"), Sdf.Path("/foo.prop:foo:bar"))
aPath = Sdf.Path("/foo.prop")
self.assertEqual(aPath.AppendProperty("prop2"), Sdf.Path.emptyPath)
self.assertEqual(aPath.AppendProperty("prop2:foo:bar"), Sdf.Path.emptyPath)
@tc_logger
def test_replace_prefix(self):
from usdrt import Sdf
# Test HasPrefix
self.assertFalse(Sdf.Path.emptyPath.HasPrefix("A"))
self.assertFalse(Sdf.Path("A").HasPrefix(Sdf.Path.emptyPath))
aPath = Sdf.Path("/Chars/Buzz_1/LArm.FB")
self.assertEqual(aPath.HasPrefix("/Chars/Buzz_1"), True)
self.assertEqual(aPath.HasPrefix("Buzz_1"), False)
# Replace aPath's prefix and get a new path
bPath = aPath.ReplacePrefix("/Chars/Buzz_1", "/Chars/Buzz_2")
self.assertEqual(bPath, Sdf.Path("/Chars/Buzz_2/LArm.FB"))
# Specify a bogus prefix to replace and get an empty path
cPath = bPath.ReplacePrefix("/BadPrefix/Buzz_2", "/ReleasedChars/Buzz_2")
self.assertEqual(cPath, bPath)
# ReplacePrefix with an empty old or new prefix returns an empty path.
self.assertEqual(Sdf.Path("/A/B").ReplacePrefix(Sdf.Path.emptyPath, "/C"), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path("/A/B").ReplacePrefix("/A", Sdf.Path.emptyPath), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path.emptyPath.ReplacePrefix(Sdf.Path.emptyPath, "/C"), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path.emptyPath.ReplacePrefix("/A", Sdf.Path.emptyPath), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path.emptyPath.ReplacePrefix("/A", "/B"), Sdf.Path.emptyPath)
self.assertEqual(
Sdf.Path("/Cone").ReplacePrefix(Sdf.Path.absoluteRootPath, Sdf.Path("/World")), Sdf.Path("/World/Cone")
)
@tc_logger
def test_get_common_prefix(self):
from usdrt import Sdf
# prefix exists
self.assertEqual(
Sdf.Path("/prefix/is/common/one").GetCommonPrefix(Sdf.Path("/prefix/is/common/two")),
Sdf.Path("/prefix/is/common"),
)
self.assertEqual(
Sdf.Path("/prefix/is/common.one").GetCommonPrefix(Sdf.Path("/prefix/is/common.two")),
Sdf.Path("/prefix/is/common"),
)
self.assertEqual(
Sdf.Path("/prefix/is/common.oneone").GetCommonPrefix(Sdf.Path("/prefix/is/common.one")),
Sdf.Path("/prefix/is/common"),
)
# paths are the same
self.assertEqual(
Sdf.Path("/paths/are/the/same").GetCommonPrefix(Sdf.Path("/paths/are/the/same")),
Sdf.Path("/paths/are/the/same"),
)
# empty path, both parts
self.assertEqual(Sdf.Path.emptyPath.GetCommonPrefix(Sdf.Path("/foo/bar")), Sdf.Path.emptyPath)
self.assertEqual(Sdf.Path("/foo/bar").GetCommonPrefix(Sdf.Path.emptyPath), Sdf.Path.emptyPath)
# no common prefix
self.assertEqual(Sdf.Path("/a/b/c").GetCommonPrefix(Sdf.Path("/d/e/f")), Sdf.Path.absoluteRootPath)
# absolute root path
self.assertEqual(Sdf.Path.GetCommonPrefix(Sdf.Path("/"), Sdf.Path("/World")), Sdf.Path.absoluteRootPath)
# make sure its valid
self.assertEqual(Sdf.Path.GetCommonPrefix(Sdf.Path("/W"), Sdf.Path("/World/Cube")), Sdf.Path.absoluteRootPath)
self.assertEqual(Sdf.Path.GetCommonPrefix(Sdf.Path("/A"), Sdf.Path("/B")), Sdf.Path.absoluteRootPath)
@tc_logger
def test_remove_common_suffix(self):
from usdrt import Sdf
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/X/Y/Z")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A/B/C"))
self.assertEqual(r2, Sdf.Path("/X/Y/Z"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B/C"))
self.assertEqual(r2, Sdf.Path("/X/Y/Z"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("X/Y/Z")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B/C"))
self.assertEqual(r2, Sdf.Path("X/Y/Z"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B/C"))
self.assertEqual(r2, Sdf.Path("X/Y/Z"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/X/Y/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/X/Y"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/X/Y"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("X/Y/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("X/Y"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("X/Y"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("/X/Y/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("/X/Y"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("/X/Y"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/X/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A"))
self.assertEqual(r2, Sdf.Path("/X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A"))
self.assertEqual(r2, Sdf.Path("/X"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("X/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("X"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("/X/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("/X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("/X"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/A/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/"))
self.assertEqual(r2, Sdf.Path("/"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A"))
self.assertEqual(r2, Sdf.Path("/A"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("A/B/C")
# (r1, r2) = aPath.RemoveCommonSuffix(bPath)
# self.assertEqual(r1, Sdf.Path('.'))
# self.assertEqual(r2, Sdf.Path('.'))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("A"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("/A/B/C")
# (r1, r2) = aPath.RemoveCommonSuffix(bPath)
# self.assertEqual(r1, Sdf.Path('.'))
# self.assertEqual(r2, Sdf.Path('/'))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A"))
self.assertEqual(r2, Sdf.Path("/A"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/X/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/X"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("X/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("X"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("X"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/B/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A"))
self.assertEqual(r2, Sdf.Path("/"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/B"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("B/C")
# (r1, r2) = aPath.RemoveCommonSuffix(bPath)
# self.assertEqual(r1, Sdf.Path('A'))
# self.assertEqual(r2, Sdf.Path('.'))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("B"))
aPath = Sdf.Path("/A/B/C")
bPath = Sdf.Path("/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("/A/B"))
self.assertEqual(r2, Sdf.Path("/"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("/A/B/C"))
self.assertEqual(r2, Sdf.Path("/C"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("C")
# (r1, r2) = aPath.RemoveCommonSuffix(bPath)
# self.assertEqual(r1, Sdf.Path('A/B'))
# self.assertEqual(r2, Sdf.Path('.'))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B/C"))
self.assertEqual(r2, Sdf.Path("C"))
aPath = Sdf.Path("A/B/C")
bPath = Sdf.Path("/C")
(r1, r2) = aPath.RemoveCommonSuffix(bPath)
self.assertEqual(r1, Sdf.Path("A/B"))
self.assertEqual(r2, Sdf.Path("/"))
(r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
self.assertEqual(r1, Sdf.Path("A/B/C"))
self.assertEqual(r2, Sdf.Path("/C"))
@tc_logger
def test_replace_name(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path("/foo/bar/baz").ReplaceName("foo"), Sdf.Path("/foo/bar/foo"))
self.assertEqual(Sdf.Path("/foo").ReplaceName("bar"), Sdf.Path("/bar"))
self.assertEqual(Sdf.Path("/foo/bar/baz.prop").ReplaceName("attr"), Sdf.Path("/foo/bar/baz.attr"))
self.assertEqual(
Sdf.Path("/foo/bar/baz.prop").ReplaceName("attr:argle:bargle"), Sdf.Path("/foo/bar/baz.attr:argle:bargle")
)
self.assertEqual(Sdf.Path("/foo/bar/baz.prop:argle:bargle").ReplaceName("attr"), Sdf.Path("/foo/bar/baz.attr"))
self.assertEqual(
Sdf.Path("/foo/bar/baz.prop:argle:bargle").ReplaceName("attr:foo:fa:raw"),
Sdf.Path("/foo/bar/baz.attr:foo:fa:raw"),
)
self.assertEqual(Sdf.Path("foo/bar/baz").ReplaceName("foo"), Sdf.Path("foo/bar/foo"))
self.assertEqual(Sdf.Path("foo").ReplaceName("bar"), Sdf.Path("bar"))
self.assertEqual(Sdf.Path("foo/bar/baz.prop").ReplaceName("attr"), Sdf.Path("foo/bar/baz.attr"))
self.assertEqual(
Sdf.Path("foo/bar/baz.prop").ReplaceName("attr:argle:bargle"), Sdf.Path("foo/bar/baz.attr:argle:bargle")
)
# STATIC TESTS
@tc_logger
def test_empty_path(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path.emptyPath, Sdf.Path(""))
self.assertEqual(Sdf.Path.emptyPath, Sdf.Path())
@tc_logger
def test_absolute_root_path(self):
from usdrt import Sdf
self.assertEqual(Sdf.Path.absoluteRootPath, Sdf.Path("/"))
@tc_logger
def test_hashing(self):
from usdrt import Sdf
test_paths = get_path_parts()
d = {}
for i in enumerate(test_paths):
d[i[1]] = i[0]
for i in enumerate(test_paths):
self.assertEqual(d[i[1]], i[0])
class TestSdfPathAncestorsRange(TestClass):
@tc_logger
def test_iterator(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = get_path_parts()
expected.reverse()
i = 0
for ancestor in path.GetAncestorsRange():
self.assertEqual(ancestor, expected[i])
i += 1
@tc_logger
def test_get_path(self):
from usdrt import Sdf
path = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.indices")
expected = get_path_parts()
expected.reverse()
ar = path.GetAncestorsRange()
self.assertEqual(ar.GetPath(), path)
| 25,107 | Python | 37.509202 | 119 | 0.627753 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_usd_timecode.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 math
import os
import pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdTimeCode(TestClass):
@tc_logger
def test_timecode(self):
from usdrt import Usd
# ctor
t0 = Usd.TimeCode()
self.assertTrue(t0)
self.assertEqual(t0.GetValue(), 0.0)
t1 = Usd.TimeCode(1.0)
self.assertTrue(t1)
self.assertEqual(t1.GetValue(), 1.0)
nan = Usd.TimeCode(float("nan"))
self.assertTrue(nan)
self.assertTrue(math.isnan(nan.GetValue()))
# operators
self.assertTrue(t1 == Usd.TimeCode(1.0))
self.assertFalse(t0 == t1)
self.assertFalse(t1 == nan)
self.assertTrue(nan == nan)
self.assertTrue(t0 != t1)
self.assertFalse(t1 != Usd.TimeCode(1.0))
self.assertTrue(t1 != nan)
self.assertFalse(nan != nan)
self.assertTrue(t0 <= t1)
self.assertFalse(t1 <= t0)
self.assertTrue(t1 <= Usd.TimeCode(1.0))
self.assertFalse(t1 <= nan)
self.assertTrue(nan <= t1)
self.assertTrue(t0 < t1)
self.assertFalse(t1 < t0)
self.assertFalse(t1 < Usd.TimeCode(1.0))
self.assertFalse(t1 < nan)
self.assertTrue(nan < t1)
self.assertTrue(t1 >= t0)
self.assertFalse(t0 >= t1)
self.assertTrue(t1 >= Usd.TimeCode(1.0))
self.assertTrue(t1 >= nan)
self.assertFalse(nan >= t1)
self.assertTrue(t1 > t0)
self.assertFalse(t0 > t1)
self.assertFalse(t1 > Usd.TimeCode(1.0))
self.assertTrue(t1 > nan)
self.assertFalse(nan > t1)
# is earliest time
self.assertFalse(t1.IsEarliestTime())
self.assertTrue(Usd.TimeCode(-1.7976931348623157e308).IsEarliestTime())
# is default
self.assertFalse(t1.IsDefault())
self.assertTrue(nan.IsDefault())
# static methods
self.assertEqual(Usd.TimeCode.EarliestTime().GetValue(), -1.7976931348623157e308)
self.assertTrue(math.isnan(Usd.TimeCode.Default().GetValue()))
@tc_logger
def test_time_code_repr(self):
"""
Validates the string representation of the default time code.
"""
from usdrt import Usd
defaultTime = Usd.TimeCode.Default()
timeRepr = repr(defaultTime)
self.assertEqual(timeRepr, "Usd.TimeCode.Default()")
self.assertEqual(eval(timeRepr), defaultTime)
@tc_logger
def testEarliestTimeRepr(self):
"""
Validates the string representation of the earliest time code.
"""
from usdrt import Usd
earliestTime = Usd.TimeCode.EarliestTime()
timeRepr = repr(earliestTime)
self.assertEqual(timeRepr, "Usd.TimeCode.EarliestTime()")
self.assertEqual(eval(timeRepr), earliestTime)
@tc_logger
def testDefaultConstructedTimeRepr(self):
"""
Validates the string representation of a time code created using
the default constructor.
"""
from usdrt import Usd
timeCode = Usd.TimeCode()
timeRepr = repr(timeCode)
self.assertEqual(timeRepr, "Usd.TimeCode()")
self.assertEqual(eval(timeRepr), timeCode)
@tc_logger
def testNumericTimeRepr(self):
"""
Validates the string representation of a numeric time code.
"""
from usdrt import Usd
timeCode = Usd.TimeCode(123.0)
timeRepr = repr(timeCode)
self.assertEqual(timeRepr, "Usd.TimeCode(123.0)")
self.assertEqual(eval(timeRepr), timeCode)
| 4,605 | Python | 27.7875 | 89 | 0.633876 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_primrange.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdPrimRange(TestClass):
@tc_logger
def test_creation(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
prim_range = Usd.PrimRange(prim)
self.assertTrue(prim_range)
@tc_logger
def test_iterator(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
prim_range = Usd.PrimRange(prim)
self.assertTrue(prim_range)
count = 0
for this_prim in prim_range:
count += 1
self.assertEqual(count, 15)
self.assertEqual(this_prim.GetPath(), Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side"))
count = 0
it = iter(prim_range)
for this_prim in it:
if this_prim.GetName() == "Green_Wall":
it.PruneChildren()
count += 1
self.assertEqual(count, 14)
self.assertEqual(this_prim.GetPath(), Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side"))
prim = stage.GetPrimAtPath(Sdf.Path("/Emissive_square/Root"))
self.assertTrue(prim)
prim_range = Usd.PrimRange(prim)
self.assertTrue(prim_range)
count = 0
for this_prim in prim_range:
count += 1
self.assertEqual(count, 5)
self.assertEqual(this_prim.GetPath(), Sdf.Path("/Emissive_square/Root/Looks/EmissiveSG/Emissive"))
count = 0
it = iter(prim_range)
for this_prim in it:
it.PruneChildren()
count += 1
self.assertEqual(count, 1)
self.assertEqual(this_prim.GetPath(), Sdf.Path("/Emissive_square/Root"))
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Emissive_square/Root"))
self.assertTrue(prim)
prim_range = Usd.PrimRange(prim)
self.assertTrue(prim_range)
expected = "PrimRange(</Emissive_square/Root>)"
self.assertEquals(repr(prim_range), expected)
| 3,515 | Python | 27.585366 | 106 | 0.640114 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_rtchangetracker.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestRtChangeTracker(TestClass):
@tc_logger
def test_ctor(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_track_attribute(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
tracker.TrackAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
self.assertFalse(tracker.HasChanges())
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute("inputs:color")
newColor = Gf.Vec3f(0, 0.5, 0.5)
attr.Set(newColor, Usd.TimeCode(0.0))
self.assertTrue(tracker.HasChanges())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_stop_tracking_attribute(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
tracker.TrackAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
self.assertFalse(tracker.HasChanges())
tracker.StopTrackingAttribute("inputs:color")
self.assertFalse(tracker.IsTrackingAttribute("inputs:color"))
newColor = Gf.Vec3f(0, 0.6, 0.6)
attr.Set(newColor, Usd.TimeCode(0.0))
self.assertFalse(tracker.HasChanges())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_pause_and_resume_tracking(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
tracker.TrackAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
tracker.PauseTracking()
newColorA = Gf.Vec3f(0, 0.7, 0.7)
attr.Set(newColorA, Usd.TimeCode(0.0))
self.assertFalse(tracker.HasChanges())
tracker.ResumeTracking()
newColorB = Gf.Vec3f(0, 0.8, 0.8)
attr.Set(newColorB, Usd.TimeCode(0.0))
self.assertTrue(tracker.HasChanges())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_is_change_tracking_paused(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertTrue(tracker)
tracker.TrackAttribute("inputs:color")
self.assertFalse(tracker.IsChangeTrackingPaused())
tracker.PauseTracking()
self.assertTrue(tracker.IsChangeTrackingPaused())
tracker.ResumeTracking()
self.assertFalse(tracker.IsChangeTrackingPaused())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_has_and_clear_changes(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
self.assertFalse(tracker.HasChanges())
newColor = Gf.Vec3f(0, 0.9, 0.9)
attr.Set(newColor, Usd.TimeCode(0.0))
self.assertTrue(tracker.HasChanges())
tracker.ClearChanges()
self.assertFalse(tracker.HasChanges())
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_get_all_changed_prims(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
colorAttr = lightPrim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
# No changes
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 0)
# Change on one prim
newColor = Gf.Vec3f(0, 0.4, 0.4)
colorAttr.Set(newColor, Usd.TimeCode(0.0))
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 1)
self.assertEqual(changedPrims[0], Sdf.Path("/DistantLight"))
# Change on two prims
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
visAttr = cubePrim.GetAttribute("visibility")
visAttr.Set("invisible", Usd.TimeCode(0.0))
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 2)
# Change on a prim that already has a change
lightVisAttr = lightPrim.GetAttribute("visibility")
lightVisAttr.Set("invisible", Usd.TimeCode(0.0))
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 2)
# Change an untracked attr on a third prim
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.3, 0.3)
displayColor.Set(newDisplayColor)
changedPrims = tracker.GetAllChangedPrims()
self.assertEqual(len(changedPrims), 2)
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_get_all_changed_attributes(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
colorAttr = lightPrim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
# No changes
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 0)
# Change attr on one prim
newColor = Gf.Vec3f(0.5, 0.6, 0.7)
colorAttr.Set(newColor, Usd.TimeCode(0.0))
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 1)
self.assertEqual(changedAttrs[0], "/DistantLight.inputs:color")
# Change attr on a second prim
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
cubeVisAttr = cubePrim.GetAttribute("visibility")
cubeVisAttr.Set("invisible", Usd.TimeCode(0.0))
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 2)
# Change a second attr on one of the prims
lightVisAttr = lightPrim.GetAttribute("visibility")
lightVisAttr.Set("invisible", Usd.TimeCode(0.0))
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 3)
# Change an untracked attr on a third prim
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.3, 0.3)
displayColor.Set(newDisplayColor, Usd.TimeCode(0.0))
changedAttrs = tracker.GetAllChangedAttributes()
self.assertEqual(len(changedAttrs), 3)
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_prim_changed(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
colorAttr = lightPrim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
# UsdPrim version of PrimChanged()
self.assertFalse(tracker.PrimChanged(lightPrim))
newColor = Gf.Vec3f(0.6, 0.7, 0.8)
colorAttr.Set(newColor, Usd.TimeCode(0.0))
self.assertTrue(tracker.PrimChanged(lightPrim))
# SdfPath version of PrimChanged()
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
self.assertFalse(tracker.PrimChanged(Sdf.Path("/Cube_5")))
cubeVisAttr = cubePrim.GetAttribute("visibility")
cubeVisAttr.Set("invisible", Usd.TimeCode(0.0))
self.assertTrue(tracker.PrimChanged(Sdf.Path("/Cube_5")))
# Change an untracked attr on a third prim
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.4, 0.4)
displayColor.Set(newDisplayColor, Usd.TimeCode(0.0))
self.assertFalse(tracker.PrimChanged(spherePrim))
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_attribute_changed(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
colorAttr = lightPrim.GetAttribute("inputs:color")
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
# UsdPrim version of AttributeChanged()
self.assertFalse(tracker.AttributeChanged(colorAttr))
newColor = Gf.Vec3f(0.7, 0.8, 0.9)
colorAttr.Set(newColor, Usd.TimeCode(0.0))
self.assertTrue(tracker.AttributeChanged(colorAttr))
# SdfPath version of AttributeChanged()
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
self.assertFalse(tracker.AttributeChanged(Sdf.Path("/Cube_5.visibility")))
cubeVisAttr = cubePrim.GetAttribute("visibility")
cubeVisAttr.Set("invisible", Usd.TimeCode(0.0))
self.assertTrue(tracker.AttributeChanged(Sdf.Path("/Cube_5.visibility")))
# Change an untracked attr on a third prim
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.5, 0.5)
displayColor.Set(newDisplayColor, Usd.TimeCode(0.0))
self.assertFalse(tracker.AttributeChanged(displayColor))
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_get_changed_attributes(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
lightPrim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
cubePrim = stage.GetPrimAtPath(Sdf.Path("/Cube_5"))
spherePrim = stage.GetPrimAtPath(Sdf.Path("/Sphere_2"))
tracker = Rt.ChangeTracker(stage)
tracker.TrackAttribute("inputs:color")
tracker.TrackAttribute("visibility")
tracker.TrackAttribute("subdivisionScheme")
# Change one attr on a prim
lightColor = lightPrim.GetAttribute("inputs:color")
self.assertEqual(len(tracker.GetChangedAttributes(lightPrim)), 0)
newColor = Gf.Vec3f(0.2, 0.3, 0.4)
lightColor.Set(newColor, Usd.TimeCode(0.0))
testResult = tracker.GetChangedAttributes(lightPrim)
self.assertEqual(len(testResult), 1)
self.assertEqual(testResult[0], "inputs:color")
# Change multiple tracked attrs on a prim
cubeVis = cubePrim.GetAttribute("visibility")
cubeVis.Set("invisible", Usd.TimeCode(0.0))
cubeSubdiv = cubePrim.GetAttribute("subdivisionScheme")
cubeSubdiv.Set("loop", Usd.TimeCode(0.0))
self.assertEqual(len(tracker.GetChangedAttributes(cubePrim)), 2)
# Change untracked attr on a prim
displayColor = spherePrim.GetAttribute("primvars:displayColor")
newDisplayColor = Gf.Vec3f(0, 0.3, 0.5)
displayColor.Set(newDisplayColor, Usd.TimeCode(0.0))
self.assertEqual(len(tracker.GetChangedAttributes(spherePrim)), 0)
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_is_tracking_attribute(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertFalse(tracker.IsTrackingAttribute("inputs:color"))
tracker.TrackAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
tracker.TrackAttribute("visibility")
self.assertTrue(tracker.IsTrackingAttribute("visibility"))
self.assertTrue(tracker.IsTrackingAttribute("inputs:color"))
tracker.StopTrackingAttribute("inputs:color")
self.assertTrue(tracker.IsTrackingAttribute("visibility"))
self.assertFalse(tracker.IsTrackingAttribute("inputs:color"))
tracker.StopTrackingAttribute("visibility")
self.assertFalse(tracker.IsTrackingAttribute("visibility"))
self.assertFalse(tracker.IsTrackingAttribute("fakeAttr"))
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
@tc_logger
def test_get_tracked_attributes(self):
from pxr import UsdUtils
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
tracker = Rt.ChangeTracker(stage)
self.assertEqual(len(tracker.GetTrackedAttributes()), 0)
tracker.TrackAttribute("inputs:color")
self.assertEqual(len(tracker.GetTrackedAttributes()), 1)
self.assertEqual(tracker.GetTrackedAttributes()[0], "inputs:color")
tracker.TrackAttribute("visibility")
self.assertEqual(len(tracker.GetTrackedAttributes()), 2)
tracker.StopTrackingAttribute("inputs:color")
self.assertEqual(len(tracker.GetTrackedAttributes()), 1)
self.assertEqual(tracker.GetTrackedAttributes()[0], "visibility")
# Really make sure the stage is dead and cache is cleared for test independence
del stage
UsdUtils.StageCache.Get().Clear()
| 17,463 | Python | 35.383333 | 87 | 0.664033 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_array.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 ctypes
import pathlib
import platform
import weakref
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
if platform.processor() == "aarch64":
# warp not supported on aarch64 yet for our testing
return
import warp as wp
wp.init()
except ImportError:
# not needed in Kit /
# warp not available in default kit install
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
def warp_array_from_cuda_array_interface(a):
import warp as wp
cai = a.__cuda_array_interface__
return wp.types.array(
dtype=wp.vec3,
length=cai["shape"][0],
capacity=cai["shape"][0] * wp.types.type_size_in_bytes(wp.vec3),
ptr=cai["data"][0],
device="cuda",
owner=False,
requires_grad=False,
)
class TestVtArray(TestClass):
@tc_logger
def test_init(self):
from usdrt import Vt
empty = Vt.IntArray()
self.assertEquals(len(empty), 0)
allocated = Vt.IntArray(10)
self.assertEquals(len(allocated), 10)
from_list = Vt.IntArray([0, 1, 2, 3])
self.assertEquals(len(from_list), 4)
@tc_logger
def test_getset(self):
from usdrt import Vt
test_list = Vt.IntArray([0, 1, 2, 3])
self.assertEquals(len(test_list), 4)
for i in range(4):
self.assertEquals(test_list[i], i)
test_list[3] = 100
self.assertEquals(test_list[3], 100)
@tc_logger
def test_iterator(self):
from usdrt import Vt
test_list = Vt.IntArray([0, 1, 2, 3])
i = 0
for item in test_list:
self.assertEquals(i, item)
i += 1
@tc_logger
def test_is_fabric(self):
from usdrt import Sdf, Usd, Vt
test_list = Vt.IntArray([0, 1, 2, 3])
self.assertFalse(test_list.IsPythonData())
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute("faceVertexIndices")
self.assertTrue(attr)
result = attr.Get()
self.assertEquals(result[0], 1)
self.assertTrue(result.IsFabricData())
result[0] = 9
self.assertTrue(result.IsFabricData())
result2 = attr.Get()
self.assertTrue(result2.IsFabricData())
self.assertEquals(result2[0], 9)
result2.DetachFromSource()
result2[0] = 15
result3 = attr.Get()
self.assertEquals(result3[0], 9)
def _getNumpyPoints(self):
import numpy as np
points = np.zeros(shape=(1024, 3), dtype=np.float32)
points[0][0] = 999.0
points[0][1] = 998.0
points[0][2] = 997.0
points[1][0] = 1.0
points[1][1] = 2.0
points[1][2] = 3.0
points[10][0] = 10.0
points[10][1] = 20.0
points[10][2] = 30.0
return points
@tc_logger
def test_array_interface(self):
import numpy as np
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/prim"))
attr = prim.CreateAttribute("points", Sdf.ValueTypeNames.Point3fArray, True)
self.assertTrue(attr)
points = self._getNumpyPoints()
pointsRef = weakref.ref(points)
pointsId = id(points)
# Create a VtArray from a numpy array using the buffer protocol
vtPoints = Vt.Vec3fArray(points)
# Ensure the VtArray incremented the refcount on points
self.assertEqual(ctypes.c_long.from_address(pointsId).value, 2)
# Delete the numpy reference to check that the VtArray kept it alive
del points
# Ensure VtArray released the refcount on points
self.assertEqual(ctypes.c_long.from_address(pointsId).value, 1)
# Set the Fabric attribute which will make a copy from numpy to Fabric
self.assertTrue(attr.Set(vtPoints))
del vtPoints
# Ensure VtArray released the refcount on points
self.assertIsNone(pointsRef())
# Retrieve a new Fabric VtArray from usdrt
fabricPoints = attr.Get()
self.assertTrue(fabricPoints.IsFabricData())
# Create a new attribute which would invalidate any existing Fabric pointer
attr2 = prim.CreateAttribute("badattr", Sdf.ValueTypeNames.Float, True)
self.assertTrue(attr2.Set(3.5))
newPoints = np.array(fabricPoints)
# Delete the fabric VtArray to ensure the data was really copied into numpy
del fabricPoints
# Now compare the round-trip through usdrt was a success
points = self._getNumpyPoints()
for i in range(1024):
for j in range(3):
self.assertEqual(
points[i][j], newPoints[i][j], msg=f"points[{i}][{j}]: {points[i][j]} != {newPoints[i][j]}"
)
@tc_logger
def test_cuda_array_interface(self):
if platform.processor() == "aarch64":
return
import numpy as np
from usdrt import Sdf, Usd, Vt
try:
import warp as wp
except ImportError:
if TestClass is omni.kit.test.AsyncTestCase:
# warp not available for testing in kit at this time
return
raise
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/prim"))
attr = prim.CreateAttribute("points", Sdf.ValueTypeNames.Point3fArray, True)
self.assertTrue(attr)
idattr = prim.CreateAttribute("faceVertexIndices", Sdf.ValueTypeNames.IntArray, True)
self.assertTrue(idattr)
tag = prim.CreateAttribute("Deformable", Sdf.ValueTypeNames.PrimTypeTag, True)
self.assertTrue(tag)
# First create a warp array from numpy
points = self._getNumpyPoints()
warpPoints = wp.array(points, device="cpu")
with wp.ScopedCudaGuard():
gpuWarpPoints = warpPoints.to("cuda")
warpId = id(gpuWarpPoints)
warpRef = weakref.ref(gpuWarpPoints)
# Create a VtArray from a warp array using the __cuda_array_interface__
self.assertEqual(ctypes.c_long.from_address(warpId).value, 1)
vtPoints = Vt.Vec3fArray(gpuWarpPoints)
self.assertEqual(ctypes.c_long.from_address(warpId).value, 2)
# Delete the warp reference to check that the VtArray kept it alive
del gpuWarpPoints
self.assertEqual(ctypes.c_long.from_address(warpId).value, 1)
# Set the Fabric attribute which will make a CUDA copy from warp to Fabric
self.assertTrue(attr.Set(vtPoints))
# OM-84460 - IntArray supported for 1d warp arrays
warp_ids = wp.zeros(shape=1024, dtype=int, device="cuda")
vt_ids = Vt.IntArray(warp_ids)
self.assertTrue(idattr.Set(vt_ids))
wp.synchronize()
# Check the VtArray destruction released the warp array
del vtPoints
self.assertIsNone(warpRef())
# Retrieve a new Fabric VtArray from usdrt
newVtPoints = attr.Get()
self.assertTrue(newVtPoints.HasFabricGpuData())
# Create a new attribute which would invalidate any existing Fabric pointer
attr2 = prim.CreateAttribute("badattr", Sdf.ValueTypeNames.Float, True)
attr2.Set(3.5)
newWarpPoints = warp_array_from_cuda_array_interface(newVtPoints)
# Delete the fabric VtArray to ensure the data was really copied into warp
del newVtPoints
newPoints = newWarpPoints.numpy()
# Now compare the round-trip through usdrt was a success
self.assertEqual(points.shape, newPoints.shape)
for i in range(1024):
for j in range(3):
self.assertEqual(
points[i][j], newPoints[i][j], msg=f"points[{i}][{j}]: {points[i][j]} != {newPoints[i][j]}"
)
@tc_logger
def test_repr(self):
from usdrt import Vt
test_array = Vt.IntArray(4)
result = "Vt.IntArray(4, ("
for i in range(4):
test_array[i] = i
result += str(i)
if i < 3:
result += ", "
else:
result += ")"
result += ")"
self.assertEqual(result, repr(test_array))
@tc_logger
def test_str(self):
from usdrt import Vt
from pxr import Vt as PxrVt
test_array = Vt.IntArray(range(4))
expected = str(PxrVt.IntArray(range(4)))
self.assertEqual(str(test_array), expected)
@tc_logger
def test_assetarray(self):
from usdrt import Sdf, Vt
test_array = Vt.AssetArray(4)
for i in range(4):
test_array[i] = Sdf.AssetPath(f"hello{i}", f"hello{i}.txt")
self.assertEqual(len(test_array), 4)
# This should not cause a crash
del test_array
@tc_logger
def test_arraybuffer_types(self):
import numpy as np
from usdrt import Vt
self.assertTrue(Vt.BoolArray(np.zeros(shape=(10, 1), dtype=np.bool_)).IsPythonData())
self.assertTrue(Vt.CharArray(np.zeros(shape=(10, 1), dtype=np.byte)).IsPythonData())
self.assertTrue(Vt.UCharArray(np.zeros(shape=(10, 1), dtype=np.ubyte)).IsPythonData())
self.assertTrue(Vt.DoubleArray(np.zeros(shape=(10, 1), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.FloatArray(np.zeros(shape=(10, 1), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.HalfArray(np.zeros(shape=(10, 1), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.IntArray(np.zeros(shape=(10, 1), dtype=np.intc)).IsPythonData())
self.assertTrue(Vt.Int64Array(np.zeros(shape=(10, 1), dtype=np.longlong)).IsPythonData())
self.assertTrue(Vt.ShortArray(np.zeros(shape=(10, 1), dtype=np.short)).IsPythonData())
self.assertTrue(Vt.UInt64Array(np.zeros(shape=(10, 1), dtype=np.ulonglong)).IsPythonData())
self.assertTrue(Vt.UIntArray(np.zeros(shape=(10, 1), dtype=np.uintc)).IsPythonData())
self.assertTrue(Vt.UShortArray(np.zeros(shape=(10, 1), dtype=np.ushort)).IsPythonData())
self.assertTrue(Vt.Matrix3dArray(np.zeros(shape=(10, 9), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Matrix3fArray(np.zeros(shape=(10, 9), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.Matrix4dArray(np.zeros(shape=(10, 16), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Matrix4fArray(np.zeros(shape=(10, 16), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.QuatdArray(np.zeros(shape=(10, 4), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.QuatfArray(np.zeros(shape=(10, 4), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.QuathArray(np.zeros(shape=(10, 4), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.Vec2dArray(np.zeros(shape=(10, 2), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Vec3dArray(np.zeros(shape=(10, 3), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Vec4dArray(np.zeros(shape=(10, 4), dtype=np.float64)).IsPythonData())
self.assertTrue(Vt.Vec2fArray(np.zeros(shape=(10, 2), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.Vec3fArray(np.zeros(shape=(10, 3), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.Vec4fArray(np.zeros(shape=(10, 4), dtype=np.float32)).IsPythonData())
self.assertTrue(Vt.Vec2hArray(np.zeros(shape=(10, 2), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.Vec3hArray(np.zeros(shape=(10, 3), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.Vec4hArray(np.zeros(shape=(10, 4), dtype=np.float16)).IsPythonData())
self.assertTrue(Vt.Vec2iArray(np.zeros(shape=(10, 2), dtype=np.intc)).IsPythonData())
self.assertTrue(Vt.Vec3iArray(np.zeros(shape=(10, 3), dtype=np.intc)).IsPythonData())
self.assertTrue(Vt.Vec4iArray(np.zeros(shape=(10, 4), dtype=np.intc)).IsPythonData())
@tc_logger
def test_implicit_conversion_bindings(self):
from usdrt import Gf, Sdf, Usd, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/prim"))
# IntArray
intarray = prim.CreateAttribute("intarray", Sdf.ValueTypeNames.IntArray, True)
self.assertTrue(intarray)
intarray.Set(Vt.IntArray([0, 1, 2]))
intlist = list(prim.GetAttribute("intarray").Get())
self.assertEqual(len(intlist), 3)
intlist.extend([3])
self.assertEqual(len(intlist), 4)
self.assertTrue(prim.GetAttribute("intarray").Set(intlist))
updated_list = prim.GetAttribute("intarray").Get()
self.assertEqual(len(updated_list), 4)
self.assertEqual(list(updated_list), [0, 1, 2, 3])
# Point3fArray
points = prim.CreateAttribute("points", Sdf.ValueTypeNames.Point3fArray, True)
self.assertTrue(points)
points.Set(Vt.Vec3fArray([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]))
vertices = list(prim.GetAttribute("points").Get())
self.assertEqual(len(vertices), 3)
vertices.extend([[3.0, 3.0, 3.0]])
prim.GetAttribute("points").Set(vertices)
updated_vertices = prim.GetAttribute("points").Get()
self.assertEqual(len(updated_vertices), 4)
| 14,605 | Python | 34.537713 | 111 | 0.621294 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_rtboundable.py | __copyright__ = "Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestRtBoundable(TestClass):
@tc_logger
def test_ctor(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
empty = Rt.Boundable()
self.assertFalse(empty)
@tc_logger
def test_get_prim(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
check_prim = boundable.GetPrim()
self.assertEqual(prim.GetPath(), check_prim.GetPath())
@tc_logger
def test_get_path(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
self.assertEqual(prim.GetPath(), boundable.GetPath())
@tc_logger
def test_world_extent(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
extent = Gf.Range3d(Gf.Vec3d(-10, -10, -10), Gf.Vec3d(10, 10, 10))
attr = boundable.CreateWorldExtentAttr(extent)
self.assertTrue(attr)
attr = boundable.GetWorldExtentAttr()
self.assertTrue(attr)
world_ext = attr.Get()
self.assertEqual(extent, world_ext)
@tc_logger
def test_has_world_extent(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
self.assertFalse(boundable.HasWorldExtent())
extent = Gf.Range3d(Gf.Vec3d(-10, -10, -10), Gf.Vec3d(10, 10, 10))
attr = boundable.CreateWorldExtentAttr(extent)
self.assertTrue(attr)
self.assertTrue(boundable.HasWorldExtent())
@tc_logger
def test_clear_world_extent(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
self.assertFalse(boundable.HasWorldXform())
extent = Gf.Range3d(Gf.Vec3d(-10, -10, -10), Gf.Vec3d(10, 10, 10))
attr = boundable.CreateWorldExtentAttr(extent)
self.assertTrue(attr)
self.assertTrue(boundable.HasWorldExtent())
boundable.ClearWorldExtent()
self.assertFalse(boundable.HasWorldExtent())
@tc_logger
def test_set_world_extent_from_usd(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
self.assertTrue(boundable)
self.assertFalse(boundable.HasWorldExtent())
self.assertTrue(boundable.SetWorldExtentFromUsd())
self.assertTrue(boundable.HasWorldExtent())
attr = boundable.GetWorldExtentAttr()
self.assertTrue(attr)
extent = attr.Get()
expected = Gf.Range3d(Gf.Vec3d(247.11319, -249.90994, 0.0), Gf.Vec3d(247.11328, 249.91781, 500.0))
self.assertTrue(Gf.IsClose(extent.GetMin(), expected.GetMin(), 0.001))
self.assertTrue(Gf.IsClose(extent.GetMax(), expected.GetMax(), 0.001))
@tc_logger
def test_boundable_tokens(self):
from usdrt import Rt
self.assertEqual(Rt.Tokens.worldExtent, "_worldExtent")
@tc_logger
def test_repr_representation(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
boundable = Rt.Boundable(prim)
expected = "Boundable(</Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back>)"
self.assertEqual(repr(boundable), expected)
| 6,321 | Python | 28.962085 | 106 | 0.655434 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_rtxformable.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestRtXformable(TestClass):
@tc_logger
def test_ctor(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
empty = Rt.Xformable()
self.assertFalse(empty)
@tc_logger
def test_get_prim(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
check_prim = xformable.GetPrim()
self.assertEqual(prim.GetPath(), check_prim.GetPath())
@tc_logger
def test_get_path(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertEqual(prim.GetPath(), xformable.GetPath())
@tc_logger
def test_world_position(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
new_world_pos = Gf.Vec3d(100, 200, 300)
offset = Gf.Vec3d(100, 200, 300)
attr = xformable.CreateWorldPositionAttr(new_world_pos)
self.assertTrue(attr)
attr = xformable.GetWorldPositionAttr()
self.assertTrue(attr)
world_pos = attr.Get()
self.assertEqual(new_world_pos, world_pos)
world_pos += offset
attr.Set(world_pos)
@tc_logger
def test_world_orientation(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
new_world_or = Gf.Quatf(0.5, -1, 2, -3)
attr = xformable.CreateWorldOrientationAttr(new_world_or)
self.assertTrue(attr)
attr = xformable.GetWorldOrientationAttr()
self.assertTrue(attr)
world_or = attr.Get()
self.assertEqual(new_world_or, world_or)
@tc_logger
def test_world_scale(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
new_world_scale = Gf.Vec3f(100, 200, 300)
attr = xformable.CreateWorldScaleAttr(new_world_scale)
self.assertTrue(attr)
attr = xformable.GetWorldScaleAttr()
self.assertTrue(attr)
world_scale = attr.Get()
self.assertEqual(new_world_scale, world_scale)
@tc_logger
def test_local_matrix(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
new_local_matrix = Gf.Matrix4d(2)
attr = xformable.CreateLocalMatrixAttr(new_local_matrix)
self.assertTrue(attr)
attr = xformable.GetLocalMatrixAttr()
self.assertTrue(attr)
local_matrix = attr.Get()
self.assertEqual(new_local_matrix, local_matrix)
@tc_logger
def test_has_world_xform(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasWorldXform())
new_world_pos = Gf.Vec3d(100, 200, 300)
attr = xformable.CreateWorldPositionAttr(new_world_pos)
self.assertTrue(attr)
self.assertTrue(xformable.HasWorldXform())
@tc_logger
def test_clear_world_xform(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasWorldXform())
new_world_pos = Gf.Vec3d(100, 200, 300)
attr = xformable.CreateWorldPositionAttr(new_world_pos)
self.assertTrue(attr)
self.assertTrue(xformable.HasWorldXform())
xformable.ClearWorldXform()
self.assertFalse(xformable.HasWorldXform())
@tc_logger
def test_set_world_xform_from_usd(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasWorldXform())
self.assertTrue(xformable.SetWorldXformFromUsd())
self.assertTrue(xformable.HasWorldXform())
pos_attr = xformable.GetWorldPositionAttr()
self.assertTrue(pos_attr)
orient_attr = xformable.GetWorldOrientationAttr()
self.assertTrue(orient_attr)
scale_attr = xformable.GetWorldScaleAttr()
self.assertTrue(scale_attr)
self.assertTrue(Gf.IsClose(pos_attr.Get(), Gf.Vec3d(0, 0, 250), 0.00001))
self.assertTrue(Gf.IsClose(orient_attr.Get(), Gf.Quatf(0.5, -0.5, 0.5, -0.5), 0.00001))
self.assertTrue(Gf.IsClose(scale_attr.Get(), Gf.Vec3f(1, 1, 1), 0.00001))
@tc_logger
def test_has_local_xform(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasLocalXform())
new_local_mat = Gf.Matrix4d(2)
attr = xformable.CreateLocalMatrixAttr(new_local_mat)
self.assertTrue(attr)
self.assertTrue(xformable.HasLocalXform())
@tc_logger
def test_clear_local_xform(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasLocalXform())
new_local_mat = Gf.Matrix4d(2)
attr = xformable.CreateLocalMatrixAttr(new_local_mat)
self.assertTrue(attr)
self.assertTrue(xformable.HasLocalXform())
xformable.ClearLocalXform()
self.assertFalse(xformable.HasLocalXform())
@tc_logger
def test_set_local_xform_from_usd(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
self.assertTrue(xformable)
self.assertFalse(xformable.HasLocalXform())
self.assertTrue(xformable.SetLocalXformFromUsd())
self.assertTrue(xformable.HasLocalXform())
attr = xformable.GetLocalMatrixAttr()
self.assertTrue(attr)
self.assertTrue(Gf.IsClose(attr.Get(), Gf.Matrix4d(1), 0.00001))
@tc_logger
def test_tokens(self):
from usdrt import Rt
self.assertEqual(Rt.Tokens.worldPosition, "_worldPosition")
self.assertEqual(Rt.Tokens.worldOrientation, "_worldOrientation")
self.assertEqual(Rt.Tokens.worldScale, "_worldScale")
self.assertEqual(Rt.Tokens.localMatrix, "_localMatrix")
@tc_logger
def test_repr_representation(self):
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
xformable = Rt.Xformable(prim)
expected = "Xformable(</Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back>)"
self.assertEqual(repr(xformable), expected)
| 10,955 | Python | 29.518106 | 97 | 0.651118 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_pointInstancer.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdGeomPointInstancer(TestClass):
@tc_logger
def test_get_relationship(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/inst"), "PointInstancer")
self.assertFalse(prim.HasRelationship("prototypes"))
inst = UsdGeom.PointInstancer(prim)
self.assertTrue(inst)
# create attribute using prim api
rel = prim.CreateRelationship(UsdGeom.Tokens.prototypes, False)
self.assertTrue(rel)
# verify get attribute using schema api
protoRel = inst.GetPrototypesRel()
self.assertTrue(protoRel)
self.assertTrue(protoRel.GetName() == "prototypes")
@tc_logger
def test_create_relationship(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/inst"), "PointInstancer")
self.assertFalse(prim.HasRelationship("prototypes"))
# create rel using schema api
inst = UsdGeom.PointInstancer(prim)
self.assertTrue(inst)
rel = inst.CreatePrototypesRel()
# verify using prim api
self.assertTrue(rel)
self.assertTrue(prim.HasRelationship(UsdGeom.Tokens.prototypes))
self.assertTrue(rel.GetName() == "prototypes")
| 2,519 | Python | 27.965517 | 78 | 0.687177 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_prim.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdPrim(TestClass):
@tc_logger
def test_has_attribute(self):
from usdrt import Sdf, Usd, UsdGeom
# print("Attach to {}".format(os.getpid()))
# time.sleep(10)
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
self.assertTrue(prim.HasAttribute(UsdGeom.Tokens.xformOpOrder))
self.assertFalse(prim.HasAttribute(UsdGeom.Tokens.radius))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
self.assertTrue(prim.HasAttribute(UsdGeom.Tokens.faceVertexIndices))
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.HasAttribute(UsdGeom.Tokens.radius))
@tc_logger
def test_get_attribute(self):
from usdrt import Sdf, Usd, UsdGeom
# print("Attach to {}".format(os.getpid()))
# time.sleep(10)
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr)
self.assertTrue(attr.GetName() == UsdGeom.Tokens.doubleSided)
# TODO get value
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.GetAttribute(UsdGeom.Tokens.radius))
@tc_logger
def test_get_attributes(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attributes = prim.GetAttributes()
self.assertTrue(len(attributes) == 12)
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.GetAttributes())
@tc_logger
def test_create_attribute(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/prim"))
self.assertFalse(prim.HasAttribute("myAttr"))
attr = prim.CreateAttribute("myAttr", Sdf.ValueTypeNames.Int, True)
self.assertTrue(attr)
self.assertTrue(prim.HasAttribute("myAttr"))
self.assertTrue(attr.GetName() == "myAttr")
@tc_logger
def test_create_attribute_invalid(self):
# Ensure creating attribute on invalid prim does not crash
from usdrt import Gf, Rt, Sdf, Usd
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/invalid"))
self.assertFalse(prim)
self.assertFalse(prim.IsValid())
# this should not crash
attr = prim.CreateAttribute("testAttr", Sdf.ValueTypeNames.Int, True)
self.assertFalse(attr)
# this should not crash
xformable = Rt.Xformable(prim)
attr = xformable.CreateWorldPositionAttr(Gf.Vec3d(0, 200, 0))
self.assertFalse(attr)
@tc_logger
def test_has_relationship(self):
from usdrt import Sdf, Usd, UsdGeom, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"))
self.assertTrue(prim)
self.assertTrue(prim.HasRelationship(UsdShade.Tokens.materialBinding))
self.assertFalse(prim.HasRelationship(UsdGeom.Tokens.proxyPrim))
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.HasRelationship(UsdShade.Tokens.materialBinding))
@tc_logger
def test_get_relationship(self):
from usdrt import Sdf, Usd, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"))
self.assertTrue(prim)
rel = prim.GetRelationship(UsdShade.Tokens.materialBinding)
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.GetRelationship(UsdShade.Tokens.materialBinding))
@tc_logger
def test_get_relationships(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"))
self.assertTrue(prim)
relationships = prim.GetRelationships()
self.assertEqual(len(relationships), 1)
targets = relationships[0].GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
# non-authored relationships from schema (proxyPrim) not included here
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall"))
relationships = prim.GetRelationships()
self.assertEqual(len(relationships), 0)
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.GetRelationships())
@tc_logger
def test_create_relationship(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG"))
self.assertTrue(prim)
self.assertFalse(prim.HasRelationship("foobar"))
rel = prim.CreateRelationship("foobar")
self.assertTrue(prim.HasRelationship("foobar"))
self.assertFalse(rel.HasAuthoredTargets())
@tc_logger
def test_create_relationship_invalid(self):
# OM_81734 Ensure creating rel on invalid prim does not crash
from usdrt import Sdf, Usd
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/invalid"))
self.assertFalse(prim)
self.assertFalse(prim.IsValid())
# this should not crash
rel = prim.CreateRelationship("testrel")
self.assertFalse(rel)
@tc_logger
def test_remove_property(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall"))
self.assertTrue(prim)
self.assertTrue(prim.HasAttribute(UsdGeom.Tokens.extent))
self.assertTrue(prim.RemoveProperty(UsdGeom.Tokens.extent))
self.assertFalse(prim.HasAttribute(UsdGeom.Tokens.extent))
# invalid prim should not cause crash
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
self.assertFalse(prim.RemoveProperty(UsdGeom.Tokens.extent))
@tc_logger
def test_family(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
child = prim.GetChild("White_Wall_Back")
self.assertTrue(child)
self.assertTrue(child.GetPath() == Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
parent = prim.GetParent()
self.assertTrue(parent)
self.assertTrue(parent.GetPath() == Sdf.Path("/Cornell_Box/Root"))
sibling = prim.GetNextSibling()
self.assertTrue(sibling)
self.assertTrue(sibling.GetPath() == Sdf.Path("/Cornell_Box/Root/Looks"))
children = prim.GetChildren()
i = 0
for child in children:
child_direct = prim.GetChild(child.GetName())
self.assertEqual(child.GetName(), child_direct.GetName())
i += 1
self.assertEqual(i, 5)
@tc_logger
def test_get_type(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
test_type = prim.GetTypeName()
self.assertEqual(test_type, "Xform")
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
test_type = prim.GetTypeName()
self.assertEqual(test_type, "Mesh")
@tc_logger
def test_set_type(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
self.assertEqual(prim.GetTypeName(), "Xform")
self.assertTrue(prim.SetTypeName("SkelRoot"))
self.assertEqual(prim.GetTypeName(), "SkelRoot")
@tc_logger
def test_has_authored_type(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Emissive_square/Root"))
self.assertTrue(prim)
self.assertFalse(prim.HasAuthoredTypeName())
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
self.assertTrue(prim.HasAuthoredTypeName())
@tc_logger
def test_clear_type(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
self.assertTrue(prim.HasAuthoredTypeName())
prim.ClearTypeName()
self.assertFalse(prim.HasAuthoredTypeName())
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP"))
self.assertTrue(prim)
expected = "Prim(</Cornell_Box/Root/Cornell_Box1_LP>)"
self.assertEqual(repr(prim), expected)
@tc_logger
def test_has_api(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
self.assertTrue(prim.HasAPI("ShapingAPI"))
self.assertFalse(prim.HasAPI("DoesNotExist"))
@tc_logger
def test_apply_api(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
self.assertTrue(prim.ApplyAPI("Test1"))
self.assertTrue(prim.HasAPI("Test1"))
self.assertTrue(prim.AddAppliedSchema("Test2"))
self.assertTrue(prim.HasAPI("Test2"))
@tc_logger
def test_remove_api(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
self.assertTrue(prim.ApplyAPI("Test1"))
self.assertTrue(prim.HasAPI("Test1"))
self.assertTrue(prim.AddAppliedSchema("Test2"))
self.assertTrue(prim.HasAPI("Test2"))
self.assertTrue(prim.RemoveAPI("Test1"))
self.assertFalse(prim.HasAPI("Test1"))
self.assertTrue(prim.RemoveAppliedSchema("Test2"))
self.assertFalse(prim.HasAPI("Test2"))
@tc_logger
def test_get_applied_schemas(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
schemas = prim.GetAppliedSchemas()
self.assertEqual(len(schemas), 5)
self.assertTrue("LightAPI" in schemas)
self.assertTrue("ShapingAPI" in schemas)
self.assertTrue("CollectionAPI" in schemas)
self.assertTrue("CollectionAPI:lightLink" in schemas)
self.assertTrue("CollectionAPI:shadowLink" in schemas)
@tc_logger
def test_get_stage(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
# force stage2 out of scope
stage2 = prim.GetStage()
self.assertTrue(stage2)
del stage2
# ensure underlying shared data is unchanged
prim = stage.GetPrimAtPath(Sdf.Path("/CylinderLight"))
self.assertTrue(prim)
| 15,183 | Python | 31.444444 | 105 | 0.652704 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_valuetypename.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestSdfValueTypeName(TestClass):
@tc_logger
def test_get_scalar_type(self):
from usdrt import Sdf
scalar_int = Sdf.ValueTypeNames.IntArray.scalarType
self.assertEqual(scalar_int, Sdf.ValueTypeNames.Int)
@tc_logger
def test_get_array_type(self):
from usdrt import Sdf
array_int = Sdf.ValueTypeNames.Int.arrayType
self.assertEqual(array_int, Sdf.ValueTypeNames.IntArray)
@tc_logger
def test_is_array(self):
from usdrt import Sdf
array_type = Sdf.ValueTypeNames.IntArray
scalar_type = Sdf.ValueTypeNames.Int
self.assertTrue(array_type.isArray)
self.assertFalse(scalar_type.isArray)
@tc_logger
def test_is_scalar(self):
from usdrt import Sdf
array_type = Sdf.ValueTypeNames.IntArray
scalar_type = Sdf.ValueTypeNames.Int
self.assertFalse(array_type.isScalar)
self.assertTrue(scalar_type.isScalar)
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf
array_type = Sdf.ValueTypeNames.IntArray
scalar_type = Sdf.ValueTypeNames.Int
array_expected = "Sdf.ValueTypeName('int[]')"
scalar_expected = "Sdf.ValueTypeName('int')"
self.assertEquals(repr(array_type), array_expected)
self.assertEquals(repr(scalar_type), scalar_expected)
| 2,477 | Python | 25.361702 | 78 | 0.691966 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/__init__.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 gc
scan_for_test_modules = True
def tc_logger(func):
"""
Print TC macros about the test when running on TC
(unneeded in kit)
"""
def wrapper(*args, **kwargs):
func(*args, **kwargs)
# Always reset global stage cache and collect
# garbage to ensure stage and Fabric cleanup
from pxr import UsdUtils
UsdUtils.StageCache.Get().Clear()
gc.collect()
return wrapper
| 895 | Python | 27.903225 | 78 | 0.710615 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_relationship.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdRelationship(TestClass):
@tc_logger
def test_has_authored_targets(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
self.assertTrue(rel.HasAuthoredTargets())
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall.proxyPrim"))
self.assertTrue(rel)
self.assertFalse(rel.HasAuthoredTargets())
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.HasAuthoredTargets())
@tc_logger
def test_get_targets(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.GetTargets())
@tc_logger
def test_add_target(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
new_target = Sdf.Path("/Cornell_Box/Root/Looks/Red1SG")
self.assertTrue(rel.AddTarget(new_target))
targets = rel.GetTargets()
self.assertEqual(len(targets), 2)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
self.assertEqual(targets[1], new_target)
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall.proxyPrim"))
self.assertTrue(rel)
proxy_prim_target = Sdf.Path("/Cube_5")
self.assertTrue(rel.AddTarget(proxy_prim_target))
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], proxy_prim_target)
# OM-75327 - add a target to a new relationship
prim = stage.GetPrimAtPath("/Cornell_Box")
self.assertTrue(prim)
rel = prim.CreateRelationship("testRel")
self.assertTrue(rel)
self.assertTrue(rel.AddTarget(proxy_prim_target))
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cube_5"))
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.AddTarget(proxy_prim_target))
@tc_logger
def test_remove_target(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
# It's valid to try to remove a target that is not
# in the list of targets in the relationship
target_not_in_list = Sdf.Path("/Foo/Bar")
self.assertTrue(rel.RemoveTarget(target_not_in_list))
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
# Removing a valid target will return empty target lists with GetTarget
target_in_list = Sdf.Path("/Cornell_Box/Root/Looks/Green1SG")
self.assertTrue(rel.RemoveTarget(target_in_list))
targets = rel.GetTargets()
self.assertEqual(len(targets), 0)
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.RemoveTarget(target_not_in_list))
@tc_logger
def test_clear_targets(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
self.assertTrue(rel.ClearTargets(True))
targets = rel.GetTargets()
self.assertEqual(len(targets), 0)
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.ClearTargets(True))
@tc_logger
def test_set_targets(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG"))
new_targets = [Sdf.Path("/Cornell_Box/Root/Looks/Red1SG")]
self.assertTrue(rel.SetTargets(new_targets))
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertEqual(targets[0], Sdf.Path("/Cornell_Box/Root/Looks/Red1SG"))
too_many_targets = [Sdf.Path("/Foo"), Sdf.Path("/Bar")]
self.assertTrue(rel.SetTargets(too_many_targets))
targets = rel.GetTargets()
self.assertEqual(len(targets), 2)
self.assertEqual(targets[0], Sdf.Path("/Foo"))
self.assertEqual(targets[1], Sdf.Path("/Bar"))
# invalid rel should not cause crash
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
self.assertFalse(rel.SetTargets(new_targets))
@tc_logger
def test_repr_representation(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
expected = "Relationship(<material:binding>)"
self.assertEquals(repr(rel), expected)
| 8,239 | Python | 33.333333 | 109 | 0.653356 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_usd_collectionAPI.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdCollectionAPI(TestClass):
@tc_logger
def test_boolean_operator(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_collection.usda")
self.assertTrue(stage)
testPrim = stage.GetPrimAtPath("/CollectionTest")
self.assertTrue(testPrim)
explicitColl = Usd.CollectionAPI(testPrim, "leafGeom")
self.assertTrue(explicitColl)
explicitColl = Usd.CollectionAPI(testPrim, "test")
self.assertFalse(explicitColl)
@tc_logger
def test_create_relationship(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_collection.usda")
self.assertTrue(stage)
testPrim = stage.GetPrimAtPath("/CollectionTest")
sphere = stage.GetPrimAtPath("/CollectionTest/Geom/Shapes/Sphere")
self.assertTrue(testPrim)
self.assertTrue(sphere.IsValid())
self.assertTrue(testPrim.ApplyAPI("CollectionAPI:test"))
explicitColl = Usd.CollectionAPI(testPrim, "test")
self.assertTrue(explicitColl)
# create rel using schema api
rel = explicitColl.CreateIncludesRel()
self.assertTrue(rel)
rel.AddTarget(sphere.GetPath())
self.assertTrue(rel.HasAuthoredTargets())
# verify using prim api
relVerify = testPrim.GetRelationship("collection:test:includes")
self.assertTrue(relVerify)
self.assertTrue(relVerify.HasAuthoredTargets())
@tc_logger
def test_get_relationship(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_collection.usda")
self.assertTrue(stage)
testPrim = stage.GetPrimAtPath("/CollectionTest")
sphere = stage.GetPrimAtPath("/CollectionTest/Geom/Shapes/Sphere")
self.assertTrue(testPrim)
self.assertTrue(sphere.IsValid())
self.assertTrue(testPrim.ApplyAPI("CollectionAPI:test"))
# create relationship using prim api
rel = testPrim.CreateRelationship("collection:test:includes", False)
self.assertTrue(rel)
rel.AddTarget(sphere.GetPath())
self.assertTrue(rel.HasAuthoredTargets())
# verify get relationship using schema api
coll = Usd.CollectionAPI(testPrim, "test")
inclRel = coll.GetIncludesRel()
self.assertTrue(inclRel)
self.assertTrue(inclRel.GetName() == "collection:test:includes")
self.assertTrue(inclRel.HasAuthoredTargets())
| 3,638 | Python | 29.325 | 81 | 0.685542 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_attribute.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
if platform.processor() == "aarch64":
# warp not supported on aarch64 yet for our testing
return
import warp as wp
wp.init()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdAttribute(TestClass):
@tc_logger
def test_get(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, UsdLux
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr)
result = False
result = attr.Get()
self.assertTrue(result)
self.assertTrue(isinstance(result, bool))
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdLux.Tokens.inputsIntensity)
self.assertTrue(attr)
result = 5.0
result = attr.Get()
self.assertEquals(result, 150.0)
self.assertTrue(isinstance(result, float))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.faceVertexIndices)
self.assertTrue(attr)
result = attr.Get()
self.assertEquals(len(result), 4)
self.assertTrue(result.IsFabricData())
self.assertEquals(result[0], 1)
self.assertEquals(result[1], 3)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute(UsdLux.Tokens.inputsColor)
result = attr.Get()
self.assertTrue(isinstance(result, Gf.Vec3f))
self.assertEquals(result, Gf.Vec3f(1, 1, 1))
attr = prim.GetAttribute(UsdGeom.Tokens.visibility)
result = attr.Get()
self.assertEquals(result, UsdGeom.Tokens.inherited)
prim = stage.GetPrimAtPath(Sdf.Path("/Cube_5/subset/BasicShapeMaterial/BasicShapeMaterial"))
attr = prim.GetAttribute("path")
result = attr.Get()
self.assertEquals(result, "/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial")
# invalid attr should not cause crash
attr = prim.GetAttribute("invalid")
self.assertFalse(attr)
self.assertFalse(attr.Get())
@tc_logger
def test_set(self):
from usdrt import Gf, Sdf, Usd, UsdGeom, UsdLux, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr)
result = False
result = attr.Get()
self.assertTrue(result)
self.assertTrue(isinstance(result, bool))
attr.Set(False)
result = attr.Get()
self.assertFalse(result)
self.assertTrue(isinstance(result, bool))
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdLux.Tokens.inputsIntensity)
self.assertTrue(attr)
result = 5.0
result = attr.Get()
self.assertEquals(result, 150.0)
self.assertTrue(isinstance(result, float))
attr.Set(15.5)
result = attr.Get()
self.assertEquals(result, 15.5)
self.assertTrue(isinstance(result, float))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.faceVertexIndices)
self.assertTrue(attr)
newValues = Vt.IntArray([9, 8, 7, 6])
self.assertTrue(attr.Set(newValues))
result = attr.Get()
self.assertEquals(len(result), 4)
self.assertTrue(result.IsFabricData())
for i in range(4):
self.assertEquals(result[i], 9 - i)
newValues = Vt.IntArray([0, 1, 2, 3, 4, 5, 6])
self.assertTrue(attr.Set(newValues))
result = attr.Get()
self.assertEquals(len(result), 7)
self.assertTrue(result.IsFabricData())
for i in range(7):
self.assertEquals(result[i], i)
prim = stage.GetPrimAtPath(Sdf.Path("/DistantLight"))
attr = prim.GetAttribute(UsdLux.Tokens.inputsColor)
newColor = Gf.Vec3f(0, 0.5, 0.5)
self.assertTrue(attr.Set(newColor))
vecCheck = attr.Get()
self.assertTrue(isinstance(vecCheck, Gf.Vec3f))
self.assertEquals(vecCheck, Gf.Vec3f(0, 0.5, 0.5))
# setting with an invalid type for the attr should fail
self.assertFalse(attr.Set("stringvalue"))
result = attr.Get()
self.assertEquals(result, Gf.Vec3f(0, 0.5, 0.5))
attr = prim.GetAttribute(UsdGeom.Tokens.visibility)
result = attr.Get()
self.assertEquals(result, UsdGeom.Tokens.inherited)
self.assertTrue(attr.Set(UsdGeom.Tokens.invisible))
result = attr.Get()
self.assertEquals(result, UsdGeom.Tokens.invisible)
prim = stage.GetPrimAtPath(Sdf.Path("/Cube_5/subset/BasicShapeMaterial/BasicShapeMaterial"))
attr = prim.GetAttribute("path")
result = attr.Get()
self.assertEquals(result, "/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial")
newString = "/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial100"
self.assertTrue(attr.Set(newString))
result = attr.Get()
self.assertEquals(result, "/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial100")
# invalid attr should not cause crash
attr = prim.GetAttribute("invalid")
self.assertFalse(attr)
self.assertFalse(attr.Set("stringvalue"))
@tc_logger
def test_has_value(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr.HasValue())
attr2 = prim.GetAttribute(UsdGeom.Tokens.purpose)
self.assertFalse(attr2.HasValue())
# invalid attr should not cause crash
attr = prim.GetAttribute("invalid")
self.assertFalse(attr)
self.assertFalse(attr.HasValue())
@tc_logger
def test_name(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.primvarsDisplayColor)
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
self.assertEquals(attr.GetName(), UsdGeom.Tokens.primvarsDisplayColor)
self.assertEquals(attr.GetBaseName(), "displayColor")
self.assertEquals(attr.GetNamespace(), "primvars")
parts = attr.SplitName()
self.assertEquals(len(parts), 2)
self.assertEquals(parts[0], "primvars")
self.assertEquals(parts[1], "displayColor")
@tc_logger
def test_create_every_attribute_type(self):
from usdrt import Gf, Sdf, Usd, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/test"), "Xform")
self.assertTrue(prim)
# These are the types that I know are missing support, either
# because Fabric doesn't support them (string array), or USDRT hasn't implemented
# support yet (assets), or there will never be a Python rep (PrimTagType)
KNOWN_INVALID_TYPES = [
"StringArray",
]
KNOWN_UNSUPPORTED_TYPES = [
"Frame4d",
"Frame4dArray",
]
NO_DATA_TAG_TYPES = [
"PrimTypeTag",
"AppliedSchemaTypeTag",
"AncestorPrimTypeTag",
"Tag",
]
# These are the types that should be supported and are not for some
# reason - OM-53013
FIXME_UNSUPPORTED_TYPES = [
"Matrix2d",
"Matrix2dArray",
"TimeCode",
"TimeCodeArray",
]
for type_name in dir(Sdf.ValueTypeNames):
if type_name.startswith("__"):
continue
if type_name in KNOWN_INVALID_TYPES:
continue
value_type_name = getattr(Sdf.ValueTypeNames, type_name)
if not isinstance(value_type_name, Sdf.ValueTypeName):
continue
attr = prim.CreateAttribute(type_name, value_type_name, True)
self.assertTrue(attr)
result = attr.Get()
if result is None:
# Python bindings warn about unsupported type using C++ name,
# add a note to clarify using SdfValueTypeName
self.assertTrue(
type_name in KNOWN_UNSUPPORTED_TYPES
or type_name in FIXME_UNSUPPORTED_TYPES
or type_name in NO_DATA_TAG_TYPES
)
if type_name in FIXME_UNSUPPORTED_TYPES:
reason = "this will be fixed eventually"
elif type_name in KNOWN_UNSUPPORTED_TYPES:
reason = "this is intentional"
elif type_name in NO_DATA_TAG_TYPES:
reason = "expected no data attribute"
print(f"i.e. SdfValueTypeName.{type_name} - {reason}")
@tc_logger
def test_get_type(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.faceVertexCounts)
self.assertTrue(attr)
self.assertEqual(attr.GetTypeName(), Sdf.ValueTypeNames.IntArray)
attr = prim.GetAttribute(UsdGeom.Tokens.normals)
self.assertTrue(attr)
self.assertEqual(attr.GetTypeName(), Sdf.ValueTypeNames.Normal3fArray)
# invalid attr should not cause crash
attr = prim.GetAttribute("invalid")
self.assertFalse(attr)
self.assertFalse(attr.GetTypeName())
@tc_logger
def test_get_type(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.faceVertexCounts)
self.assertTrue(attr)
expected = "Attribute(</Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back.faceVertexCounts>)"
self.assertEqual(repr(attr), expected)
@tc_logger
def test_cpu_gpu_data_sync(self):
if platform.processor() == "aarch64":
return
from usdrt import Sdf, Usd, UsdGeom, Vt
try:
import warp as wp
except ImportError:
if TestClass is omni.kit.test.AsyncTestCase:
# warp not available for testing in kit at this time
return
raise
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
attr = prim.GetAttribute(UsdGeom.Tokens.points)
self.assertTrue(attr)
self.assertTrue(attr.IsCpuDataValid())
self.assertFalse(attr.IsGpuDataValid())
# Force sync to GPU
attr.SyncDataToGpu()
self.assertTrue(attr.IsCpuDataValid())
self.assertTrue(attr.IsGpuDataValid())
# Write a new GPU value
points = attr.Get()
wp_points = wp.array(points, device="cpu")
with wp.ScopedCudaGuard():
wpgpu_points = wp_points.to("cuda")
vt_gpu = Vt.Vec3fArray(wpgpu_points)
attr.Set(vt_gpu)
wp.synchronize()
self.assertFalse(attr.IsCpuDataValid())
self.assertTrue(attr.IsGpuDataValid())
# Force sync to CPU
attr.SyncDataToCpu()
self.assertTrue(attr.IsCpuDataValid())
self.assertTrue(attr.IsGpuDataValid())
# Invalidate data on CPU
attr.InvalidateCpuData()
self.assertFalse(attr.IsCpuDataValid())
self.assertTrue(attr.IsGpuDataValid())
# Invalidate data on GPU
attr.InvalidateGpuData()
self.assertTrue(attr.IsCpuDataValid())
self.assertFalse(attr.IsGpuDataValid())
# Test Connections
@tc_logger
def test_has_authored_connections(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
self.assertTrue(attr.HasAuthoredConnections())
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:surface"))
self.assertTrue(attr)
self.assertFalse(attr.HasAuthoredConnections())
attr = stage.GetAttributeAtPath(
Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.info:implementationSource")
)
self.assertTrue(attr)
self.assertFalse(attr.HasAuthoredConnections())
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.HasAuthoredConnections())
@tc_logger
def test_get_connections(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out"))
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.GetConnections())
@tc_logger
def test_add_connection(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
path = Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement")
attr = stage.GetAttributeAtPath(path)
self.assertTrue(attr)
new_connection = Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:surface")
self.assertTrue(attr.AddConnection(new_connection))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], new_connection)
# add a connection to a new attribute
proxy_prim_connection = Sdf.Path("/Cube_5")
prim = stage.GetPrimAtPath("/Cornell_Box")
self.assertTrue(prim)
attr = prim.CreateAttribute("testAttr", Sdf.ValueTypeNames.Token, True)
self.assertTrue(attr)
self.assertTrue(attr.AddConnection(proxy_prim_connection))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cube_5"))
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.AddConnection(Sdf.Path("/Cube_5")))
@tc_logger
def test_remove_connection(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
# It's valid to try to remove a connection that is not
# in the list of connections
connection_not_in_list = Sdf.Path("/Foo/Bar")
self.assertTrue(attr.RemoveConnection(connection_not_in_list))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out"))
# Removing a valid connection will return empty connection lists with GetConnections
connection_in_list = Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out")
self.assertTrue(attr.RemoveConnection(connection_in_list))
connections = attr.GetConnections()
self.assertEqual(len(connections), 0)
# multiple connections not supported yet
# test removing if there are multiple in the list
# multiple_connections = [Sdf.Path("/Foo"), Sdf.Path("/Bar")]
# self.assertTrue(attr.SetConnections(multiple_connections))
# self.assertTrue(attr.RemoveConnection(Sdf.Path("/Bar")))
# connections = attr.GetConnections()
# self.assertEqual(len(connections), 1)
# self.assertEqual(connections[0], Sdf.Path("/Foo"))
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.RemoveConnection(Sdf.Path("/Cube_5")))
@tc_logger
def test_clear_connections(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out"))
self.assertTrue(attr.ClearConnections())
connections = attr.GetConnections()
self.assertEqual(len(connections), 0)
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.ClearConnections())
@tc_logger
def test_set_connections(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Looks/Green1SG.outputs:mdl:displacement"))
self.assertTrue(attr)
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Green1SG/Green_Side.outputs:out"))
new_connections = [Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side.outputs:out")]
self.assertTrue(attr.SetConnections(new_connections))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side.outputs:out"))
too_many_connections = [Sdf.Path("/Foo"), Sdf.Path("/Bar")]
# do nothing for now, this isnt supported
self.assertFalse(attr.SetConnections(too_many_connections))
connections = attr.GetConnections()
self.assertEqual(len(connections), 1)
# same as previous connection
self.assertEqual(connections[0], Sdf.Path("/Cornell_Box/Root/Looks/Red1SG/Red_Side.outputs:out"))
# invalid attr should not cause crash
attr = stage.GetAttributeAtPath("/Cornell_Box.invalid")
self.assertFalse(attr)
self.assertFalse(attr.SetConnections(new_connections))
| 21,466 | Python | 34.897993 | 110 | 0.642178 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_assetpath.py | __copyright__ = "Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestSdfAssetPath(TestClass):
@tc_logger
def test_ctor(self):
from usdrt import Sdf
emptypath = Sdf.AssetPath()
self.assertEqual(emptypath.path, "")
self.assertEqual(emptypath.resolvedPath, "")
asset_only = Sdf.AssetPath("hello")
self.assertEqual(asset_only.path, "hello")
self.assertEqual(asset_only.resolvedPath, "")
asset_and_resolved = Sdf.AssetPath("hello", "hello.txt")
self.assertEqual(asset_and_resolved.path, "hello")
self.assertEqual(asset_and_resolved.resolvedPath, "hello.txt")
@tc_logger
def test_get_asset(self):
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath("/Cornell_Box/Root/Looks/Green1SG/Green_Side")
self.assertTrue(prim)
attr = prim.GetAttribute("info:mdl:sourceAsset")
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
val = attr.Get()
self.assertEqual(val.path, "./Green_Side.mdl")
self.assertTrue(os.path.normpath(val.resolvedPath).endswith(os.path.normpath("data/usd/tests/Green_Side.mdl")))
@tc_logger
def test_get_assetlist(self):
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_assetlist.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/World"))
self.assertTrue(prim)
attr = prim.GetAttribute("test:assetlist")
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
val = attr.Get()
self.assertEqual(len(val), 3)
unresolved = ["./asset.txt", "./asset_other.txt", "./existing_1042.txt"]
resolved_ends = [
os.path.normpath(i)
for i in ["data/usd/tests/asset.txt", "data/usd/tests/asset_other.txt", "data/usd/tests/existing_1042.txt"]
]
for i in range(3):
self.assertEqual(val[i].path, unresolved[i])
self.assertTrue(os.path.normpath(val[i].resolvedPath).endswith(resolved_ends[i]))
@tc_logger
def test_set_asset(self):
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath("/Cornell_Box/Root/Looks/Green1SG/Green_Side")
self.assertTrue(prim)
attr = prim.GetAttribute("info:mdl:sourceAsset")
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
newval = Sdf.AssetPath("hello", "hello.txt")
self.assertTrue(attr.Set(newval))
val = attr.Get()
self.assertEqual(val.path, "hello")
self.assertEqual(val.resolvedPath, "hello.txt")
@tc_logger
def test_set_assetlist(self):
from usdrt import Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/test_assetlist.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/World"))
self.assertTrue(prim)
attr = prim.GetAttribute("test:assetlist")
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
newval = Vt.AssetArray(4)
for i in range(4):
newval[i] = Sdf.AssetPath(f"hello{i}", f"hello{i}.txt")
attr.Set(newval)
# Freeing the original array must be fine
del newval
val = attr.Get()
self.assertEqual(len(val), 4)
for i in range(4):
self.assertEqual(val[i].path, f"hello{i}")
self.assertEqual(val[i].resolvedPath, f"hello{i}.txt")
| 4,750 | Python | 28.509317 | 119 | 0.638526 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_cube.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestUsdGeomCube(TestClass):
@tc_logger
def test_get_attribute(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cube.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cube/Geom/cube"))
self.assertTrue(prim)
cube = UsdGeom.Cube(prim)
self.assertTrue(cube)
# create attribute using prim api
attr = prim.CreateAttribute(UsdGeom.Tokens.size, Sdf.ValueTypeNames.Double, False)
self.assertTrue(attr)
# verify get attribute using schema api
cubeAttr = cube.GetSizeAttr()
self.assertTrue(cubeAttr)
self.assertTrue(cubeAttr.GetName() == "size")
val = cubeAttr.Get()
assert val == 25
@tc_logger
def test_create_attribute(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/Cube/Geom/cube"), "Cube")
self.assertFalse(prim.HasAttribute("size"))
# create attribute using schema api
cube = UsdGeom.Cube(prim)
self.assertTrue(cube)
attr = cube.CreateSizeAttr()
# verify using prim api
self.assertTrue(attr)
self.assertTrue(prim.HasAttribute(UsdGeom.Tokens.size))
self.assertTrue(attr.GetName() == "size")
@tc_logger
def test_boolean_operator(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cube.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath("/Cube/Geom/cube")
self.assertTrue(prim)
# is this a valid schema object?
self.assertTrue(UsdGeom.Cube(prim))
self.assertTrue(prim)
self.assertFalse(UsdGeom.Cone(prim))
self.assertTrue(prim)
# verify we have an api applied
self.assertTrue(prim.HasAPI("MotionAPI"))
# is this a valid api applied in fabric?
self.assertTrue(UsdGeom.MotionAPI(prim))
self.assertFalse(UsdGeom.VisibilityAPI(prim))
@tc_logger
def test_define(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
prim = UsdGeom.Cube.Define(stage, Sdf.Path("/Cube/Geom/cube"))
self.assertTrue(prim)
| 3,504 | Python | 27.266129 | 90 | 0.658961 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_schema_base.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestSchemaBase(TestClass):
@tc_logger
def test_invalid_schema_base(self):
from usdrt import Sdf, Usd
sb = Usd.SchemaBase()
# Conversion to bool should return False.
self.assertFalse(sb)
# It should still be safe to get the prim, but the prim will be invalid.
p = sb.GetPrim()
self.assertFalse(p.IsValid())
# It should still be safe to get the path, but the path will be empty.
self.assertEqual(sb.GetPrimPath(), Sdf.Path(""))
# Try creating a CollectionAPI from it, and make sure the result is
# a suitably invalid CollactionAPI object.
coll = Usd.CollectionAPI(sb, "newcollection")
self.assertFalse(coll)
# revisit
# with self.assertRaises(RuntimeError):
# coll.CreateExpansionRuleAttr()
class TestImports(TestClass):
@tc_logger
def test_usd_schema_imports(self):
try:
from usdrt import Usd
except ImportError:
self.fail("from usdrt import Usd failed")
try:
from usdrt import UsdGeom
except ImportError:
self.fail("from usdrt import UsdGeom failed")
try:
from usdrt import UsdLux
except ImportError:
self.fail("from usdrt import UsdLux failed")
try:
from usdrt import UsdMedia
except ImportError:
self.fail("from usdrt import UsdMedia failed")
try:
from usdrt import UsdRender
except ImportError:
self.fail("from usdrt import UsdRender failed")
try:
from usdrt import UsdShade
except ImportError:
self.fail("from usdrt import UsdShade failed")
try:
from usdrt import UsdSkel
except ImportError:
self.fail("from usdrt import UsdSkel failed")
try:
from usdrt import UsdUI
except ImportError:
self.fail("from usdrt import UsdUI failed")
try:
from usdrt import UsdVol
except ImportError:
self.fail("from usdrt import UsdVol failed")
# Nvidia Schemas
try:
from usdrt import UsdPhysics
except ImportError:
self.fail("from usdrt import UsdPhysics failed")
try:
from usdrt import PhysxSchema
except ImportError:
self.fail("from usdrt import PhysxSchema failed")
try:
from usdrt import ForceFieldSchema
except ImportError:
self.fail("from usdrt import ForceFieldSchema failed")
try:
from usdrt import DestructionSchema
except ImportError:
self.fail("from usdrt import DestructionSchema failed")
| 3,879 | Python | 27.740741 | 80 | 0.633668 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_stage.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import random
import sys
import tempfile
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
def get_tmp_usda_path(outdir):
timestr = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
randstr = random.randint(0, 32767)
return os.path.join(outdir, f"{timestr}_{randstr}.usda")
class TestUsdStage(TestClass):
@tc_logger
def test_open(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
@tc_logger
def test_create_new(self):
from usdrt import Sdf, Usd
with tempfile.TemporaryDirectory() as tempdir:
stage = Usd.Stage.CreateNew(get_tmp_usda_path(tempdir))
self.assertTrue(stage)
@tc_logger
def test_attach(self):
import pxr
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
layer = pxr.Sdf.Layer.FindOrOpen(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage = cache.FindOneMatching(layer)
stage_id = cache.GetId(usd_stage).ToLongInt()
attached_stage = Usd.Stage.Attach(stage_id)
self.assertTrue(attached_stage)
# verify attached stage can access stage in progress
prim = attached_stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
# verify destruction of attached stage does not destroy stage in progress
del attached_stage
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
cache.Clear()
@tc_logger
def test_attach_no_swh(self):
import pxr
from usdrt import Sdf, Usd
# Note - no SWH created here
stage = pxr.Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
id = cache.Insert(stage)
stage_id = id.ToLongInt()
# This creates the SWH
self.assertFalse(Usd.Stage.SimStageWithHistoryExists(stage_id))
attached_stage = Usd.Stage.Attach(stage_id)
self.assertTrue(attached_stage)
self.assertTrue(Usd.Stage.SimStageWithHistoryExists(stage_id))
# verify attached stage can access stage in progress
prim = attached_stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
# verify that assumed ownership cleans up SWH on destruction
self.assertTrue(Usd.Stage.SimStageWithHistoryExists(stage_id))
# deprecated API support for 104
self.assertTrue(Usd.Stage.StageWithHistoryExists(stage_id))
del attached_stage
self.assertFalse(Usd.Stage.SimStageWithHistoryExists(stage_id))
# deprecated API support for 104
self.assertFalse(Usd.Stage.StageWithHistoryExists(stage_id))
cache.Clear()
@tc_logger
def test_invalid_swh_id(self):
import pxr
from usdrt import Sdf, Usd
# OM-85698 can pass invalid ID to StageWithHistoryExists
self.assertFalse(Usd.Stage.SimStageWithHistoryExists(-1))
self.assertFalse(Usd.Stage.StageWithHistoryExists(-1))
@tc_logger
def test_get_sip_id(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
id = stage.GetStageReaderWriterId()
self.assertNotEqual(id.id, 0)
# deprecated API support for 104
id2 = stage.GetStageInProgressId()
self.assertNotEqual(id2.id, 0)
self.assertEqual(id.id, id2.id)
@tc_logger
def test_get_prim_at_path(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
@tc_logger
def test_get_prim_at_path_invalid(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Invalid"))
self.assertFalse(prim)
@tc_logger
def test_get_prim_at_path_only_in_fabric(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
defined = stage.DefinePrim("/Test", "Cube")
self.assertTrue(defined)
got = stage.GetPrimAtPath("/Test")
self.assertTrue(got)
self.assertEqual(got.GetName(), "Test")
@tc_logger
def test_get_default_prim(self):
from usdrt import Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetDefaultPrim()
self.assertTrue(prim)
self.assertTrue(prim.GetName() == "Cornell_Box")
@tc_logger
def test_get_pseudo_root(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPseudoRoot()
self.assertTrue(prim)
self.assertTrue(prim.GetPath() == Sdf.Path("/"))
@tc_logger
def test_define_prim(self):
from usdrt import Sdf, Usd
with tempfile.TemporaryDirectory() as tempdir:
stage = Usd.Stage.CreateNew(get_tmp_usda_path(tempdir))
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/Test"), "Mesh")
self.assertTrue(prim)
self.assertEqual(prim.GetName(), "Test")
self.assertEqual(prim.GetTypeName(), "Mesh")
prim_notype = stage.DefinePrim(Sdf.Path("/Test2"))
self.assertTrue(prim_notype)
self.assertEqual(prim_notype.GetName(), "Test2")
self.assertEqual(prim_notype.GetTypeName(), "")
@tc_logger
def test_define_prim_with_complete_type(self):
from usdrt import Sdf, Usd
# OM-90066 - use either alias or complete type name to define prim
with tempfile.TemporaryDirectory() as tempdir:
stage = Usd.Stage.CreateNew(get_tmp_usda_path(tempdir))
self.assertTrue(stage)
prim = stage.DefinePrim(Sdf.Path("/Test"), "Mesh")
self.assertTrue(prim)
self.assertEqual(prim.GetName(), "Test")
self.assertEqual(prim.GetTypeName(), "Mesh")
prim = stage.DefinePrim(Sdf.Path("/Test2"), "UsdGeomMesh")
self.assertTrue(prim)
self.assertEqual(prim.GetTypeName(), "Mesh")
result = stage.GetPrimsWithTypeName("Xformable")
self.assertEqual(len(result), 2)
self.assertTrue(Sdf.Path("/Test") in result)
self.assertTrue(Sdf.Path("/Test2") in result)
@tc_logger
def test_get_attribute_at_path(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back.points"))
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
self.assertTrue(attr.GetName() == UsdGeom.Tokens.points)
@tc_logger
def test_get_attribute_at_path_invalid(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
attr = stage.GetAttributeAtPath(Sdf.Path("/Invalid.points"))
self.assertFalse(attr)
attr = stage.GetAttributeAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(attr)
@tc_logger
def test_get_relationship_at_path(self):
from usdrt import Sdf, Usd, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(
Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/Green_Wall/Green1SG.material:binding")
)
self.assertTrue(rel)
self.assertTrue(rel.HasAuthoredTargets())
self.assertEqual(rel.GetName(), UsdShade.Tokens.materialBinding)
@tc_logger
def test_get_relationship_at_path_invalid(self):
from usdrt import Sdf, Usd, UsdShade
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
rel = stage.GetRelationshipAtPath(Sdf.Path("/Invalid.material:binding"))
self.assertFalse(rel)
rel = stage.GetRelationshipAtPath(Sdf.Path("/Cornell_Box.invalid"))
self.assertFalse(rel)
@tc_logger
def test_traverse(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
self.assertTrue(prim)
prim_range = stage.Traverse()
self.assertTrue(prim_range)
count = 0
for this_prim in prim_range:
count += 1
prim = this_prim
self.assertTrue(count == 40)
self.assertEqual(prim.GetPath(), Sdf.Path("/RectLight"))
@tc_logger
def test_write_layer(self):
"""
Note that in this implementation, WriteToLayer has the same limitations
as Fabric's exportUsd. New prims are not typed, empty prims may be
defined as overs, etc...
"""
import pxr
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
world = stage.DefinePrim(Sdf.Path("/World"), "Xform")
triangle = stage.DefinePrim(Sdf.Path("/World/Triangle"), "Mesh")
points = triangle.CreateAttribute(UsdGeom.Tokens.points, Sdf.ValueTypeNames.Point3fArray, False)
faceVertexCounts = triangle.CreateAttribute(UsdGeom.Tokens.faceVertexCounts, Sdf.ValueTypeNames.IntArray, False)
faceVertexIndices = triangle.CreateAttribute(
UsdGeom.Tokens.faceVertexIndices, Sdf.ValueTypeNames.IntArray, False
)
points.Set(Vt.Vec3fArray([Gf.Vec3f(1, 0, 0), Gf.Vec3f(0, 1, 0), Gf.Vec3f(-1, 0, 0)]))
faceVertexCounts.Set(Vt.IntArray([3]))
faceVertexIndices.Set(Vt.IntArray([0, 1, 2]))
with tempfile.TemporaryDirectory() as tempdir:
test_file = get_tmp_usda_path(tempdir)
stage.WriteToLayer(test_file)
# Verfiy that data was stored to the new layer
test_stage = pxr.Usd.Stage.Open(test_file)
attr = test_stage.GetAttributeAtPath(pxr.Sdf.Path("/World/Triangle.points"))
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
self.assertEqual(len(attr.Get()), 3)
prim = test_stage.GetPrimAtPath(pxr.Sdf.Path("/World/Triangle"))
self.assertEqual(prim.GetTypeName(), "Mesh")
@tc_logger
def test_write_stage(self):
"""
Note that in this implementation, WriteToStage has the same limitations
as Fabric's cacheToUsd. Most importantly, new prims defined in
Fabric are not written out to the USD Stage
"""
import pxr
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
layer = pxr.Sdf.Layer.FindOrOpen(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage = cache.FindOneMatching(layer)
stage_id = cache.GetId(usd_stage).ToLongInt()
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
self.assertTrue(prim)
# Change doubleSided to False in Fabric
attr = prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertTrue(attr)
result = attr.Set(False)
self.assertTrue(result)
attr = prim.GetAttribute(UsdGeom.Tokens.normals)
self.assertTrue(attr)
result = attr.Get()
self.assertEquals(len(result), 4)
for i in range(4):
self.assertEquals(result[i], Gf.Vec3f(0, 0, -1))
# Change normals to (1, 0, 0) in Fabric
self.assertTrue(result.IsFabricData())
for i in range(4):
result[i] = Gf.Vec3f(1, 0, 0)
stage.WriteToStage()
usd_prim = usd_stage.GetPrimAtPath(pxr.Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back"))
# Verify doubleSided is now false on USD stage
usd_attr = usd_prim.GetAttribute(UsdGeom.Tokens.doubleSided)
self.assertFalse(usd_attr.Get())
# Verify normals are now (1, 0, 0) on USD stage
usd_attr = usd_prim.GetAttribute(UsdGeom.Tokens.normals)
new_normals = usd_attr.Get()
self.assertEquals(len(new_normals), 4)
for i in range(4):
self.assertEquals(new_normals[i], pxr.Gf.Vec3f(1, 0, 0))
# Clear stage cache, since we modified the USD stage
cache.Clear()
@tc_logger
def test_set_attribute_value(self):
from usdrt import Gf, Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
newNormals = Vt.Vec3fArray([Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0)])
attrPath = Sdf.Path("/Cornell_Box/Root/Cornell_Box1_LP/White_Wall_Back.normals")
result = stage.SetAttributeValue(attrPath, newNormals)
self.assertTrue(result)
attr = stage.GetAttributeAtPath(attrPath)
self.assertTrue(attr)
value = attr.Get()
for i in range(4):
self.assertEquals(value[i], Gf.Vec3f(1, 0, 0))
@tc_logger
def test_set_attribute_value_invalid_prim(self):
from usdrt import Gf, Sdf, Usd, Vt
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
newNormals = Vt.Vec3fArray([Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0), Gf.Vec3f(1, 0, 0)])
attrPath = Sdf.Path("/Invalid.normals")
result = stage.SetAttributeValue(attrPath, newNormals)
self.assertFalse(result)
@tc_logger
def test_has_prim_at_path(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# No prims populated into Fabric yet
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
# Prim is now in Fabric
self.assertTrue(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
# OM-87225
# prim not in fabric
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cube_5")))
# do a stage query, this will tag everything with metadata
paths = stage.GetPrimsWithTypeName("Mesh")
# prim not in fabric when we ignore tags by default
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cube_5")))
# prim in fabric if we include tags in the query
self.assertTrue(stage.HasPrimAtPath(Sdf.Path("/Cube_5"), excludeTags=False))
@tc_logger
def test_remove_prim(self):
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
# No prims populated into Fabric yet
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
prim = stage.GetPrimAtPath(Sdf.Path("/Cornell_Box"))
# Prim is now in Fabric
self.assertTrue(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
self.assertTrue(stage.RemovePrim(Sdf.Path("/Cornell_Box")))
# Prim removed from Fabric by RemovePrim
self.assertFalse(stage.HasPrimAtPath(Sdf.Path("/Cornell_Box")))
# Remove non-existant prim does not cause crash, but returns False
self.assertFalse(stage.RemovePrim(Sdf.Path("/Cornell_Box")))
@tc_logger
def test_remove_prim_from_usd(self):
import pxr
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
layer = pxr.Sdf.Layer.FindOrOpen(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage = cache.FindOneMatching(layer)
stage_id = cache.GetId(usd_stage).ToLongInt()
path = "/DistantLight/BillboardComponent_0"
# Populate into Fabric
prim = stage.GetPrimAtPath(Sdf.Path(path))
# Remove from USD stage
usd_stage.RemovePrim(path)
# The prim is still in Fabric
self.assertTrue(stage.HasPrimAtPath(Sdf.Path(path)))
expected_attrs = [UsdGeom.Tokens.visibility, UsdGeom.Tokens.xformOpOrder, "xformOp:transform"]
for attr in prim.GetAttributes():
self.assertTrue(attr.GetName() in expected_attrs)
# Removing prim from Fabric is okay
self.assertTrue(stage.RemovePrim(Sdf.Path(path)))
self.assertFalse(stage.HasPrimAtPath(Sdf.Path(path)))
cache.Clear()
@tc_logger
def test_repr_representation(self):
import pxr
from usdrt import Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
cache = pxr.UsdUtils.StageCache.Get()
layer = pxr.Sdf.Layer.FindOrOpen(TEST_DIR + "/data/usd/tests/cornell.usda")
usd_stage = cache.FindOneMatching(layer)
stage_id = cache.GetId(usd_stage).ToLongInt()
expected = "Stage(<ID: " + str(stage_id) + ">)"
self.assertEquals(repr(stage), expected)
@tc_logger
def test_layer_rewrite(self):
# OM-70883
import pxr
from usdrt import Gf, Sdf, Usd, UsdGeom, Vt
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(stage)
world = stage.DefinePrim(Sdf.Path("/World"), "Xform")
triangle = stage.DefinePrim(Sdf.Path("/World/Triangle"), "Mesh")
points = triangle.CreateAttribute(UsdGeom.Tokens.points, Sdf.ValueTypeNames.Point3fArray, False)
faceVertexCounts = triangle.CreateAttribute(UsdGeom.Tokens.faceVertexCounts, Sdf.ValueTypeNames.IntArray, False)
faceVertexIndices = triangle.CreateAttribute(
UsdGeom.Tokens.faceVertexIndices, Sdf.ValueTypeNames.IntArray, False
)
points.Set(Vt.Vec3fArray([Gf.Vec3f(1, 0, 0), Gf.Vec3f(0, 1, 0), Gf.Vec3f(-1, 0, 0)]))
faceVertexCounts.Set(Vt.IntArray([3]))
faceVertexIndices.Set(Vt.IntArray([0, 1, 2]))
with tempfile.TemporaryDirectory() as tempdir:
test_file = get_tmp_usda_path(tempdir)
stage.WriteToLayer(test_file)
# In OM-70883, multiple WriteToLayer on the same file causes a crash
stage.WriteToLayer(test_file)
# Verfiy that data was stored to the new layer
test_stage = pxr.Usd.Stage.Open(test_file)
attr = test_stage.GetAttributeAtPath(pxr.Sdf.Path("/World/Triangle.points"))
self.assertTrue(attr)
self.assertTrue(attr.HasValue())
self.assertEqual(len(attr.Get()), 3)
prim = test_stage.GetPrimAtPath(pxr.Sdf.Path("/World/Triangle"))
self.assertEqual(prim.GetTypeName(), "Mesh")
@tc_logger
def test_get_prims_with_type_name(self):
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
paths = stage.GetPrimsWithTypeName("Mesh")
self.assertEqual(len(paths), 8)
paths = stage.GetPrimsWithTypeName("Shader")
self.assertEqual(len(paths), 5)
paths = stage.GetPrimsWithTypeName("Invalid")
self.assertEqual(len(paths), 0)
paths = stage.GetPrimsWithTypeName("UsdGeomBoundable")
aliasPaths = stage.GetPrimsWithTypeName("Boundable")
self.assertEqual(len(paths), len(aliasPaths))
@tc_logger
def test_get_prims_with_applied_api_name(self):
# Begin example query by API
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
paths = stage.GetPrimsWithAppliedAPIName("ShapingAPI")
self.assertEqual(len(paths), 2)
paths = stage.GetPrimsWithAppliedAPIName("CollectionAPI:lightLink")
self.assertEqual(len(paths), 5)
# End example query by API
paths = stage.GetPrimsWithAppliedAPIName("Invalid:test")
self.assertEqual(len(paths), 0)
@tc_logger
def test_get_prims_with_type_and_applied_api_name(self):
# Begin example query mixed
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
paths = stage.GetPrimsWithTypeAndAppliedAPIName("Mesh", ["CollectionAPI:test"])
self.assertEqual(len(paths), 1)
# End example query mixed
paths = stage.GetPrimsWithTypeAndAppliedAPIName("Invalid", ["Invalid:test"])
self.assertEqual(len(paths), 0)
@tc_logger
def test_get_stage_extent(self):
# Begin example stage extent
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/cornell.usda")
self.assertTrue(stage)
bound = stage.GetStageExtent()
self.assertTrue(Gf.IsClose(bound.GetMin(), Gf.Vec3d(-333.8142, -249.9100, -5.444), 0.01))
self.assertTrue(Gf.IsClose(bound.GetMax(), Gf.Vec3d(247.1132, 249.9178, 500.0), 0.01))
# End example stage extent
@tc_logger
def test_get_prims_with_type_and_scenegraph_instancing(self):
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/xform_component_hierarchy_instances.usda")
self.assertTrue(stage)
# There are 2 prototype proxy meshes on the stage
paths = stage.GetPrimsWithTypeName("Mesh")
self.assertEqual(len(paths), 2)
paths = stage.GetPrimsWithTypeName("Invalid")
self.assertEqual(len(paths), 0)
@tc_logger
def test_get_prims_with_type_and_unknown_schema(self):
from usdrt import Gf, Sdf, Usd
stage = Usd.Stage.Open(TEST_DIR + "/data/usd/tests/TestConversionOnLoad.usda")
self.assertTrue(stage)
# This is an old OG schema that no longer exists
paths = stage.GetPrimsWithTypeName("ComputeGraphSettings")
self.assertEqual(len(paths), 1)
| 23,789 | Python | 32.985714 | 120 | 0.638068 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/scenegraph/tests/test_schema_registry.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 pathlib
import platform
import sys
import time
import unittest
from . import tc_logger
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestSchemaRegistry(TestClass):
@tc_logger
def test_IsA(self):
from usdrt import Sdf, Usd, UsdGeom
stage = Usd.Stage.CreateInMemory("test.usda")
self.assertTrue(bool(stage))
prim = stage.DefinePrim(Sdf.Path("/cube"), "UsdGeomCube")
schemaRegistry = Usd.SchemaRegistry.GetInstance()
self.assertTrue(bool(schemaRegistry))
self.assertTrue(prim.IsA("UsdGeomCube"))
self.assertTrue(prim.IsA("Cube"))
self.assertTrue(prim.IsA(Usd.Typed))
self.assertTrue(prim.IsA(UsdGeom.Cube))
self.assertTrue(prim.IsA(UsdGeom.Xformable))
self.assertTrue(schemaRegistry.IsA(prim.GetTypeName(), Usd.Typed))
self.assertTrue(schemaRegistry.IsA(prim.GetTypeName(), UsdGeom.Cube))
self.assertTrue(schemaRegistry.IsA(UsdGeom.Cube, "UsdTyped"))
self.assertTrue(schemaRegistry.IsA(UsdGeom.Cube, Usd.Typed))
self.assertTrue(schemaRegistry.IsA(prim.GetTypeName(), "UsdTyped"))
self.assertTrue(schemaRegistry.IsA(prim.GetTypeName(), "UsdGeomCube"))
self.assertFalse(schemaRegistry.IsA(prim.GetTypeName(), "UsdGeomCone"))
self.assertFalse(schemaRegistry.IsA(prim.GetTypeName(), "Invalid"))
@tc_logger
def test_IsConcrete(self):
from usdrt import Sdf, Usd
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsConcrete("UsdModelAPI"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsConcrete("invalid"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsConcrete("UsdGeomCube"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsConcrete("Cube"))
@tc_logger
def test_IsAppliedAPISchema(self):
from usdrt import Sdf, Usd
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsAppliedAPISchema("UsdGeomCube"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsAppliedAPISchema("UsdGeomModelAPI"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsAppliedAPISchema("invalid"))
@tc_logger
def test_IsMultipleApplyAPISchema(self):
from usdrt import Sdf, Usd
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsMultipleApplyAPISchema("UsdGeomCube"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsMultipleApplyAPISchema("UsdCollectionAPI"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsMultipleApplyAPISchema("CollectionAPI"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsMultipleApplyAPISchema("invalid"))
@tc_logger
def test_IsTyped(self):
from usdrt import Sdf, Usd
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsTyped("UsdGeomCube"))
self.assertTrue(Usd.SchemaRegistry.GetInstance().IsTyped("Cube"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsTyped("UsdModelAPI"))
self.assertFalse(Usd.SchemaRegistry.GetInstance().IsTyped("invalid"))
@tc_logger
def test_GetSchemaTypeName(self):
from usdrt import Sdf, Usd, UsdGeom
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetSchemaTypeName(UsdGeom.Cube), "UsdGeomCube")
@tc_logger
def test_GetAliasFromName(self):
from usdrt import Sdf, Usd, UsdGeom
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetAliasFromName("Cube"), "Cube")
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetAliasFromName("UsdGeomCube"), "Cube")
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetAliasFromName(""), "")
self.assertEqual(Usd.SchemaRegistry.GetInstance().GetAliasFromName("invalid"), "invalid")
| 4,667 | Python | 36.951219 | 105 | 0.716092 |
omniverse-code/kit/exts/usdrt.scenegraph/usdrt/Rt/__init__.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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.core
# TODO: automate this
from usdrt import Gf, Sdf, Usd
from ._Rt import *
| 542 | Python | 32.937498 | 78 | 0.787823 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/quicklayout.py | # Copyright (c) 2018-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.
#
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
from pathlib import Path
from omni.ui.workspace_utils import CompareDelegate
import carb
import carb.tokens
import json
import omni.client
import omni.ui as ui
import traceback
class QuickLayout:
"""Namespace that has the methods to load and save the layout"""
def __init__(self):
self._dialog = None
def destroy(self): # pragma: no cover
if self._dialog:
self._dialog.destroy()
self._dialog = None
def __on_filter_item(self, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if self._dialog.current_filter_option == 0:
# Show only files with listed extensions
if item.path.endswith(".json"):
return True
else:
return False
else:
# Show All Files (*)
return True
@staticmethod
def __get_workspace_dir() -> str:
"""Return the workspace file"""
token = carb.tokens.get_tokens_interface()
dir = token.resolve("${data}")
# FilePickerDialog needs the capital drive. In case it's linux, the
# first letter will be / and it's still OK.
dir = dir[:1].upper() + dir[1:]
return dir
@staticmethod
def __get_workspace_file() -> str:
"""Return the workspace file"""
dir = QuickLayout.__get_workspace_dir()
return f"{dir}/user.layout.json"
def __on_apply_save(self, filename: str, dir: str):
"""Called when the user presses the Save button in the dialog"""
# Get the file extension from the filter
if self._dialog.current_filter_option == 0 and not filename.lower().endswith(".json"):
filename += ".json"
self._dialog.hide()
self.save_file(omni.client.combine_urls(dir if dir.endswith("/") else dir+"/", filename))
def __on_apply_load(self, filename, dir):
"""Called when the user presses the Load button in the dialog"""
self._dialog.hide()
self.load_file(omni.client.combine_urls(dir if dir.endswith("/") else dir+"/", filename))
@staticmethod
def save_file(workspace_file: str):
"""Save the layout to the workspace file"""
workspace_dump = ui.Workspace.dump_workspace()
payload = bytes(json.dumps(workspace_dump, sort_keys=True, indent=2).encode("utf-8"))
result = omni.client.write_file(workspace_file, payload)
if result != omni.client.Result.OK: # pragma: no cover
carb.log_error(f"[quicklayout] The workspace cannot be written to {workspace_file}, error code: {result}")
return
carb.log_info(f"[quicklayout] The workspace saved to {workspace_file}")
@staticmethod
def load_file(workspace_file: str, keep_windows_open=False):
"""Load the layout from the workspace file"""
result, _, content = omni.client.read_file(workspace_file)
if result != omni.client.Result.OK: # pragma: no cover
carb.log_error(f"[quicklayout] Can't read the workspace file {workspace_file}, error code: {result}")
return
data = json.loads(memoryview(content).tobytes().decode("utf-8"))
ui.Workspace.restore_workspace(data, keep_windows_open)
carb.log_info(f"[quicklayout] The workspace is loaded from {workspace_file}")
@staticmethod
def compare_file(workspace_file: str, compare_delegate: CompareDelegate=CompareDelegate()):
"""Load the layout from the workspace file"""
result, _, content = omni.client.read_file(workspace_file)
if result != omni.client.Result.OK: # pragma: no cover
carb.log_error(f"[quicklayout] Can't read the workspace file {workspace_file}, error code: {result}")
return
data = json.loads(memoryview(content).tobytes().decode("utf-8"))
result = ui.Workspace.compare_workspace(data, compare_delegate=compare_delegate)
carb.log_info(f"[quicklayout] compared {workspace_file} with workspace")
return result
def save(self, menu: str, value: bool):
"""Save layout with the dialog"""
# Remove previously opened dialog
self.destroy()
self._dialog = FilePickerDialog(
"Select File to Save Layout",
apply_button_label="Save",
current_directory=QuickLayout.__get_workspace_dir(),
click_apply_handler=self.__on_apply_save,
item_filter_options=["JSON Files (*.json)", "All Files (*)"],
item_filter_fn=self.__on_filter_item,
)
def load(self, menu: str, value: bool):
"""Load layout with the dialog"""
# Remove previously opened dialog
self.destroy()
self._dialog = FilePickerDialog(
"Select File to Load Layout",
apply_button_label="Load",
current_directory=QuickLayout.__get_workspace_dir(),
click_apply_handler=self.__on_apply_load,
item_filter_options=["JSON Files (*.json)", "All Files (*)"],
item_filter_fn=self.__on_filter_item,
)
@staticmethod
def quick_save(menu: str, value: bool):
workspace_file = QuickLayout.__get_workspace_file()
QuickLayout.save_file(workspace_file)
@staticmethod
def quick_load(menu: str, value: bool):
workspace_file = QuickLayout.__get_workspace_file()
QuickLayout.load_file(workspace_file)
| 5,988 | Python | 38.662251 | 118 | 0.635939 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/quicklayout_extension.py | # Copyright (c) 2018-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.
#
from .quicklayout import QuickLayout
import omni.ext
import omni.kit.ui
class QuickLayoutExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self.__quick_layout = QuickLayout()
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu_save = editor_menu.add_item("Window/Layout/Save Layout...", self.__quick_layout.save)
self._menu_load = editor_menu.add_item("Window/Layout/Load Layout...", self.__quick_layout.load)
self._menu_quick_save = editor_menu.add_item("Window/Layout/Quick Save", QuickLayout.quick_save)
self._menu_quick_load = editor_menu.add_item("Window/Layout/Quick Load", QuickLayout.quick_load)
def on_shutdown(self): # pragma: no cover
self._menu_save = None
self._menu_load = None
self._menu_quick_save = None
self._menu_quick_load = None
self._menu = None
self.__quick_layout.destroy()
self.__quick_layout = None
| 1,423 | Python | 42.151514 | 108 | 0.691497 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/layout_templates_page.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import re
import os
import carb.settings
import omni.kit.app
import omni.ui as ui
from omni.kit.window.preferences import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX
from omni.kit.quicklayout import QuickLayout
class LayoutTemplatesPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Template Startup")
def build(self):
layout_names = {"Open Last Used Layout": "$$last_used$$"}
for item in QuickLayout.get_default_layouts():
layout_names[item[0]] = item[0]
with ui.VStack(height=0):
with self.add_frame("Default Layout"):
with ui.VStack():
self.create_setting_widget_combo("Default Layout", PERSISTENT_SETTINGS_PREFIX + "/app/quicklayout/defaultLayout", layout_names, setting_is_index=True)
| 1,262 | Python | 38.468749 | 170 | 0.722662 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/tests/test_quicklayout_menu.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import carb
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from pxr import Vt, Gf
from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows
from omni.kit.quicklayout import QuickLayout
from omni.kit.menu.utils import MenuItemDescription, MenuAlignment
from omni.kit.ui_test.query import MenuRef
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class TestQuicklayoutMenu(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
# carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/quicklayout/defaultLayout", "$$last_used$$")
self.assertEqual(QuickLayout.get_default_layouts(), [])
data_path = get_test_data_path(__name__)
self._layout_data = [ ["Test 1", f"{data_path}/layouts/test1.json", carb.input.KeyboardInput.KEY_1],
["Test 2", f"{data_path}/layouts/test2.json", carb.input.KeyboardInput.KEY_2]]
QuickLayout.add_default_layouts(self._layout_data)
# After running each test
async def tearDown(self):
QuickLayout.remove_default_layouts(self._layout_data)
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/quicklayout/defaultLayout", "$$last_used$$")
self.assertEqual(QuickLayout.get_default_layouts(), [])
async def test_layout_menu(self):
# add layout placeholder
menu_placeholder = [MenuItemDescription(name="placeholder", show_fn=lambda: False)]
omni.kit.menu.utils.add_menu_items(menu_placeholder, name="Layout")
await ui_test.human_delay(10)
layout_menu_items = []
def add_layout_menu_entry(name, parameter, key):
item = MenuItemDescription(name=name)
layout_menu_items.append(item)
for item in QuickLayout.get_default_layouts():
add_layout_menu_entry(f"{item[0]}", item[1], item[2])
# add menu
layout_delegate = QuickLayout.LayoutMenuDelegate(read_fn=lambda: "Test 2",
layout_id="Test 2",
text_width=175,
hotkey_width=75)
omni.kit.menu.utils.add_menu_items(layout_menu_items, "Layout", delegate=layout_delegate)
await ui_test.human_delay(10)
# click layout
layout_menu = omni.kit.ui_test.get_menubar().find_menu("Layout")
await layout_menu.click()
await ui_test.human_delay(10)
# verify menu icon status
layout_menu_icons = layout_menu.widget.delegate._layout_menu_icons
self.assertFalse(layout_menu.widget.delegate._layout_menu_icons['Test 1']['selected_image'].enabled)
self.assertTrue(layout_menu.widget.delegate._layout_menu_icons['Test 2']['selected_image'].enabled)
# remove menus
omni.kit.menu.utils.remove_menu_items(layout_menu_items, name="Layout")
omni.kit.menu.utils.remove_menu_items(menu_placeholder, name="Layout")
await ui_test.human_delay(10)
| 3,637 | Python | 42.309523 | 121 | 0.659335 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/tests/test_menus.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from omni.ui.tests.test_base import OmniUiTest
import omni.kit
import omni.ui as ui
import omni.kit.ui_test as ui_test
class TestQuickLayoutMenus(OmniUiTest):
async def test_menus(self):
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("Window").click()
await menu_widget.find_menu("Layout").click()
await menu_widget.find_menu("Quick Save").click()
await ui_test.human_delay(10)
await menu_widget.find_menu("Window").click()
await menu_widget.find_menu("Layout").click()
await menu_widget.find_menu("Quick Load").click()
await ui_test.human_delay(10)
| 1,082 | Python | 39.11111 | 77 | 0.719963 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/tests/quicklayout_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.
##
from ..quicklayout import QuickLayout
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import json
import omni.kit
import omni.ui as ui
import os
import tempfile
from omni.kit.mainwindow import get_main_window
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../data")
ROOT_WINDOW_NAME = "DockSpace"
class TestQuickLayout(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self._dump_workspace = ui.Workspace.dump_workspace()
# After running each test
async def tearDown(self):
self._golden_img_dir = None
ui.Workspace.restore_workspace(self._dump_workspace)
await super().tearDown()
async def test_floating(self):
ui.Workspace.clear()
window_left = ui.Window("Left", width=100, height=100, position_x=10, position_y=10)
window_right = ui.Window("Right", width=100, height=100, position_x=120, position_y=10)
await omni.kit.app.get_app().next_update_async()
temp_file = Path(tempfile.gettempdir()).joinpath("workspace_" + next(tempfile._get_candidate_names()) + ".json")
QuickLayout.save_file(f"{temp_file}")
with open(f"{temp_file}") as json_file:
data = json.load(json_file)
os.remove(f"{temp_file}")
left_pos = 0
right_pos = 0
for win in data:
if "title" in win:
if win["title"] == "Left":
left_pos = win['position_x']
elif win["title"] == "Right":
right_pos = win['position_x']
# self.assertEqual(len(data), 3) # Not true if test_restore is run first
self.assertEqual(left_pos, 10.0)
self.assertEqual(right_pos, 120.0)
async def test_docking(self):
ui.Workspace.clear()
window_left = ui.Window("Left2", width=100, height=100, position_x=10, position_y=10)
window_right = ui.Window("Right2", width=100, height=100, position_x=120, position_y=10)
target_window = ui.Workspace.get_window(ROOT_WINDOW_NAME)
await omni.kit.app.get_app().next_update_async()
window_left.dock_in(target_window, ui.DockPosition.SAME)
window_right.dock_in(window_left, ui.DockPosition.RIGHT, 0.5)
await omni.kit.app.get_app().next_update_async()
temp_file = Path(tempfile.gettempdir()).joinpath("workspace_" + next(tempfile._get_candidate_names()) + ".json")
QuickLayout.save_file(f"{temp_file}")
with open(f"{temp_file}") as json_file:
data = json.load(json_file)
os.remove(f"{temp_file}")
self.assertEqual(len(data[0]["children"]), 2)
self.assertIn(data[0]["children"][0]["position"], ["LEFT", "RIGHT"])
self.assertIn(data[0]["children"][1]["position"], ["LEFT", "RIGHT"])
async def test_restore(self):
data = [
{
"children": [
{
"children": [
{
"dock_id": 1,
"height": 100,
"selected_in_dock": True,
"title": "LeftDocked",
"visible": True,
"width": 100,
}
],
"dock_id": 1,
"position": "LEFT",
},
{
"children": [
{
"dock_id": 2,
"height": 100,
"selected_in_dock": False,
"title": "RightDocked",
"visible": True,
"width": 100,
}
],
"dock_id": 2,
"position": "RIGHT",
},
],
"dock_id": 0,
}
]
await self.create_test_area()
window_left = ui.Window("LeftDocked")
with window_left.frame:
ui.Rectangle(style={"background_color": 0xFFF07E4D})
window_right = ui.Window("RightDocked")
with window_right.frame:
ui.Rectangle(style={"background_color": 0xFF7DF0A6})
await omni.kit.app.get_app().next_update_async()
temp_file = Path(tempfile.gettempdir()).joinpath("workspace_" + next(tempfile._get_candidate_names()) + ".json")
# Save data to json file and open it in QuickLayout
with open(f"{temp_file}", "w") as json_file:
json.dump(data, json_file, sort_keys=True, indent=2)
QuickLayout.load_file(f"{temp_file}")
await omni.kit.app.get_app().next_update_async()
# for code coverage. Real QuickLayout.compare_file test is in omni.kit.test_suite.layout as it needs windows
QuickLayout.compare_file(f"{temp_file}")
# We don't test tab bar
window_left.dock_tab_bar_visible = False
window_right.dock_tab_bar_visible = False
os.remove(f"{temp_file}")
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 5,838 | Python | 35.72327 | 120 | 0.538883 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/common.py | import omni.ext
import omni.kit.menu.utils
from .legacy_help import HelpExtension
from .legacy_window import WindowExtension
class CommonMenuExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._legacy_help = HelpExtension()
self._legacy_window = WindowExtension()
def on_shutdown(self):
del self._legacy_help
del self._legacy_window
| 385 | Python | 24.733332 | 47 | 0.706494 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/legacy_window.py | import carb
import carb.input
import carb.settings
import omni.kit.ui
import omni.appwindow
import omni.kit.menu.utils
import omni.ui as ui
from carb.input import KeyboardInput as Key
class WindowExtension:
def __init__(self):
self._appwindow = omni.appwindow.get_default_app_window()
self._settings = carb.settings.get_settings()
self.WINDOW_UI_TOGGLE_VISIBILITY_MENU = "Window/UI Toggle Visibility"
self.WINDOW_FULLSCREEN_MODE_MENU = "Window/Fullscreen Mode"
self.WINDOW_DPI_SCALE_INCREASE_MENU = "Window/DPI Scale/Increase"
self.WINDOW_DPI_SCALE_DECREASE_MENU = "Window/DPI Scale/Decrease"
self.WINDOW_DPI_SCALE_RESET_MENU = "Window/DPI Scale/Reset"
self.SHOW_DPI_SCALE_MENU_SETTING = "/app/window/showDpiScaleMenu"
self.DPI_SCALE_OVERRIDE_SETTING = "/app/window/dpiScaleOverride"
self.DPI_SCALE_OVERRIDE_DEFAULT = -1.0
self.DPI_SCALE_OVERRIDE_MIN = 0.5
self.DPI_SCALE_OVERRIDE_MAX = 5.0
self.DPI_SCALE_OVERRIDE_STEP = 0.5
self.menus = []
menu = omni.kit.ui.get_editor_menu()
if menu:
window_ui_toggle_visibility_menu = menu.add_item(self.WINDOW_UI_TOGGLE_VISIBILITY_MENU, None, priority=51)
window_ui_toggle_visibility_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_UI_TOGGLE_VISIBILITY_MENU, lambda *_: self.on_toggle_ui(), "UiToggle", (0, Key.F7))
self.menus.append((window_ui_toggle_visibility_menu, window_ui_toggle_visibility_action))
window_fullscreen_mode_menu = menu.add_item(self.WINDOW_FULLSCREEN_MODE_MENU, None, priority=52)
window_fullscreen_mode_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_FULLSCREEN_MODE_MENU, lambda *_: self.on_fullscreen(), "FullscreenMode", (0, Key.F11))
self.menus.append((window_fullscreen_mode_menu, window_fullscreen_mode_menu_action))
self._settings.set_default_bool(self.SHOW_DPI_SCALE_MENU_SETTING, False)
if self._settings.get_as_bool(self.SHOW_DPI_SCALE_MENU_SETTING):
window_dpi_scale_increase_menu = menu.add_item(self.WINDOW_DPI_SCALE_INCREASE_MENU, None, priority=53)
window_dpi_scale_increase_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_DPI_SCALE_INCREASE_MENU, lambda *_: self.on_dpi_scale_increase(), "DPIScaleIncrease", (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, Key.EQUAL))
self.menus.append((window_dpi_scale_increase_menu, window_dpi_scale_increase_menu_action))
window_dpi_scale_decrease_menu = menu.add_item(self.WINDOW_DPI_SCALE_DECREASE_MENU, None, priority=54)
window_dpi_scale_decrease_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_DPI_SCALE_DECREASE_MENU, lambda *_: self.on_dpi_scale_decrease(), "DPIScaleDecrease", (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, Key.MINUS))
self.menus.append((window_dpi_scale_decrease_menu, window_dpi_scale_decrease_menu_action))
window_dpi_scale_reset_menu = menu.add_item(self.WINDOW_DPI_SCALE_RESET_MENU, None, priority=55)
window_dpi_scale_reset_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_DPI_SCALE_RESET_MENU, lambda *_: self.on_dpi_scale_reset(), "DPIScaleReset")
self.menus.append((window_dpi_scale_reset_menu, window_dpi_scale_reset_menu_action))
# Sort top level menus:
menu.set_priority("Window", -6)
def __del__(self):
self.menus = None
def add_menu(self, *argv, **kwargs):
new_menu = omni.kit.ui.get_editor_menu().add_item(*argv, **kwargs)
self.menus.append(new_menu)
return new_menu
def set_ui_hidden(self, hide):
self._settings.set("/app/window/hideUi", hide)
def is_ui_hidden(self):
return self._settings.get("/app/window/hideUi")
def on_toggle_ui(self):
self.set_ui_hidden(not self.is_ui_hidden())
def on_fullscreen(self):
display_mode_lock = self._settings.get(f"/app/window/displayModeLock")
if display_mode_lock:
# Always stay in fullscreen_mode, only hide or show UI.
self.set_ui_hidden(not self.is_ui_hidden())
else:
# Only toggle fullscreen on/off when not display_mode_lock
was_fullscreen = self._appwindow.is_fullscreen()
self._appwindow.set_fullscreen(not was_fullscreen)
# Always hide UI in fullscreen
self.set_ui_hidden(not was_fullscreen)
def step_and_clamp_dpi_scale_override(self, increase):
# Get the current value.
dpi_scale = self._settings.get_as_float(self.DPI_SCALE_OVERRIDE_SETTING)
if dpi_scale == self.DPI_SCALE_OVERRIDE_DEFAULT:
dpi_scale = ui.Workspace.get_dpi_scale()
# Increase or decrease the current value by the setp value.
if increase:
dpi_scale += self.DPI_SCALE_OVERRIDE_STEP
else:
dpi_scale -= self.DPI_SCALE_OVERRIDE_STEP
# Clamp the new value between the min/max values.
dpi_scale = max(min(dpi_scale, self.DPI_SCALE_OVERRIDE_MAX), self.DPI_SCALE_OVERRIDE_MIN)
# Set the new value.
self._settings.set(self.DPI_SCALE_OVERRIDE_SETTING, dpi_scale)
def on_dpi_scale_increase(self):
self.step_and_clamp_dpi_scale_override(True)
def on_dpi_scale_decrease(self):
self.step_and_clamp_dpi_scale_override(False)
def on_dpi_scale_reset(self):
self._settings.set(self.DPI_SCALE_OVERRIDE_SETTING, self.DPI_SCALE_OVERRIDE_DEFAULT)
| 5,631 | Python | 48.840708 | 248 | 0.665068 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/legacy_help.py | import webbrowser
import os
import carb
import carb.input
import carb.settings
import omni.kit.app
import omni.kit.menu.utils
from carb.input import KeyboardInput as Key
from omni.kit.menu.utils import MenuItemDescription
class HelpExtension:
def __init__(self):
def get_discover_kit_sdk_path(settings):
if omni.kit.app.get_app().is_app_external():
return settings.get("/exts/omni.kit.menu.common/external_kit_sdk_url")
else:
return settings.get("/exts/omni.kit.menu.common/internal_kit_sdk_url")
def get_manual_url_path(settings):
if omni.kit.app.get_app().is_app_external():
return settings.get("/exts/omni.kit.menu.common/external_kit_manual_url")
else:
return settings.get("/exts/omni.kit.menu.common/internal_kit_manual_url")
def get_discover_reference_guide_path(settings):
if omni.kit.app.get_app().is_app_external():
return settings.get("/exts/omni.kit.menu.common/external_reference_guide_url")
else:
return settings.get("/exts/omni.kit.menu.common/internal_reference_guide_url")
settings = carb.settings.get_settings()
discover_reference_guide_path = get_discover_reference_guide_path(settings)
discover_kit_sdk_path = get_discover_kit_sdk_path(settings)
manual_url_path = get_manual_url_path(settings)
self._register_actions("omni.kit.menu.common", discover_reference_guide_path, discover_kit_sdk_path, manual_url_path)
reference_guide_name = settings.get("/exts/omni.kit.menu.common/reference_guide_name")
kit_sdk_name = settings.get("/exts/omni.kit.menu.common/kit_sdk_name")
kit_manual_name = settings.get("/exts/omni.kit.menu.common/kit_manual_name")
self._help_menu = []
if reference_guide_name:
self._help_menu.append(MenuItemDescription(
name=reference_guide_name,
onclick_action=("omni.kit.menu.common", "OpenRefGuide"),
hotkey=(0, Key.F1),
enabled=False if reference_guide_name is None else True
))
if kit_sdk_name:
self._help_menu.append(MenuItemDescription(
name=kit_sdk_name,
onclick_action=("omni.kit.menu.common", "OpenDevKitSDK"),
enabled=False if discover_kit_sdk_path is None else True
))
if kit_manual_name:
self._help_menu.append(MenuItemDescription(
name=kit_manual_name,
onclick_action=("omni.kit.menu.common", "OpenDevManual"),
enabled=False if manual_url_path is None else True
))
if self._help_menu:
omni.kit.menu.utils.add_menu_items(self._help_menu, "Help", 99)
def __del__(self):
omni.kit.menu.utils.remove_menu_items(self._help_menu, "Help")
self._deregister_actions("omni.kit.menu.common")
self.menus = None
def _register_actions(self, extension_id, discover_reference_guide_path, discover_kit_sdk_path, manual_url_path):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Help Menu Actions"
# actions
action_registry.register_action(
extension_id,
"OpenRefGuide",
lambda: webbrowser.open(discover_reference_guide_path),
display_name="Help->Reference Guide",
description="Reference Guide",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"OpenDevKitSDK",
lambda: webbrowser.open(discover_kit_sdk_path),
display_name="Help->Discover Kit SDK",
description="Discover Kit SDK",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"OpenDevManual",
lambda: webbrowser.open(manual_url_path),
display_name="Help->Developers Manual",
description="Developers Manual",
tag=actions_tag,
)
def _deregister_actions(self, extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
if action_registry:
action_registry.deregister_all_actions_for_extension(extension_id)
| 4,436 | Python | 38.616071 | 125 | 0.606402 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/__init__.py | from .common import *
| 22 | Python | 10.499995 | 21 | 0.727273 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/tests/__init__.py | from .common_tests import *
| 28 | Python | 13.499993 | 27 | 0.75 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/tests/test_func_common_window.py | import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from carb.input import KeyboardInput
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
from omni.kit.viewport.utility import get_active_viewport_window, get_num_viewports
DPI_SCALE_OVERRIDE_SETTING = "/app/window/dpiScaleOverride"
def get_hide_ui():
hide_ui = carb.settings.get_settings().get("/app/window/hideUi")
if hide_ui == None:
return False
return hide_ui
async def common_test_func_window_viewport(tester, menu_item = None):
# XXX: Unclear where this API is used, but it originally took an unused menu_item
if menu_item:
carb.log_error("common_test_func_window_new_viewport_window does not use a menu_item")
# Get the default Viewport name, most likely 'Viewport'
default_vp_window_name = carb.settings.get_settings().get("/exts/omni.kit.viewport.window/startup/windowName")
default_vp_window_name = default_vp_window_name or "Viewport"
window_menu = ui_test.get_menubar().find_menu("Window")
tester.assertIsNotNone(window_menu)
# There will always be a "Viewport" menu item, but on legacy it is a single item otherwise a sub-menu container
viewport_menu = window_menu.find_menu("Viewport")
tester.assertIsNotNone(viewport_menu)
# Build up the sub-menu (and full menu-path) that will be used
vp_menu_entry_name = f"{default_vp_window_name} 1"
full_default_vp_menu_path = f"Window/Viewport/{default_vp_window_name} 1"
# If it doesnt't exists as a child of the "Viewport" menu-item, assume legacy
vp_show_menu_entry = viewport_menu.find_menu(vp_menu_entry_name)
if not vp_show_menu_entry:
viewport_menu = window_menu
vp_menu_entry_name = default_vp_window_name
full_default_vp_menu_path = f"Window/{default_vp_window_name}"
vp_show_menu_entry = window_menu.find_menu(vp_menu_entry_name)
# Needs to be valid by now
tester.assertIsNotNone(vp_show_menu_entry)
# Pre-check that the Viewport Window can also be found
viewport_window = get_active_viewport_window(window_name=default_vp_window_name)
tester.assertIsNotNone(viewport_window)
# verify initial visibility and check state
tester.assertTrue(viewport_window.visible)
tester.assertTrue(vp_show_menu_entry.widget.checked)
# use menu
await ui_test.menu_click(full_default_vp_menu_path)
await ui_test.human_delay()
# verify
tester.assertFalse(viewport_window.visible)
tester.assertFalse(vp_show_menu_entry.widget.checked)
# use menu
await ui_test.menu_click(full_default_vp_menu_path)
await ui_test.human_delay()
# verify
tester.assertTrue(viewport_window.visible)
tester.assertTrue(vp_show_menu_entry.widget.checked)
async def common_test_func_window_ui_toggle_visibility(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertTrue(get_hide_ui() == False)
# use menu
await ui_test.menu_click("Window/UI Toggle Visibility")
await ui_test.human_delay(50)
# verify state
tester.assertTrue(get_hide_ui() == True)
# cannot use menu so use hotkey instead
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(get_hide_ui() == False)
async def common_test_hotkey_func_window_ui_toggle_visibility(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertTrue(get_hide_ui() == False)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(get_hide_ui() == True)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(get_hide_ui() == False)
async def common_test_func_window_fullscreen_mode(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False)
# use menu
await ui_test.menu_click("Window/Fullscreen Mode")
await ui_test.human_delay(50)
# verify state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == True)
# cannot use menu so use hotkey instead
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False)
async def common_test_hotkey_func_window_fullscreen_mode(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == True)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False)
async def common_test_func_window_new_viewport_window(tester, menu_item = None):
# XXX: Unclear where this API is used, but it originally took an unused menu_item
if menu_item:
carb.log_error("common_test_func_window_new_viewport_window does not use a menu_item")
# verify default state
tester.assertEqual(get_num_viewports(), 1)
# All functionaliyt contained in Window menu
window_menu = ui_test.get_menubar().find_menu("Window")
tester.assertIsNotNone(window_menu)
# There will always be a "Viewport" menu item, but on legacy it is a single item otherwise a sub-menu container
viewport_menu = window_menu.find_menu("Viewport")
tester.assertIsNotNone(viewport_menu)
# use menu
if viewport_menu.find_menu("Viewport 2"):
await ui_test.menu_click("Window/Viewport/Viewport 2")
else:
await ui_test.menu_click("Window/New Viewport Window")
await ui_test.human_delay()
# verify
tester.assertEqual(get_num_viewports(), 2)
# close new viewport window
viewport_window = get_active_viewport_window(window_name="Viewport 2")
if viewport_window:
viewport_window.visible = False
viewport_window.destroy()
del viewport_window
async def common_test_func_window_dpi_scale_increase(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# use menu
await ui_test.menu_click("Window/DPI Scale/Increase")
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.5)
# cannot use menu so use hotkey instead
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 2.0)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
async def common_test_hotkey_func_window_dpi_scale_increase(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.5)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 2.0)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
async def common_test_func_window_dpi_scale_decrease(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# use menu
await ui_test.menu_click("Window/DPI Scale/Decrease")
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5)
# cannot use menu so use hotkey instead
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state - still 0.5 because it gets clamped to the min
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
async def common_test_hotkey_func_window_dpi_scale_decrease(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state - still 0.5 because it gets clamped to the min
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
async def common_test_func_window_dpi_scale_reset(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# use menu
await ui_test.menu_click("Window/DPI Scale/Reset")
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), -1.0)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
| 10,876 | Python | 36.506896 | 115 | 0.713406 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/tests/test_func_common_help.py | import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
async def common_test_func_help_usd_reference_guide(tester, menu_item: MenuItemDescription):
carb.log_warn("Help/USD Reference Guide - No test")
# don't know how to test this as it opens a webpage
async def common_test_hotkey_func_help_usd_reference_guide(tester, menu_item: MenuItemDescription):
carb.log_warn("Help/USD Reference Guide - No test")
# don't know how to test this as it opens a webpage
async def common_test_func_help_developers_manual(tester, menu_item: MenuItemDescription):
carb.log_warn("Help/Developers Manual - No test")
# don't know how to test this as it opens a webpage
async def common_test_func_help_discover_kit_sdk(tester, menu_item: MenuItemDescription):
carb.log_warn("Help/Discover Kit SDK - No test")
# don't know how to test this as it opens a webpage
| 983 | Python | 34.142856 | 99 | 0.748728 |
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/__init__.py | import carb.events
from ._appwindow import *
| 45 | Python | 14.333329 | 25 | 0.777778 |
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/tests/test_appwindow.py | import omni.kit.app
import omni.kit.test
import carb.windowing
import carb.settings
import omni.appwindow
WINDOW_ENABLED_PATH = "/app/window/enabled"
LINUX_WM_LATENCY_MAX = 100
class Test(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._windowing = carb.windowing.acquire_windowing_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._settings = carb.settings.acquire_settings_interface()
async def tearDown(self):
self._app_window_factory = None
def _cmp_vectors_and_delta(self, vec_result, vec_base, delta):
return (vec_result[0] == vec_base[0] + delta[0]) and (vec_result[1] == vec_base[1] + delta[1])
async def test_create_os_window(self):
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window = self._app_window.get_window()
self.assertNotEqual(self._native_app_window, None)
self._windowing.show_window(self._native_app_window)
await omni.kit.app.get_app().next_update_async()
self._app_window.shutdown()
self._app_window = None
async def test_create_virtual_window(self):
is_window_enabled = self._settings.get(WINDOW_ENABLED_PATH)
self._settings.set(WINDOW_ENABLED_PATH, False)
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test virtual window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window = self._app_window.get_window()
self.assertEqual(self._native_app_window, None)
await omni.kit.app.get_app().next_update_async()
self._app_window.shutdown()
self._app_window = None
self._settings.set(WINDOW_ENABLED_PATH, is_window_enabled)
async def test_move_os_window(self):
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window = self._app_window.get_window()
self.assertNotEqual(self._native_app_window, None)
self._windowing.show_window(self._native_app_window)
move_delta = [10, 20]
pos = self._app_window.get_position()
pos_native = self._windowing.get_window_position(self._native_app_window)
self.assertEqual(pos_native[0], pos[0])
self.assertEqual(pos_native[1], pos[1])
self._app_window.move(pos[0] + move_delta[0], pos[1] + move_delta[1])
for i in range(LINUX_WM_LATENCY_MAX):
await omni.kit.app.get_app().next_update_async()
# This code is needed due to Linux WM latency; window operations do not happen
# immediately, and not deterministically
new_pos = self._app_window.get_position()
move_happened = self._cmp_vectors_and_delta(new_pos, pos, move_delta)
if move_happened:
break
new_pos = self._app_window.get_position()
new_pos_native = self._windowing.get_window_position(self._native_app_window)
self.assertEqual(new_pos[0], pos[0] + move_delta[0])
self.assertEqual(new_pos[1], pos[1] + move_delta[1])
self.assertEqual(new_pos_native[0], new_pos[0])
self.assertEqual(new_pos_native[1], new_pos[1])
self._app_window.shutdown()
self._app_window = None
async def test_resize_os_window(self):
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window = self._app_window.get_window()
self.assertNotEqual(self._native_app_window, None)
self._windowing.show_window(self._native_app_window)
resize_delta = [10, 20]
size = self._app_window.get_size()
size_native = [self._windowing.get_window_width(self._native_app_window), self._windowing.get_window_height(self._native_app_window)]
self.assertEqual(size_native[0], size[0])
self.assertEqual(size_native[1], size[1])
self._app_window.resize(size[0] + resize_delta[0], size[1] + resize_delta[1])
for i in range(LINUX_WM_LATENCY_MAX):
await omni.kit.app.get_app().next_update_async()
# This code is needed due to Linux WM latency; window operations do not happen
# immediately, and not deterministically
new_size = self._app_window.get_size()
resize_happened = self._cmp_vectors_and_delta(new_size, size, resize_delta)
if resize_happened:
break
new_size = self._app_window.get_size()
new_size_native = [self._windowing.get_window_width(self._native_app_window), self._windowing.get_window_height(self._native_app_window)]
self.assertEqual(new_size[0], size[0] + resize_delta[0])
self.assertEqual(new_size[1], size[1] + resize_delta[1])
self.assertEqual(new_size_native[0], new_size[0])
self.assertEqual(new_size_native[1], new_size[1])
self._app_window.shutdown()
self._app_window = None
async def test_multiple_os_windows(self):
self._app_window1 = self._app_window_factory.create_window_from_settings()
self._app_window1.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window1 = self._app_window1.get_window()
self.assertNotEqual(self._native_app_window1, None)
self._windowing.show_window(self._native_app_window1)
self._app_window2 = self._app_window_factory.create_window_from_settings()
self._app_window2.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window2 = self._app_window2.get_window()
self.assertNotEqual(self._native_app_window2, None)
self._windowing.show_window(self._native_app_window2)
resize_delta = [30, 40]
size = self._app_window1.get_size()
size_native = [self._windowing.get_window_width(self._native_app_window1), self._windowing.get_window_height(self._native_app_window1)]
self.assertEqual(size_native[0], size[0])
self.assertEqual(size_native[1], size[1])
move_delta = [50, 60]
pos = self._app_window2.get_position()
pos_native = self._windowing.get_window_position(self._native_app_window2)
self.assertEqual(pos_native[0], pos[0])
self.assertEqual(pos_native[1], pos[1])
self._app_window1.resize(size[0] + resize_delta[0], size[1] + resize_delta[1])
self._app_window2.move(pos[0] + move_delta[0], pos[1] + move_delta[1])
for i in range(LINUX_WM_LATENCY_MAX):
await omni.kit.app.get_app().next_update_async()
# This code is needed due to Linux WM latency; window operations do not happen
# immediately, and not deterministically
new_size = self._app_window1.get_size()
new_pos = self._app_window2.get_position()
resize_happened = self._cmp_vectors_and_delta(new_size, size, resize_delta)
move_happened = self._cmp_vectors_and_delta(new_pos, pos, move_delta)
if resize_happened and move_happened:
break
new_size = self._app_window1.get_size()
new_size_native = [self._windowing.get_window_width(self._native_app_window1), self._windowing.get_window_height(self._native_app_window1)]
self.assertEqual(new_size[0], size[0] + resize_delta[0])
self.assertEqual(new_size[1], size[1] + resize_delta[1])
self.assertEqual(new_size_native[0], new_size[0])
self.assertEqual(new_size_native[1], new_size[1])
new_pos = self._app_window2.get_position()
new_pos_native = self._windowing.get_window_position(self._native_app_window2)
self.assertEqual(new_pos[0], pos[0] + move_delta[0])
self.assertEqual(new_pos[1], pos[1] + move_delta[1])
self.assertEqual(new_pos_native[0], new_pos[0])
self.assertEqual(new_pos_native[1], new_pos[1])
self._app_window1.shutdown()
self._app_window2.shutdown()
self._app_window1 = None
self._app_window2 = None
async def test_create_no_cursor_blink_window(self):
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test window, no cursor blink set",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0,
cursor_blink=False
)
self._native_app_window = self._app_window.get_window()
self.assertNotEqual(self._native_app_window, None)
self._windowing.show_window(self._native_app_window)
await omni.kit.app.get_app().next_update_async()
self.assertFalse(self._app_window.get_cursor_blink())
self._app_window.shutdown()
self._app_window = None
| 11,127 | Python | 40.992453 | 147 | 0.609329 |
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/tests/__init__.py | from .test_appwindow import *
| 30 | Python | 14.499993 | 29 | 0.766667 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/stage_extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageExtension"]
import asyncio
import omni.ext
import omni.kit.ui
import omni.ui as ui
from omni.kit.menu.utils import MenuItemDescription
from .stage_window import StageWindow
class StageExtension(omni.ext.IExt):
"""The entry point for Stage Window"""
WINDOW_NAME = "Stage"
MENU_GROUP = "Window"
def on_startup(self):
self._window = None
ui.Workspace.set_show_window_fn(StageExtension.WINDOW_NAME, self.show_window)
self._menu = [MenuItemDescription(
name=StageExtension.WINDOW_NAME,
ticked=True, # menu item is ticked
ticked_fn=self._is_visible, # gets called when the menu needs to get the state of the ticked menu
onclick_fn=self._toggle_window
)]
omni.kit.menu.utils.add_menu_items(self._menu, name=StageExtension.MENU_GROUP)
ui.Workspace.show_window(StageExtension.WINDOW_NAME)
def on_shutdown(self):
omni.kit.menu.utils.remove_menu_items(self._menu, name=StageExtension.MENU_GROUP)
self._menu = None
if self._window:
self._window.destroy()
self._window = None
ui.Workspace.set_show_window_fn(StageExtension.WINDOW_NAME, None)
def _set_menu(self, value):
"""Set the menu to create this window on and off"""
# this only tags test menu to update when menu is opening, so it
# doesn't matter that is called before window has been destroyed
omni.kit.menu.utils.refresh_menu_items(StageExtension.MENU_GROUP)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def _visiblity_changed_fn(self, visible):
self._set_menu(visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, value):
if value:
self._window = StageWindow()
self._window.set_visibility_changed_listener(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
def _is_visible(self) -> bool:
return False if self._window is None else self._window.visible
def _toggle_window(self):
if self._is_visible():
self.show_window(False)
else:
self.show_window(True)
| 3,049 | Python | 35.309523 | 109 | 0.654969 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/external_drag_drop_helper.py | import omni.ui as ui
from typing import List
from pxr import Sdf
from omni.kit.window.drop_support import ExternalDragDrop
external_drag_drop = None
def setup_external_drag_drop(window_name :str, stage_widget):
global external_drag_drop
destroy_external_drag_drop()
external_drag_drop = ExternalDragDrop(window_name=window_name,
drag_drop_fn=lambda e, p, m=stage_widget.get_model(): _on_ext_drag_drop(e, p, m))
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], model: ui.AbstractItemModel):
import omni.usd
default_prim_path = Sdf.Path("/")
stage = omni.usd.get_context().get_stage()
if stage.HasDefaultPrim():
default_prim_path = stage.GetDefaultPrim().GetPath()
target_item = model.find(default_prim_path)
for file_path in edd.expand_payload(payload):
model.drop(target_item, file_path.replace("\\", "/"))
| 1,088 | Python | 31.029411 | 123 | 0.674632 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/stage_window.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageWindow"]
from .selection_watch import SelectionWatch
from .external_drag_drop_helper import setup_external_drag_drop, destroy_external_drag_drop
from .stage_settings import StageSettings
from omni.kit.widget.stage import StageWidget
from typing import List
from typing import Optional
from typing import Tuple
from pxr import Usd
import carb.events
import carb.settings
import omni.ui as ui
import omni.usd
class CustomizedStageWidget(StageWidget):
@StageWidget.show_prim_display_name.setter
def show_prim_display_name(self, value):
StageWidget.show_prim_display_name.fset(self, value)
StageSettings().show_prim_displayname = value
@StageWidget.children_reorder_supported.setter
def children_reorder_supported(self, value):
StageWidget.children_reorder_supported.fset(self, value)
StageSettings().should_keep_children_order = value
@StageWidget.auto_reload_prims.setter
def auto_reload_prims(self, value):
StageWidget.auto_reload_prims.fset(self, value)
StageSettings().auto_reload_prims = value
def get_treeview(self):
return self._tree_view
def get_delegate(self):
return self._delegate
class StageWindow(ui.Window):
"""The Stage window"""
def __init__(self, usd_context_name: str = ""):
self._usd_context = omni.usd.get_context(usd_context_name)
self._visiblity_changed_listener = None
super().__init__(
"Stage",
width=600,
height=800,
flags=ui.WINDOW_FLAGS_NO_SCROLLBAR,
dockPreference=ui.DockPreference.RIGHT_TOP,
)
self.set_visibility_changed_fn(self._visibility_changed_fn)
# Dock it to the same space where Layers is docked, make it the first tab and the active tab.
self.deferred_dock_in("Layers", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
self.dock_order = 0
# Get list of columns from settings
self._settings = carb.settings.get_settings()
self._columns_settings_path = "/persistent/exts/omni.kit.window.stage/columns"
columns: Optional[str] = self._settings.get(self._columns_settings_path)
if columns is None:
# By default Visibility and Type are enabled columns
self._columns = ["Visibility","Type"]
else:
self._columns = columns.split("|")
with self.frame:
self._stage_widget = CustomizedStageWidget(
None, columns_enabled=self._columns,
children_reorder_supported=StageSettings().should_keep_children_order,
show_prim_display_name=StageSettings().show_prim_displayname,
auto_reload_prims=StageSettings().auto_reload_prims
)
# The Open/Close Stage logic
self._stage_subscription = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_usd_context_event, name="Stage Window USD Stage Open/Closing Listening"
)
self._on_stage_opened()
# The selection logic
self._selection = SelectionWatch(usd_context=self._usd_context)
self._stage_widget.set_selection_watch(self._selection)
# Callback when columns are changed or toggled
self._columns_changed_sub = self._stage_widget.subscribe_columns_changed(self._columns_changed)
def _columns_changed(self, columns: List[Tuple[str, bool]]):
"""
Called by StageWidget when columns are changed or toggled.
"""
enabled_columns = [c[0] for c in columns if c[1]]
self._settings.set_string(self._columns_settings_path, "|".join(enabled_columns))
def _visibility_changed_fn(self, visible):
if self._visiblity_changed_listener:
self._visiblity_changed_listener(visible)
if not visible:
if self._selection:
self._selection.destroy()
self._selection = None
else:
self._selection = SelectionWatch(usd_context=self._usd_context)
if self._stage_widget:
self._stage_widget.set_selection_watch(self._selection)
def set_visibility_changed_listener(self, listener):
self._visiblity_changed_listener = listener
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
self._visiblity_changed_listener = None
if self._selection:
self._selection._tree_view = None
self._selection._events = None
self._selection._stage_event_sub = None
self._selection = None
self._stage_widget.destroy()
self._stage_widget = None
self._stage_subscription = None
self._settings = None
self._columns_changed_sub = None
super().destroy()
destroy_external_drag_drop()
def _on_usd_context_event(self, event: carb.events.IEvent):
"""Called on USD Context event"""
if event.type == int(omni.usd.StageEventType.OPENED):
self._on_stage_opened()
elif event.type == int(omni.usd.StageEventType.CLOSING):
self._on_stage_closing()
def _on_stage_opened(self):
"""Called when opening a new stage"""
stage = self._usd_context.get_stage()
if not stage:
return
self._stage_widget.open_stage(stage)
setup_external_drag_drop("Stage", self._stage_widget)
def _on_stage_closing(self):
"""Called when close the stage"""
self._stage_widget.open_stage(None)
setup_external_drag_drop("Stage", self._stage_widget)
def get_widget(self) -> CustomizedStageWidget:
return self._stage_widget
| 6,244 | Python | 36.172619 | 105 | 0.653107 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/stage_settings.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.
#
# Selection Watch implementation has been moved omni.kit.widget.stage.
# Import it here for keeping back compatibility.
import carb.settings
import omni.kit.usd.layers as layers
from .singleton import Singleton
SETTINGS_SHOW_PRIM_DISPLAYNAME = "/persistent/ext/omni.kit.widget.stage/show_prim_displayname"
SETTINGS_KEEP_CHILDREN_ORDER = "/persistent/ext/omni.usd/keep_children_order"
@Singleton
class StageSettings:
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(SETTINGS_SHOW_PRIM_DISPLAYNAME, False)
self._settings.set_default_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS, False)
self._settings.set_default_bool(SETTINGS_KEEP_CHILDREN_ORDER, False)
@property
def show_prim_displayname(self):
return self._settings.get_as_bool(SETTINGS_SHOW_PRIM_DISPLAYNAME)
@show_prim_displayname.setter
def show_prim_displayname(self, enabled: bool):
self._settings.set(SETTINGS_SHOW_PRIM_DISPLAYNAME, enabled)
@property
def auto_reload_prims(self):
return self._settings.get_as_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS)
@auto_reload_prims.setter
def auto_reload_prims(self, enabled: bool):
self._settings.set(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS, enabled)
@property
def should_keep_children_order(self):
return self._settings.get_as_bool(SETTINGS_KEEP_CHILDREN_ORDER)
@should_keep_children_order.setter
def should_keep_children_order(self, value):
self._settings.set(SETTINGS_KEEP_CHILDREN_ORDER, value)
| 2,068 | Python | 37.314814 | 94 | 0.738878 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/tests/stage_window_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 omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
import omni.kit.app
import omni.ui as ui
import omni.usd
import omni.kit.commands
from omni.kit import ui_test
from unittest.mock import Mock, patch, ANY
from ..stage_window import StageWindow
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data")
class TestStageWindow(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self._w = ui.Workspace.get_window("Stage")
self._usd_context = omni.usd.get_context()
# After running each test
async def tearDown(self):
self._w = None
self._golden_img_dir = None
await super().tearDown()
async def test_general(self):
# New stage with a sphere
await self._usd_context.new_stage_async()
omni.kit.commands.execute("CreatePrim", prim_path="/Sphere", prim_type="Sphere", select_new_prim=False)
# Loading icon takes time.
# TODO: We need a mode that blocks UI until icons are loaded
await self.wait(10)
await self.docked_test_window(
window=self._w,
width=450,
height=100,
restore_window=ui.Workspace.get_window("Layer"),
restore_position=ui.DockPosition.SAME,
)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_multi_visibility_change(self):
"""Testing visibility of StageWidget"""
await self.docked_test_window(
window=self._w,
width=450,
height=200,
)
# New stage with three prims
await self._usd_context.new_stage_async()
omni.kit.commands.execute("CreatePrim", prim_path="/A", prim_type="Sphere", select_new_prim=False)
omni.kit.commands.execute("CreatePrim", prim_path="/B", prim_type="Sphere", select_new_prim=False)
omni.kit.commands.execute("CreatePrim", prim_path="/C", prim_type="Sphere", select_new_prim=False)
await ui_test.wait_n_updates(5)
# select both A and C
self._usd_context.get_selection().set_selected_prim_paths(["/A", "/C"], True)
# make A invisible
await ui_test.wait_n_updates(5)
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
eye_icon = stage_widget.find_all("**/ToolButton[*]")[0]
await eye_icon.click()
await ui_test.wait_n_updates(5)
# check C will also be invisible
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def wait(self, n=100):
for i in range(n):
await omni.kit.app.get_app().next_update_async()
async def test_header_columns(self):
from omni.kit import ui_test
await ui_test.find("Stage").focus()
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
name_column = stage_widget.find("**/Label[*].text=='Name (Old to New)'")
self.assertTrue(name_column)
await ui_test.emulate_mouse_move(name_column.center)
await name_column.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu("Create")
await self.wait()
await name_column.click()
await self.wait()
name_column = stage_widget.find("**/Label[*].text=='Name (A to Z)'")
self.assertTrue(name_column)
await name_column.click()
await self.wait()
name_column = stage_widget.find("**/Label[*].text=='Name (Z to A)'")
self.assertTrue(name_column)
await name_column.click()
await self.wait()
name_column = stage_widget.find("**/Label[*].text=='Name (New to Old)'")
self.assertTrue(name_column)
await name_column.click()
await self.wait()
name_column = stage_widget.find("**/Label[*].text=='Name (Old to New)'")
self.assertTrue(name_column)
await self.finalize_test_no_image()
async def test_rename_with_context_menu(self):
from omni.kit import ui_test
await ui_test.find("Stage").focus()
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
# New stage with three prims
await self._usd_context.new_stage_async()
stage = omni.usd.get_context().get_stage()
stage.GetRootLayer().Clear()
await ui_test.wait_n_updates(5)
prim = stage.DefinePrim("/test", "Xform")
await ui_test.wait_n_updates(5)
prim_item = stage_widget.find("**/Label[*].text=='test'")
self.assertTrue(prim_item)
prim_name_field = stage_widget.find("**/StringField[*].identifier=='rename_field'")
self.assertTrue(prim_name_field)
await prim_item.double_click()
self.assertTrue(prim_name_field.widget.selected)
prim_name_field.model.set_value("")
await prim_name_field.input("test2")
await ui_test.input.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await ui_test.wait_n_updates(5)
old_prim = stage.GetPrimAtPath("/test")
self.assertFalse(old_prim)
new_prim = stage.GetPrimAtPath("/test2")
self.assertTrue(new_prim)
# Rename with context menu
prim_item = stage_widget.find("**/Label[*].text=='test2'")
self.assertTrue(prim_item)
prim_name_field = stage_widget.find("**/StringField[*].identifier=='rename_field'")
self.assertTrue(prim_name_field)
await prim_item.right_click()
await ui_test.select_context_menu("Rename")
self.assertTrue(prim_name_field.widget.selected)
await prim_name_field.input("test3")
await ui_test.input.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await ui_test.wait_n_updates(5)
old_prim = stage.GetPrimAtPath("/test")
self.assertFalse(old_prim)
new_prim = stage.GetPrimAtPath("/test2test3")
self.assertTrue(new_prim)
await self.finalize_test_no_image()
async def test_window_destroyed_when_hidden(self):
"""Test that hiding stage window destroys it, and showing creates a new instance."""
ui.Workspace.show_window("Stage")
self.assertTrue(ui.Workspace.get_window("Stage").visible)
with patch.object(StageWindow, "destroy", autospec=True) as mock_destroy_dialog:
ui.Workspace.show_window("Stage", False)
await ui_test.wait_n_updates(5)
mock_destroy_dialog.assert_called()
self.assertFalse(ui.Workspace.get_window("Stage").visible)
await self.finalize_test_no_image()
| 7,238 | Python | 37.505319 | 111 | 0.63664 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/__init__.py | from .scripts.extension import *
from .scripts.command import *
| 64 | Python | 20.66666 | 32 | 0.78125 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshSphereDatabase.py | """Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshSphere
If necessary, create a new mesh representing a shpere
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
import numpy
class OgnProceduralMeshSphereDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshSphere
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.diameter
inputs.latitudeResolution
inputs.longitudeResolution
inputs.parameterCheck
Outputs:
outputs.extent
outputs.faceVertexCounts
outputs.faceVertexIndices
outputs.parameterCheck
outputs.points
outputs.stIndices
outputs.sts
"""
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:diameter', 'float', 0, None, 'Sphere diameter', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''),
('inputs:latitudeResolution', 'int', 0, None, 'Sphere Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''),
('inputs:longitudeResolution', 'int', 0, None, 'Sphere Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''),
('inputs:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''),
('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''),
('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''),
('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''),
('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''),
('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''),
('outputs:stIndices', 'int[]', 0, None, 'Texture coordinate indices of faces', {}, True, None, False, ''),
('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"diameter", "latitudeResolution", "longitudeResolution", "parameterCheck", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.diameter, self._attributes.latitudeResolution, self._attributes.longitudeResolution, self._attributes.parameterCheck]
self._batchedReadValues = [100, 10, 10, -1]
@property
def diameter(self):
return self._batchedReadValues[0]
@diameter.setter
def diameter(self, value):
self._batchedReadValues[0] = value
@property
def latitudeResolution(self):
return self._batchedReadValues[1]
@latitudeResolution.setter
def latitudeResolution(self, value):
self._batchedReadValues[1] = value
@property
def longitudeResolution(self):
return self._batchedReadValues[2]
@longitudeResolution.setter
def longitudeResolution(self, value):
self._batchedReadValues[2] = value
@property
def parameterCheck(self):
return self._batchedReadValues[3]
@parameterCheck.setter
def parameterCheck(self, value):
self._batchedReadValues[3] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.extent_size = None
self.faceVertexCounts_size = None
self.faceVertexIndices_size = None
self.points_size = None
self.stIndices_size = None
self.sts_size = None
self._batchedWriteValues = { }
@property
def extent(self):
data_view = og.AttributeValueHelper(self._attributes.extent)
return data_view.get(reserved_element_count=self.extent_size)
@extent.setter
def extent(self, value):
data_view = og.AttributeValueHelper(self._attributes.extent)
data_view.set(value)
self.extent_size = data_view.get_array_size()
@property
def faceVertexCounts(self):
data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts)
return data_view.get(reserved_element_count=self.faceVertexCounts_size)
@faceVertexCounts.setter
def faceVertexCounts(self, value):
data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts)
data_view.set(value)
self.faceVertexCounts_size = data_view.get_array_size()
@property
def faceVertexIndices(self):
data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices)
return data_view.get(reserved_element_count=self.faceVertexIndices_size)
@faceVertexIndices.setter
def faceVertexIndices(self, value):
data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices)
data_view.set(value)
self.faceVertexIndices_size = data_view.get_array_size()
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
return data_view.get(reserved_element_count=self.points_size)
@points.setter
def points(self, value):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.set(value)
self.points_size = data_view.get_array_size()
@property
def stIndices(self):
data_view = og.AttributeValueHelper(self._attributes.stIndices)
return data_view.get(reserved_element_count=self.stIndices_size)
@stIndices.setter
def stIndices(self, value):
data_view = og.AttributeValueHelper(self._attributes.stIndices)
data_view.set(value)
self.stIndices_size = data_view.get_array_size()
@property
def sts(self):
data_view = og.AttributeValueHelper(self._attributes.sts)
return data_view.get(reserved_element_count=self.sts_size)
@sts.setter
def sts(self, value):
data_view = og.AttributeValueHelper(self._attributes.sts)
data_view.set(value)
self.sts_size = data_view.get_array_size()
@property
def parameterCheck(self):
value = self._batchedWriteValues.get(self._attributes.parameterCheck)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.parameterCheck)
return data_view.get()
@parameterCheck.setter
def parameterCheck(self, value):
self._batchedWriteValues[self._attributes.parameterCheck] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnProceduralMeshSphereDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnProceduralMeshSphereDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnProceduralMeshSphereDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,957 | Python | 46.030043 | 177 | 0.637127 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/extension.py | import omni.ext
from ..bindings._omni_kit_procedural_mesh import *
from .menu import *
class PublicExtension(omni.ext.IExt):
def on_startup(self):
self._interface = acquire_interface()
self._menu = Menu()
def on_shutdown(self):
self._menu.on_shutdown()
self._menu = None
release_interface(self._interface)
| 357 | Python | 22.866665 | 50 | 0.644258 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/procedural_mesh_omnigraph_utils.py | """
A set of utilities
"""
import omni.kit.app
import omni.usd
from pxr import Sdf, UsdGeom
import omni.graph.core as og
def get_parent(stage, parentPath):
if parentPath:
parentPrim = stage.GetPrimAtPath(parentPath)
if parentPrim:
return parentPrim, False
# fallback to default behavior (creating a parent xform prim)
omni.kit.commands.execute(
"CreatePrimWithDefaultXform",
prim_type="Xform",
prim_path=omni.usd.get_stage_next_free_path(stage, "/" + "ProceduralMeshXform", True),
select_new_prim=True,
create_default_xform=False,
)
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
for path in paths:
parentPrim = stage.GetPrimAtPath(path)
return parentPrim, True
def create_mesh_computer(stage, prim_name: str, evaluator_name: str, node_type: str, parentPath=None):
parentPrim, isParentOwned = get_parent(stage, parentPath)
omni.kit.commands.execute(
"CreatePrimWithDefaultXform",
prim_type="Mesh",
prim_path=omni.usd.get_stage_next_free_path(
stage, str(parentPrim.GetPath().AppendElementString(prim_name)), False
),
select_new_prim=True,
create_default_xform=False,
)
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
for path in paths:
mesh = stage.GetPrimAtPath(path)
helper = og.OmniGraphHelper()
computer = helper.create_node(str(mesh.GetPath().AppendElementString(evaluator_name)), node_type)
if isParentOwned:
return parentPrim, mesh, computer
else:
return mesh, mesh, computer
def init_common_attributes(prim):
# parameter check
# sschirm
parameterCheckAttr = prim.CreateAttribute("proceduralMesh:parameterCheck", Sdf.ValueTypeNames.Int)
parameterCheckAttr.Set(0)
# basic attributes
pointsAttr = prim.GetAttribute("points")
faceVertexCountsAttr = prim.GetAttribute("faceVertexCounts")
faceVertexIndicesAttr = prim.GetAttribute("faceVertexIndices")
# extent
extentAttr = prim.GetAttribute("extent")
def connect_common_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect parameterCheck attribute as in and output
helper.connect(ognPrim, "proceduralMesh:parameterCheck", computer, "inputs:parameterCheck")
helper.connect(computer, "outputs:parameterCheck", ognPrim, "proceduralMesh:parameterCheck")
# connect basic attributes
helper.connect(computer, "outputs:points", ognPrim, "points")
helper.connect(computer, "outputs:faceVertexCounts", ognPrim, "faceVertexCounts")
helper.connect(computer, "outputs:faceVertexIndices", ognPrim, "faceVertexIndices")
# connect to extent
helper.connect(computer, "outputs:extent", ognPrim, "extent")
def init_crease_attributes(prim):
creaseIndicesAttr = prim.GetAttribute("creaseIndices")
creaseLengthsAttr = prim.GetAttribute("creaseLengths")
creaseSharpnessesAttr = prim.GetAttribute("creaseSharpnesses")
def connect_crease_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect smooth group related attributes
helper.connect(computer, "outputs:creaseIndices", ognPrim, "creaseIndices")
helper.connect(computer, "outputs:creaseLengths", ognPrim, "creaseLengths")
helper.connect(computer, "outputs:creaseSharpnesses", ognPrim, "creaseSharpnesses")
def init_corner_attributes(prim):
cornerIndicesAttr = prim.GetAttribute("cornerIndices")
cornerSharpnessesAttr = prim.GetAttribute("cornerSharpnesses")
def connect_corner_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect smooth group related attributes
helper.connect(computer, "outputs:cornerIndices", ognPrim, "cornerIndices")
helper.connect(computer, "outputs:cornerSharpnesses", ognPrim, "cornerSharpnesses")
def init_normals_facevarying_attributes(prim):
mesh = UsdGeom.Mesh(prim)
# authored normals only works when subdivision is none
mesh.CreateSubdivisionSchemeAttr("none")
normalsVar = mesh.CreatePrimvar("normals", Sdf.ValueTypeNames.Normal3fArray)
normalsAttr = prim.GetAttribute("primvars:normals")
normalIndicesAttr = prim.CreateAttribute("primvars:normals:indices", Sdf.ValueTypeNames.IntArray, False)
normalsVar.SetInterpolation("faceVarying")
def connect_normals_facevarying_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect normal related attributes
helper.connect(computer, "outputs:normals", ognPrim, "primvars:normals")
helper.connect(computer, "outputs:normalIndices", ognPrim, "primvars:normals:indices")
def init_texture_coords_facevarying_attributes(prim):
mesh = UsdGeom.Mesh(prim)
# st related attributes
stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
stsAttr = prim.GetAttribute("primvars:st")
stIndicesAttr = prim.CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False)
def connect_texture_coords_facevarying_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect st related attributes
helper.connect(computer, "outputs:sts", ognPrim, "primvars:st")
helper.connect(computer, "outputs:stIndices", ognPrim, "primvars:st:indices")
def init_texture_coords_attributes(prim):
mesh = UsdGeom.Mesh(prim)
# st related attributes
stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
stsAttr = prim.GetAttribute("primvars:st")
def connect_texture_coords_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect st related attributes
helper.connect(computer, "outputs:sts", ognPrim, "primvars:st")
def create_procedural_mesh_cube(
stage, parentPath=None, xLength=100, yLength=100, zLength=100, xResolution=10, yResolution=10, zResolution=10
):
root, cube, computer = create_mesh_computer(
stage, "ProceduralMeshCube", "CubeEvaluator", "omni.kit.procedural.mesh.CreateMeshCube", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:xLength", xLength],
["inputs:yLength", yLength],
["inputs:zLength", zLength],
["inputs:xResolution", xResolution],
["inputs:yResolution", xResolution],
["inputs:zResolution", zResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(cube)
init_crease_attributes(cube)
init_normals_facevarying_attributes(cube)
init_texture_coords_facevarying_attributes(cube)
connect_common_attributes(cube, computer)
connect_crease_attributes(cube, computer)
connect_normals_facevarying_attributes(cube, computer)
connect_texture_coords_facevarying_attributes(cube, computer)
return root, cube
def create_procedural_mesh_sphere(stage, parentPath=None, diameter=100, longitudeResolution=10, latitudeResolution=10):
root, sphere, computer = create_mesh_computer(
stage, "ProceduralMeshSphere", "SphereEvaluator", "omni.kit.procedural.mesh.CreateMeshSphere", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:longitudeResolution", longitudeResolution],
["inputs:latitudeResolution", latitudeResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(sphere)
init_texture_coords_facevarying_attributes(sphere)
connect_common_attributes(sphere, computer)
connect_texture_coords_facevarying_attributes(sphere, computer)
return root, sphere
def create_procedural_mesh_capsule(
stage,
parentPath=None,
diameter=100,
yLength=200,
longitudeResolution=10,
hemisphereLatitudeResolution=10,
middleLatitudeResolution=10,
):
root, capsule, computer = create_mesh_computer(
stage, "ProceduralMeshCapsule", "CapsuleEvaluator", "omni.kit.procedural.mesh.CreateMeshCapsule", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:yLength", yLength],
["inputs:longitudeResolution", longitudeResolution],
["inputs:hemisphereLatitudeResolution", hemisphereLatitudeResolution],
["inputs:middleLatitudeResolution", middleLatitudeResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(capsule)
init_texture_coords_facevarying_attributes(capsule)
connect_common_attributes(capsule, computer)
connect_texture_coords_facevarying_attributes(capsule, computer)
return root, capsule
def create_procedural_mesh_cylinder(
stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10
):
root, cylinder, computer = create_mesh_computer(
stage, "ProceduralMeshCylinder", "CylinderEvaluator", "omni.kit.procedural.mesh.CreateMeshCylinder", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:height", height],
["inputs:longitudeResolution", longitudeResolution],
["inputs:latitudeResolution", latitudeResolution],
["inputs:capResolution", capResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(cylinder)
init_crease_attributes(cylinder)
init_normals_facevarying_attributes(cylinder)
init_texture_coords_facevarying_attributes(cylinder)
connect_common_attributes(cylinder, computer)
connect_crease_attributes(cylinder, computer)
connect_normals_facevarying_attributes(cylinder, computer)
connect_texture_coords_facevarying_attributes(cylinder, computer)
return root, cylinder
def create_procedural_mesh_cone(
stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10
):
root, cone, computer = create_mesh_computer(
stage, "ProceduralMeshCone", "ConeEvaluator", "omni.kit.procedural.mesh.CreateMeshCone", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:height", height],
["inputs:longitudeResolution", longitudeResolution],
["inputs:latitudeResolution", latitudeResolution],
["inputs:capResolution", capResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(cone)
init_crease_attributes(cone)
init_corner_attributes(cone)
init_normals_facevarying_attributes(cone)
init_texture_coords_facevarying_attributes(cone)
connect_common_attributes(cone, computer)
connect_crease_attributes(cone, computer)
connect_corner_attributes(cone, computer)
connect_normals_facevarying_attributes(cone, computer)
connect_texture_coords_facevarying_attributes(cone, computer)
return root, cone
def create_procedural_mesh_torus(
stage, parentPath=None, diameter=200, sectionDiameter=50, sectionTwist=0, loopResolution=10, sectionResolution=10
):
root, torus, computer = create_mesh_computer(
stage, "ProceduralMeshTorus", "TorusEvaluator", "omni.kit.procedural.mesh.CreateMeshTorus", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:sectionDiameter", sectionDiameter],
["inputs:sectionTwist", sectionTwist],
["inputs:loopResolution", loopResolution],
["inputs:sectionResolution", sectionResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(torus)
init_texture_coords_facevarying_attributes(torus)
connect_common_attributes(torus, computer)
connect_texture_coords_facevarying_attributes(torus, computer)
return root, torus
def create_procedural_mesh_disk(stage, parentPath=None, diameter=100, longitudeResolution=10, capResolution=10):
root, disk, computer = create_mesh_computer(
stage, "ProceduralMeshDisk", "DiskEvaluator", "omni.kit.procedural.mesh.CreateMeshDisk", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:longitudeResolution", longitudeResolution],
["inputs:capResolution", capResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(disk)
init_texture_coords_attributes(disk)
connect_common_attributes(disk, computer)
connect_texture_coords_attributes(disk, computer)
return root, disk
def create_procedural_mesh_plane(stage, parentPath=None, xLength=100, zLength=100, xResolution=10, zResolution=10):
root, plane, computer = create_mesh_computer(
stage, "ProceduralMeshPlane", "PlaneEvaluator", "omni.kit.procedural.mesh.CreateMeshPlane", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:xLength", xLength],
["inputs:zLength", zLength],
["inputs:xResolution", xResolution],
["inputs:zResolution", zResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(plane)
init_texture_coords_attributes(plane)
connect_common_attributes(plane, computer)
connect_texture_coords_attributes(plane, computer)
return root, plane
| 14,417 | Python | 33.910412 | 119 | 0.703614 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/menu.py | import omni.kit.ui
import omni.usd
# ======================================================================
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cube'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Sphere'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Capsule'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cylinder'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cone'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Torus'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Plane'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Disk'
)
class Menu:
def __init__(self):
self.on_startup()
def on_startup(self):
self.menus = []
editor_menu = omni.kit.ui.get_editor_menu()
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK, self._on_menu_click))
def _on_menu_click(self, menu_item, value):
if menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE:
omni.kit.commands.execute("CreateProceduralMeshCube")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE:
omni.kit.commands.execute("CreateProceduralMeshSphere")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE:
omni.kit.commands.execute("CreateProceduralMeshCapsule")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER:
omni.kit.commands.execute("CreateProceduralMeshCylinder")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE:
omni.kit.commands.execute("CreateProceduralMeshCone")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS:
omni.kit.commands.execute("CreateProceduralMeshTorus")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE:
omni.kit.commands.execute("CreateProceduralMeshPlane")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK:
omni.kit.commands.execute("CreateProceduralMeshDisk")
def on_shutdown(self):
self.menus = []
| 3,576 | Python | 50.840579 | 114 | 0.694631 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/command.py | import omni
from pxr import UsdGeom, Usd, Vt, Kind, Sdf
from .procedural_mesh_omnigraph_utils import (
create_procedural_mesh_cube,
create_procedural_mesh_sphere,
create_procedural_mesh_capsule,
create_procedural_mesh_cylinder,
create_procedural_mesh_cone,
create_procedural_mesh_torus,
create_procedural_mesh_plane,
create_procedural_mesh_disk,
)
class CreateProceduralMeshCommand(omni.kit.commands.Command):
def __init__(self):
self._create = None
self._stage = omni.usd.get_context().get_stage()
self._selection = omni.usd.get_context().get_selection()
def do(self):
xForm, mesh = self._create(self._stage)
self._prim_path = xForm.GetPath()
# set the new prim as the active selection
self._selection.set_prim_path_selected(self._prim_path.pathString, True, False, True, True)
return xForm
def undo(self):
prim = self._stage.GetPrimAtPath(self._prim_path)
if prim:
self._stage.RemovePrim(self._prim_path)
class CreateProceduralMeshCubeCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_cube
class CreateProceduralMeshSphereCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_sphere
class CreateProceduralMeshCapsuleCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_capsule
class CreateProceduralMeshCylinderCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_cylinder
class CreateProceduralMeshConeCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_cone
class CreateProceduralMeshTorusCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_torus
class CreateProceduralMeshPlaneCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_plane
class CreateProceduralMeshDiskCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_disk
omni.kit.commands.register(CreateProceduralMeshCubeCommand)
omni.kit.commands.register(CreateProceduralMeshSphereCommand)
omni.kit.commands.register(CreateProceduralMeshCapsuleCommand)
omni.kit.commands.register(CreateProceduralMeshCylinderCommand)
omni.kit.commands.register(CreateProceduralMeshConeCommand)
omni.kit.commands.register(CreateProceduralMeshTorusCommand)
omni.kit.commands.register(CreateProceduralMeshPlaneCommand)
omni.kit.commands.register(CreateProceduralMeshDiskCommand)
| 2,939 | Python | 31.307692 | 99 | 0.714869 |
omniverse-code/kit/exts/omni.kit.gfn/omni/kit/gfn/__init__.py | from ._kit_gfn import *
# Cached interface instance pointer
def get_geforcenow_interface() -> IGeForceNow:
"""Returns cached :class:`omni.kit.gfn.IGeForceNow` interface"""
if not hasattr(get_geforcenow_interface, "geforcenow"):
get_geforcenow_interface.geforcenow = acquire_geforcenow_interface()
return get_geforcenow_interface.geforcenow
| 362 | Python | 35.299996 | 76 | 0.745856 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/thumbnail_grid.py |
from functools import partial
from typing import Callable, Dict, List, Optional
import omni.ui as ui
from omni.ui import constant as fl
from .style import ICON_PATH
class ThumbnailItem(ui.AbstractItem):
"""
Data item for a thumbnail.
Args:
thumbnail (str): Url to thumbnail.
url (str): Url to item.
text (str): Display text for this item. Default use file name of url.
"""
def __init__(self, thumbnail: str, url: str, text: Optional[str] = None):
self.thumbnail = thumbnail
self.url = url
self.text = text if text else url.split("/")[-1]
super().__init__()
def execute(self):
pass
class ThumbnailModel(ui.AbstractItemModel):
"""
Data model for thumbnail items.
Args:
items (List[ThumbnailItem]): List of thumbnail items
"""
def __init__(self, items: List[ThumbnailItem]):
super().__init__()
self._items = items
def get_item_children(self, item: Optional[ThumbnailItem] = None) -> List[ThumbnailItem]:
return self._items
class ThumbnailGrid:
"""
Widget to show a grid (thumbnail + label).
Args:
model (ThumbnailModel): Data model.
label_height (int): Height for item label. Default 30.
thumbnail_width (int): Thumbnail width. Default 128.
thumbnail_height (int): Thumbnail height. Default 128.
thumbnail_padding_x (int): X padding between different thumbnail items. Default 2.
thumbnail_padding_y (int): Y padding between different thumbnail items. Default 4.
"""
def __init__(
self,
model: ThumbnailModel,
on_selection_changed: Callable[[Optional[ThumbnailItem]], None] = None,
label_height:int=fl._find("welcome_open_lable_size"),
thumbnail_width: int=fl._find("welcome_open_thumbnail_size"),
thumbnail_height: int=fl._find("welcome_open_thumbnail_size"),
thumbnail_padding_x: int=2,
thumbnail_padding_y: int=4,
):
self._model = model
self._on_selection_changed = on_selection_changed
self._label_height = label_height
self._thumbnail_width = thumbnail_width
self._thumbnail_height = thumbnail_height
self._thumbnail_padding_x = thumbnail_padding_x
self._thumbnail_padding_y = thumbnail_padding_y
self._column_width = self._thumbnail_width + 2 * self._thumbnail_padding_x
self._row_height = self._thumbnail_height + 2 * self._thumbnail_padding_y + self._label_height
self.__selected_thumbnail: Optional[ThumbnailItem] = None
self.__frames: Dict[ThumbnailItem, ui.Frame] = {}
self._build_ui()
@property
def selected(self) -> Optional[ThumbnailItem]:
return self.__selected_thumbnail
@selected.setter
def selected(self, item: Optional[ThumbnailItem]) -> None:
self.select_item(item)
def _build_ui(self):
self._container = ui.ScrollingFrame(
style_type_name_override="ThumbnailGrid.Frame",
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
)
self._refresh()
self._sub_model = self._model.subscribe_item_changed_fn(lambda m, i: self._refresh())
def _refresh(self):
self._container.clear()
with self._container:
self._grid = ui.VGrid(
column_width=self._column_width,
row_hegiht=self._row_height,
content_clipping=True,
)
with self._grid:
children = self._model.get_item_children()
if not children:
return
for item in children:
with ui.VStack():
ui.Spacer(height=self._thumbnail_padding_y)
with ui.HStack():
ui.Spacer(width=self._thumbnail_padding_x)
self.__frames[item] = ui.Frame(
build_fn=lambda i=item: self._build_thumbnail_item(i),
mouse_double_clicked_fn=lambda x, y, a, f, i=item: i.execute(),
mouse_pressed_fn=lambda x, y, a, f, i=item: self.select_item(i),
)
ui.Spacer(width=self._thumbnail_padding_x)
ui.Spacer(height=self._thumbnail_padding_y)
self._grid.set_mouse_pressed_fn(lambda x, y, btn, flag: self.select_item(None))
def _build_thumbnail_item(self, item: ThumbnailItem) -> None:
with ui.ZStack():
with ui.VStack():
self.build_thumbnail(item)
self.build_label(item)
ui.Rectangle(style_type_name_override="ThumbnailGrid.Selection")
def build_thumbnail(self, item: ThumbnailItem) -> None:
def on_image_progress(default_image: ui.Image, thumbnail_image: ui.Image, progress: float):
"""Called when the image loading progress is changed."""
if progress != 1.0:
# We only need to catch the moment when the image is loaded.
return
# Hide the default_image at the back.
default_image.visible = False
# Remove the callback to avoid circular references.
thumbnail_image.set_progress_changed_fn(None)
with ui.ZStack(width=self._thumbnail_width, height=self._thumbnail_height):
# Default image for thumbnail not defined or invalid thumbnail url or download in progress
# Hidden when actually thumbnail downloaded
default_image = ui.Image(f"{ICON_PATH}/usd_stage_256.png", style_type_name_override="ThumbnailGrid.Image")
if item.thumbnail:
thumbnail_image = ui.Image(item.thumbnail, style_type_name_override="ThumbnailGrid.Image")
thumbnail_image.set_progress_changed_fn(partial(on_image_progress, default_image, thumbnail_image))
def build_label(self, item: ThumbnailItem) -> None:
with ui.ZStack():
ui.Rectangle(style_type_name_override="ThumbnailGrid.Item.Background")
ui.Label(
item.text,
height=self._label_height,
word_wrap=True,
elided_text=True,
skip_draw_when_clipped=True,
alignment=ui.Alignment.CENTER,
style_type_name_override="ThumbnailGrid.Item",
)
def select_item(self, item: Optional[ThumbnailItem]) -> None:
if self.__selected_thumbnail:
self.__frames[self.__selected_thumbnail].selected = False
if item:
self.__frames[item].selected = True
self.__selected_thumbnail = item
if self._on_selection_changed:
self._on_selection_changed(item)
def find_item(self, url: str) -> Optional[ThumbnailItem]:
for item in self._model.get_item_children(None):
if item.url == url:
return item
return None
def select_url(self, url: str) -> None:
if url:
item = self.find_item(url)
self.select_item(item)
else:
self.select_item(None) | 7,367 | Python | 38.612903 | 118 | 0.586806 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/stage_tab.py | from typing import Optional
import carb
import omni.ui as ui
from omni.ui import constant as fl
from omni.kit.welcome.window import show_window as show_welcome_window
from .recent_widget import RecentWidget
from .template_grid import TemplateGrid
from .thumbnail_grid import ThumbnailItem
SETTING_SHOW_TEMPLATES = "/exts/omni.kit.welcome.open/show_templates"
class StageTab:
"""
Tab to show stage content.
"""
def __init__(self):
self._checkpoint_combobox = None
self._build_ui()
def destroy(self):
self._recent_widget.destroy()
def _build_ui(self):
with ui.VStack():
# Templates
if carb.settings.get_settings().get_as_bool(SETTING_SHOW_TEMPLATES):
with ui.HStack(height=0):
ui.Spacer(width=fl._find("welcome_content_padding_x"))
with ui.VStack():
ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator")
ui.Label("NEW", height=0, style_type_name_override="ThumbnailGrid.Title")
ui.Spacer(height=10)
ui.Spacer(width=fl._find("welcome_content_padding_x"))
with ui.HStack(height=fl._find("welcome_open_thumbnail_size") + fl._find("welcome_open_lable_size") + 60):
ui.Spacer(width=8)
self._template_grid = TemplateGrid(on_selection_changed=self.__on_template_selected)
ui.Spacer(width=8)
# Recent files
with ui.HStack(height=0):
ui.Spacer(width=fl._find("welcome_content_padding_x"))
with ui.VStack():
ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator")
with ui.HStack(height=20):
ui.Label("RECENT", width=0, style_type_name_override="ThumbnailGrid.Title")
ui.Spacer()
self._mode_image = ui.Image(name="grid", width=20, style_type_name_override="ThumbnailGrid.Mode", mouse_pressed_fn=lambda x, y, b,a: self.__toggle_thumbnail_model())
ui.Spacer(height=10)
ui.Spacer(width=fl._find("welcome_content_padding_x"))
self._recent_widget = RecentWidget(self.__on_recent_selected, self.__on_grid_mode)
# Open widgets
with ui.ZStack(height=26):
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=2)
with ui.HStack(spacing=2):
self._checkpoint_blank = ui.Rectangle(style_type_name_override="Stage.Blank")
self._checkpoint_frame = ui.Frame(build_fn=self.__build_checkpoints, visible=False)
# Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget
ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_file())
ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False))
def __toggle_thumbnail_model(self):
if self._mode_image.name == "grid":
self._mode_image.name = "table"
self._recent_widget.show_grid(False)
else:
self._mode_image.name = "grid"
self._recent_widget.show_grid(True)
def __build_checkpoints(self):
try:
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate("omni.kit.widget.versioning", True)
from omni.kit.widget.versioning import CheckpointCombobox
with ui.HStack(spacing=2):
with ui.ZStack(content_clipping=True, width=0):
ui.Rectangle(style_type_name_override="Stage.Blank")
ui.Label("Checkpoints", width=0, style_type_name_override="Stage.Label")
self._checkpoint_combobox = CheckpointCombobox(
self._recent_widget.selected_url if self._recent_widget.selected_url else "",
None,
width=ui.Fraction(1),
has_pre_spacer=False,
popup_width=0,
modal=True
)
except Exception as e:
carb.log_warn(f"Failed to create checkpoint combobox: {e}")
self._checkpoint_combobox = None
def __on_template_selected(self, item: Optional[ThumbnailItem]):
if item:
# Clear selection in recents
self._recent_widget.selected_url = None
# Hide checkpoint combobox
self._checkpoint_frame.visible = False
self._checkpoint_blank.visible = True
def __on_recent_selected(self, item: Optional[ui.AbstractItem]):
if item:
# Clear selection in templates
self._template_grid.selected = None
if isinstance(item, ThumbnailItem):
# Show checkpoint combobox if selected in recent grid
self._checkpoint_frame.visible = bool(item)
self._checkpoint_blank.visible = not bool(item)
if item and self._checkpoint_combobox:
self._checkpoint_combobox.url = item.url
def __on_grid_mode(self, grid_mode: bool) -> None:
# Show checkpoint combobox in grid mode and recent file selected
if grid_mode:
show_checkpoint = bool(self._recent_widget.selected_url)
self._checkpoint_frame.visible = show_checkpoint
self._checkpoint_blank.visible = not show_checkpoint
else:
self._checkpoint_frame.visible = False
self._checkpoint_blank.visible = True
def __open_file(self) -> None:
selected = self._template_grid.selected
if selected:
carb.log_info(f"Open template: {selected.url}")
selected.execute()
else:
self._recent_widget.open_selected(self._checkpoint_combobox.url if self._checkpoint_combobox else None)
| 6,253 | Python | 44.985294 | 189 | 0.58244 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/style.py | from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons")
fl.welcome_open_thumbnail_size = 145
fl.welcome_open_lable_size = 30
cl.welcome_open_item_selected = cl.shade(cl("#77878A"))
cl.welcome_open_label = cl.shade(cl("#9E9E9E"))
OPEN_PAGE_STYLE = {
"RadioButton": {"background_color": cl.transparent, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "padding": 0, "margin": 0},
"RadioButton.Label": {"font_size": fl.welcome_title_font_size, "color": cl.welcome_label, "alignment": ui.Alignment.LEFT_CENTER},
"RadioButton.Label:checked": {"color": cl.welcome_label_selected},
"RadioButton:checked": {"background_color": cl.transparent},
"RadioButton:hovered": {"background_color": cl.transparent},
"RadioButton:pressed": {"background_color": cl.transparent},
"RadioButton.Image::STAGE": {"image_url": f"{ICON_PATH}/USD.svg"},
"RadioButton.Image::SAMPLES": {"image_url": f"{ICON_PATH}/image.svg"},
"RadioButton.Image::FILE": {"image_url": f"{ICON_PATH}/hdd.svg"},
"RadioButton.Image": {"color": cl.welcome_label, "alignment": ui.Alignment.RIGHT_CENTER},
"RadioButton.Image:checked": {"color": cl.welcome_label_selected},
"ThumbnailGrid.Separator": {"color": cl.welcome_window_background, "border_width": 1.5},
"ThumbnailGrid.Title": {"color": 0xFFCCCCCC, "font_size": fl.welcome_title_font_size},
"ThumbnailGrid.Mode": {"margin": 2},
"ThumbnailGrid.Mode::grid": {"image_url": f"{ICON_PATH}/thumbnail.svg"},
"ThumbnailGrid.Mode::table": {"image_url": f"{ICON_PATH}/list.svg"},
"ThumbnailGrid.Frame": {
"background_color": cl.transparent,
"secondary_color": 0xFF808080,
"border_radius": 0,
"scrollbar_size": 10,
},
"ThumbnailGrid.Selection": {
"background_color": cl.transparent,
},
"ThumbnailGrid.Selection:selected": {
"border_width": 1,
"border_color": cl.welcome_open_item_selected,
"border_radius": 0,
},
"ThumbnailGrid.Item.Background": {
"background_color": cl.transparent,
},
"ThumbnailGrid.Item.Background:selected": {
"background_color": 0xFF525252,
},
"ThumbnailGrid.Item": {
"margin_width": 2,
"color": cl.welcome_label,
},
"Template.Add": {"color": 0xFFFFFFFF},
"Template.Add:hovered": {"color": cl.welcome_label_selected},
"Template.Add:pressed": {"color": cl.welcome_label_selected},
"Template.Add:selected": {"color": cl.welcome_label_selected},
"Stage.Label": {"color": cl.welcome_open_label, "margin_width": 6},
"Stage.Button": {
"background_color": 0xFF23211F,
"selected_color": 0xFF8A8777,
"color": cl.welcome_open_label,
"margin": 0,
"padding": 0
},
"Stage.Button:hovered": {"background_color": 0xFF3A3A3A},
"Stage.Button.Label": {"color": cl.welcome_open_label},
"Stage.Button.Label:disabled": {"color": 0xFF3A3A3A},
"Stage.Separator": {"background_color": cl.welcome_window_background},
"Stage.Blank": {"background_color": cl.welcome_content_background},
} | 3,242 | Python | 41.116883 | 133 | 0.652067 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/extension.py | from typing import Optional
import omni.ext
import omni.ui as ui
from omni.kit.welcome.window import register_page
from .open_widget import OpenWidget
class OpenPageExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._widget: Optional[OpenWidget] = None
self.__ext_name = omni.ext.get_extension_name(ext_id)
register_page(self.__ext_name, self.build_ui)
def on_shutdown(self):
if self._widget:
self._widget.destroy()
self._widget = None
def build_ui(self) -> None:
self._widget = OpenWidget()
| 585 | Python | 23.416666 | 61 | 0.652991 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_widget.py | import asyncio
import os
from typing import Callable, List, Optional
import carb.settings
import omni.ui as ui
from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel
SETTING_RECENT_FILES = "/persistent/app/file/recentFiles"
class RecentItem(ThumbnailItem):
"""
Data item for recent file.
"""
def __init__(self, url: str):
super().__init__(self.__get_thumbnail(url), url)
def __get_thumbnail(self, url: str):
file_name = os.path.basename(url)
path = os.path.dirname(url)
# Do not check if thumbnail image exists here, leave it to ThumbnailGrid
return f"{path}/.thumbs/256x256/{file_name}.png"
def execute(self, url: Optional[str] = None):
from .open_action import run_open_action
run_open_action("omni.kit.window.file", "open_stage", url if url else self.url)
class RecentModel(ThumbnailModel):
"""
Data model for recent files.
"""
def __init__(self, recent_files: List[str]):
super().__init__([])
self.refresh(recent_files)
def refresh(self, recent_files: List[str]) -> None:
self._items = [RecentItem(recent) for recent in recent_files] if recent_files else []
self._item_changed(None)
class RecentWidget:
"""
Show recents grid and open widgets.
"""
def __init__(self, on_recent_changed_fn: Callable[[Optional[ui.AbstractItem]], None], on_grid_mode_fn: Callable[[bool], None]):
self._settings = carb.settings.get_settings()
self.__get_recent_history()
self._grid_model = RecentModel(self.__recent_files)
self._recent_table: Optional[RecentTable] = None
self.__on_recent_selected_fn = on_recent_changed_fn
self.__on_grid_mode_fn = on_grid_mode_fn
self._build_ui()
def destroy(self):
self._subscription = None
self._event_sub = None
@property
def selected_url(self) -> str:
if self._grid_frame.visible:
return self._recent_grid.selected.url if self._recent_grid.selected else ""
else:
return self._recent_table.selected
@selected_url.setter
def selected_url(self, url: str) -> None:
if self._grid_frame.visible:
self._recent_grid.select_url(url)
else:
self._recent_table.selected = url
def clear_selection(self):
if self._grid_frame.visible:
self._recent_grid.selected = None
else:
self._recent_table.selected = None
def show_grid(self, grid: bool) -> None:
self._grid_frame.visible = grid
self._table_frame.visible = not grid
if grid:
# Set grid selection from table
if self._recent_table:
self._recent_grid.select_url(self._recent_table.selected)
else:
# Set table selection from grid
if self._recent_table:
if self._recent_grid.selected:
self._recent_table.selected = self._recent_grid.selected.url
else:
# Wait for widget create and set selection
async def __delay_select():
await omni.kit.app.get_app().next_update_async()
if self._recent_grid.selected:
self._recent_table.selected = self._recent_grid.selected.url
asyncio.ensure_future(__delay_select())
self.__on_grid_mode_fn(grid)
def open_selected(self, checkpoint_url: Optional[str]) -> None:
def __open_file(url):
carb.log_info(f"Open recent file: {url}")
from .open_action import run_open_action
run_open_action("omni.kit.window.file", "open_stage", url)
if self.selected_url:
if self._grid_frame.visible:
__open_file(checkpoint_url or self.selected_url)
else:
__open_file(self._recent_table.get_filename())
def _build_ui(self):
with ui.ZStack():
self._grid_frame = ui.Frame(build_fn=self._build_grid_ui)
self._table_frame = ui.Frame(build_fn=self._build_table_ui, visible=False)
def _build_table_ui(self):
try:
from .recent_table import RecentTable
self._recent_table = RecentTable(self.__recent_files, on_selection_changed_fn=self.__on_recent_selected_fn)
except Exception as e:
self._recent_table = None
carb.log_error(f"Failed to create recent table: {e}")
def _build_grid_ui(self):
with ui.VStack():
# Recent grid
with ui.HStack():
ui.Spacer(width=8)
self._recent_grid = ThumbnailGrid(self._grid_model, on_selection_changed=self.__on_recent_selected_fn)
ui.Spacer(width=8)
def _on_change(self, item, event_type):
if event_type == carb.settings.ChangeEventType.CHANGED:
self.__recent_files = self._settings.get(SETTING_RECENT_FILES)
self.__rebuild_recents()
def __rebuild_recents_from_event(self) -> None:
from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types
self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD)
if self._recent_table:
self._recent_table.refresh(self.__recent_files)
self._grid_model.refresh(self.__recent_files)
def __get_recent_history(self):
load_recents_from_event = self._settings.get("/exts/omni.kit.welcome.open/load_recent_from_event")
if load_recents_from_event:
self.__get_recent_from_event()
else:
self.__recent_files = self._settings.get(SETTING_RECENT_FILES)
# If recent files changed, refresh
self._subscription = omni.kit.app.SettingChangeSubscription(SETTING_RECENT_FILES, self._on_change)
def __get_recent_from_event(self) -> None:
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate("omni.kit.helper.file_utils", True)
from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types, FILE_EVENT_QUEUE_UPDATED
self._max_recent_files = self._settings.get("exts/omni.kit.menu.file/maxRecentFiles") or 10
self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD)
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._event_sub = event_stream.create_subscription_to_pop_by_type(FILE_EVENT_QUEUE_UPDATED, lambda _: self.__rebuild_recents_from_event()) | 6,736 | Python | 39.10119 | 146 | 0.614757 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_action.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["run_open_action"]
import asyncio
def run_open_action(extension_id: str, action_id: str, *args, **kwargs):
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
# Setup the viewport (and UI first)
action_registry.execute_action("omni.app.setup", "enable_viewport_rendering")
# Finally hide the Welcome window
from omni.kit.welcome.window import show_window as show_welcome_window
show_welcome_window(visible=False, stage_opened=True)
# Run the action which will open or create a Usd.Stage
async def __execute_action():
import omni.kit.app
# OM-90720: sometimes open stage will popup a prompt to ask if save current stage
# But the prompt is a popup window which will hide immediately if the welcome window (modal) still there
# As a result, the required stage will not be opened
# So here wait a few frames to make sure welcome window is really closed
for _ in range(4):
await omni.kit.app.get_app().next_update_async()
action_registry.execute_action(extension_id, action_id, *args, **kwargs)
asyncio.ensure_future(__execute_action())
| 1,624 | Python | 45.42857 | 112 | 0.723522 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_widget.py | from typing import Dict, Optional
import carb
import omni.ui as ui
from omni.kit.welcome.window import show_window as show_welcome_window
from omni.ui import constant as fl
from .stage_tab import StageTab
from .style import OPEN_PAGE_STYLE
class OpenWidget:
"""
Widget for open page.
"""
def __init__(self):
self.__tabs: Dict[str, callable] = {
"STAGE": self.__build_stage,
"SAMPLES": self.__build_sample,
"FILE": self.__build_file,
}
self.__tab_frames: Dict[str, ui.Frame] = {}
self.__stage_tab: Optional[StageTab] = None
self._build_ui()
def destroy(self):
if self.__stage_tab:
self.__stage_tab.destroy()
self.__stage_tab = None
def _build_ui(self):
self._collection = ui.RadioCollection()
with ui.ZStack(style=OPEN_PAGE_STYLE):
# Background
ui.Rectangle(style_type_name_override="Content")
with ui.VStack():
# Tab buttons
with ui.VStack(height=fl._find("welcome_page_title_height")):
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
with ui.HStack(spacing=30):
for tab in self.__tabs.keys():
ui.RadioButton(text=tab, width=0, spacing=8, image_width=24, image_height=24, name=tab, radio_collection=self._collection, clicked_fn=lambda t=tab: self._show_tab(t))
ui.Spacer()
ui.Spacer()
# Tab frames
with ui.ZStack():
for tab in self.__tabs.keys():
self.__tab_frames[tab] = ui.Frame(build_fn=lambda t=tab: self.__tabs[t](), visible=tab == "STAGE")
def _show_tab(self, name: str) -> None:
for tab in self.__tabs.keys():
if tab == name:
self.__tab_frames[name].visible = True
else:
self.__tab_frames[tab].visible = False
def __build_stage(self):
self.__stage_tab = StageTab()
def __build_sample(self):
try:
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate("omni.kit.browser.sample", True)
from omni.kit.browser.sample import get_instance as get_sample_instance
from omni.kit.browser.sample.browser_widget import SampleTreeFolderBrowserWidget
from omni.kit.browser.core import BrowserSearchBar
# Remove options button
class SampleWidget(SampleTreeFolderBrowserWidget):
def _build_search_bar(self):
self._search_bar = BrowserSearchBar(options_menu=None)
# Hack to close welcome window after sample opened
def __open_sample(item):
from .open_action import run_open_action
run_open_action("omni.kit.window.file", "open_stage", item.url)
model = get_sample_instance().get_model()
model.execute = __open_sample
# Sample widget
with ui.ZStack():
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=4)
with ui.HStack():
ui.Spacer(width=2)
self.__sample_widget = SampleWidget(model)
# Open widgets
with ui.ZStack(height=26):
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=2)
with ui.HStack(spacing=2):
ui.Rectangle(style_type_name_override="Stage.Blank")
# Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget
ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_sample())
ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False))
except Exception as e:
carb.log_error(f"Failed to import sample browser widget: {e}")
def __build_file(self):
try:
from omni.kit.window.filepicker import FilePickerWidget
def __open_file(file_name, dir_name):
from .open_action import run_open_action
run_open_action("omni.kit.window.file", "open_stage", dir_name + file_name)
with ui.ZStack():
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=2)
with ui.HStack():
ui.Spacer(width=2)
FilePickerWidget(
"Welcome",
enable_checkpoints=True,
apply_button_label="Open File",
cancel_button_label="Close",
click_apply_handler=__open_file,
click_cancel_handler=lambda f, d: show_welcome_window(visible=False),
modal=True,
)
except Exception as e:
carb.log_error(f"Failed to import file picker widget: {e}")
def __open_sample(self):
selections = self.__sample_widget.detail_selection
if selections:
self.__sample_widget._browser_model.execute(selections[0])
show_welcome_window(visible=False) | 5,849 | Python | 42.333333 | 198 | 0.526586 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_table.py | import os
from typing import List, Optional
import omni.client
import omni.ui as ui
from omni.kit.widget.filebrowser import LAYOUT_SINGLE_PANE_LIST, LISTVIEW_PANE, FileBrowserItem, FileBrowserModel
from omni.kit.widget.filebrowser.model import FileBrowserItemFields
from omni.kit.window.filepicker import FilePickerWidget
class RecentTableModel(FileBrowserModel):
def __init__(self, recent_files: List[str]):
super().__init__()
self.refresh(recent_files)
def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]:
return self._items
def refresh(self, recent_files: List[str]):
if recent_files:
self._items = [self.__create_file_item(url) for url in recent_files]
else:
self._items = []
self._item_changed(None)
def __create_file_item(self, url: str) -> Optional[FileBrowserItem]:
file_name = os.path.basename(url)
result, entry = omni.client.stat(url)
if result == omni.client.Result.OK:
item = FileBrowserItem(url, FileBrowserItemFields(file_name, entry.modified_time, 0, 0), is_folder=False)
item._models = (ui.SimpleStringModel(item.name), entry.modified_time, ui.SimpleStringModel(""))
return item
else:
return None
class RecentTable:
def __init__(self, recent_files: List[str], on_selection_changed_fn: callable):
self.__recent_files = recent_files
self.__picker: Optional[FilePickerWidget] = None
self.__on_selection_changed_fn = on_selection_changed_fn
self._build_ui()
@property
def selected(self) -> str:
if self.__picker:
selections = self.__picker._view.get_selections(pane=LISTVIEW_PANE)
if selections:
return selections[0].path
else:
return ""
else:
return ""
@selected.setter
def selected(self, url: str) -> None:
if self.__picker:
if url:
for item in self._model.get_item_children(None):
if item.path == url:
selections = [item]
else:
selections = []
self.__picker._view.set_selections(selections, pane=LISTVIEW_PANE)
def refresh(self, recent_files: List[str]):
self._model.refresh(recent_files)
def get_filename(self) -> str:
return self.__picker._api.get_filename() if self.__picker else ""
def _build_ui(self):
with ui.ZStack():
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=2)
with ui.HStack():
self.__picker = FilePickerWidget(
"Welcome",
enable_tool_bar=False,
layout=LAYOUT_SINGLE_PANE_LIST,
show_grid_view=False,
save_grid_view=False,
enable_checkpoints=True,
enable_zoombar=False,
enable_file_bar=False,
selection_changed_fn=self.__on_selection_changed_fn,
)
self._model = RecentTableModel(self.__recent_files)
self.__picker._view.show_model(self._model)
| 3,377 | Python | 35.717391 | 117 | 0.568256 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/template_grid.py | import functools
import locale
from typing import List
import omni.kit.stage_templates
import omni.ui as ui
from omni.kit.welcome.window import show_window
from .style import ICON_PATH
from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel
import asyncio
class TemplateItem(ThumbnailItem):
"""
Data item for template.
"""
def __init__(self, template: list):
# TODO: how to get template thumbnail?
stage_name = template[0]
super().__init__("", stage_name)
def execute(self):
from .open_action import run_open_action
run_open_action("omni.kit.stage.templates", self.__get_action_name())
def __get_action_name(self):
return "create_new_stage_" + self.url.lower().replace('-', '_').replace(' ', '_')
class TemplateModel(ThumbnailModel):
"""
Data model for templates.
"""
def __init__(self):
stage_templates = omni.kit.stage_templates.get_stage_template_list()
template_items: List[ThumbnailItem] = []
def sort_cmp(template1, template2):
return locale.strcoll(template1[0], template2[0])
for template_list in stage_templates:
for template in sorted(template_list.items(), key=functools.cmp_to_key(sort_cmp)):
template_items.append(TemplateItem(template))
super().__init__(template_items)
class TemplateGrid(ThumbnailGrid):
"""
Template grid.
"""
def __init__(self, **kwargs):
self._model = TemplateModel()
super().__init__(self._model, **kwargs)
def build_thumbnail(self, item: ThumbnailItem):
padding = 5
with ui.ZStack():
super().build_thumbnail(item)
with ui.VStack():
ui.Spacer()
with ui.HStack(height=20):
ui.Spacer()
ui.Image(
f"{ICON_PATH}/add_dark.svg",
width=20,
style_type_name_override="Template.Add",
mouse_pressed_fn=lambda x, y, a, f, i=item: i.execute()
)
ui.Spacer(width=padding)
ui.Spacer(height=padding) | 2,216 | Python | 29.791666 | 94 | 0.576715 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection_actions.py | import omni.kit.actions.core
def register_actions(extension_id):
import omni.kit.commands
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Selection Actions"
action_registry.register_action(
extension_id,
"all",
lambda: omni.kit.commands.execute("SelectAll"),
display_name="Select->All",
description="Select all prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"none",
lambda: omni.kit.commands.execute("SelectNone"),
display_name="Select->None",
description="Deselect all prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"invert",
lambda: omni.kit.commands.execute("SelectInvert"),
display_name="Select->Invert",
description="Deselect all currently unselected prims, and select all currently unselected prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"parent",
lambda: omni.kit.commands.execute("SelectParentCommand"),
display_name="Select->Parent",
description="Select the parents of all currently selected prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"leaf",
lambda: omni.kit.commands.execute("SelectLeafCommand"),
display_name="Select->Leaf",
description="Select the leafs of all currently selected prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"hierarchy",
lambda: omni.kit.commands.execute("SelectHierarchyCommand"),
display_name="Select->Hierarchy",
description="Select the hierachies of all currently selected prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"similar",
lambda: omni.kit.commands.execute("SelectSimilarCommand"),
display_name="Select->Similar",
description="Select prims of the same type as any currently selected prim.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"HideUnselected",
lambda: omni.kit.commands.execute("HideUnselected"),
display_name="Select->Hide Unselected",
description="Hide Unselected Prims",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"UnhideAllPrims",
lambda: omni.kit.commands.execute("UnhideAllPrims"),
display_name="Select->Unhide All Prims",
description="Unhide All Prims",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 2,880 | Python | 31.370786 | 106 | 0.639931 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/__init__.py | from .selection import *
| 25 | Python | 11.999994 | 24 | 0.76 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection.py | import omni.kit.commands
from pxr import Usd, Sdf, UsdGeom, Gf, Tf, Trace, Kind
from .selection_actions import register_actions, deregister_actions
class SelectionExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name)
def on_shutdown(self):
deregister_actions(self._ext_name)
class SelectAllCommand(omni.kit.commands.Command):
"""
Select all prims.
Args:
type (Union[str, None]): Specific type name. If it's None, it will select
all prims. If it has type str with value "", it will select all prims without any type.
Otherwise, it will select prims with that type.
"""
def __init__(self, type=None):
self._type = type
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
@Trace.TraceFunction
def do(self):
omni.usd.get_context().get_selection().select_all_prims(self._type)
def undo(self):
if self._prev_selection:
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
else:
omni.usd.get_context().get_selection().clear_selected_prim_paths()
class SelectNoneCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def do(self):
omni.usd.get_context().get_selection().clear_selected_prim_paths()
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectInvertCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
@Trace.TraceFunction
def do(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
omni.usd.get_context().get_selection().select_inverted_prims()
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class HideUnselectedCommand(omni.kit.commands.Command):
def get_parent_prims(self, stage, prim):
parent_prims = set([])
while prim.GetParent():
parent_prims.add(prim.GetParent().GetPath())
prim = prim.GetParent()
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
break
return parent_prims
def get_all_children(self, prim):
children_list = set([])
queue = [prim]
while len(queue) > 0:
child_prim = queue.pop()
for child in child_prim.GetAllChildren():
children_list.add(child.GetPath())
queue.append(child)
return children_list
def __init__(self):
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
# if selected path as children and none of the children are selected, then all the children are selected..
selected_prims = set([])
for prim_path in selection:
sdf_prim_path = Sdf.Path(prim_path)
prim = stage.GetPrimAtPath(sdf_prim_path)
if prim:
selected_prims.add(sdf_prim_path)
selected_prims.update(self.get_all_children(prim))
## exclude parent prims as visabillity is inherited
all_parent_prims = set([])
for prim_path in selected_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim:
all_parent_prims.update(self.get_parent_prims(stage, prim))
selected_prims.update(all_parent_prims)
all_prims = set([])
children_iterator = iter(stage.TraverseAll())
for prim in children_iterator:
if omni.usd.is_hidden_type(prim):
children_iterator.PruneChildren()
continue
all_prims.add(prim.GetPath())
self._invert_prims = [item for item in all_prims if item not in selected_prims]
self._prev_visabillity = []
for prim_path in self._invert_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
continue
imageable = UsdGeom.Imageable(prim)
if imageable:
self._prev_visabillity.append([prim, imageable.ComputeVisibility()])
@Trace.TraceFunction
def do(self):
stage = omni.usd.get_context().get_stage()
for prim_path in self._invert_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
continue
imageable = UsdGeom.Imageable(prim)
if imageable:
imageable.MakeInvisible()
def undo(self):
for prim, state in self._prev_visabillity:
imageable = UsdGeom.Imageable(prim)
if imageable:
if state == UsdGeom.Tokens.invisible:
imageable.MakeInvisible()
else:
imageable.MakeVisible()
class SelectParentCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def do(self):
stage = omni.usd.get_context().get_stage()
parent_prims = set()
for prim_path in self._prev_selection:
prim = stage.GetPrimAtPath(prim_path)
if prim and prim.GetParent() is not None:
parent_prims.add(prim.GetParent().GetPath().pathString)
omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(parent_prims)), True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectLeafCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def collect_leafs(self, prim, leaf_set):
prim_children = prim.GetChildren()
if not prim_children:
leaf_set.add(prim.GetPath().pathString)
else:
for child in prim_children:
self.collect_leafs(child, leaf_set)
def do(self):
stage = omni.usd.get_context().get_stage()
leaf_prims = set()
for prim_path in self._prev_selection:
prim = stage.GetPrimAtPath(prim_path)
self.collect_leafs(prim, leaf_prims)
omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(leaf_prims)), True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectHierarchyCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def collect_hierarchy(self, prim, hierarchy_set):
hierarchy_set.add(prim.GetPath().pathString)
prim_children = prim.GetChildren()
for child in prim_children:
self.collect_hierarchy(child, hierarchy_set)
def do(self):
stage = omni.usd.get_context().get_stage()
heirarchy_prims = set()
for prim_path in self._prev_selection:
prim = stage.GetPrimAtPath(prim_path)
self.collect_hierarchy(prim, heirarchy_prims)
omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(heirarchy_prims)), True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectSimilarCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def do(self):
stage = omni.usd.get_context().get_stage()
similar_prim_types = set()
for prim_path in self._prev_selection:
prim_type = stage.GetPrimAtPath(prim_path).GetTypeName()
similar_prim_types.add(prim_type)
omni.usd.get_context().get_selection().select_all_prims(sorted(list(similar_prim_types)))
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectListCommand(omni.kit.commands.Command):
def __init__(self, **kwargs):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
self._new_selection = []
if 'selection' in kwargs:
self._new_selection = kwargs['selection']
def do(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._new_selection, True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectKindCommand(omni.kit.commands.Command):
def __init__(self, **kwargs):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
self._kind = ""
if 'kind' in kwargs:
self._kind = kwargs['kind']
@Trace.TraceFunction
def do(self):
selection = []
for prim in omni.usd.get_context().get_stage().TraverseAll():
model_api = Usd.ModelAPI(prim)
if Kind.Registry.IsA(model_api.GetKind(), self._kind):
selection.append(str(prim.GetPath()))
omni.usd.get_context().get_selection().set_selected_prim_paths(selection, True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
| 9,914 | Python | 36.415094 | 114 | 0.620637 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/create_prims.py | import os
import carb
import carb.settings
import omni.kit.commands
from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux
def create_test_stage():
settings = carb.settings.get_settings()
default_prim_name = settings.get("/persistent/app/stage/defaultPrimName")
rootname = f"/{default_prim_name}"
stage = omni.usd.get_context().get_stage()
kit_folder = carb.tokens.get_tokens_interface().resolve("${kit}")
omni_pbr_mtl = os.path.normpath(kit_folder + "/mdl/core/Base/OmniPBR.mdl")
# create Looks folder
omni.kit.commands.execute(
"CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=False
)
# create GroundMat material
mtl_name = "GroundMat"
mtl_path = omni.usd.get_stage_next_free_path(
stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False
)
omni.kit.commands.execute(
"CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=mtl_path
)
ground_mat_prim = stage.GetPrimAtPath(mtl_path)
shader = UsdShade.Material(ground_mat_prim).ComputeSurfaceSource("mdl")[0]
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(ground_mat_prim, "specular_level", 0.25, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(
ground_mat_prim, "diffuse_color_constant", Gf.Vec3f(0.08, 0.08, 0.08), Sdf.ValueTypeNames.Color3f
)
omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f)
omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f)
omni.usd.create_material_input(ground_mat_prim, "metallic_constant", 0.0, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float)
# create BackSideMat
mtl_name = "BackSideMat"
backside_mtl_path = omni.usd.get_stage_next_free_path(
stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False
)
omni.kit.commands.execute(
"CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=backside_mtl_path
)
backside_mtl_prim = stage.GetPrimAtPath(backside_mtl_path)
shader = UsdShade.Material(backside_mtl_prim).ComputeSurfaceSource("mdl")[0]
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
omni.usd.create_material_input(
backside_mtl_prim,
"diffuse_color_constant",
Gf.Vec3f(0.11814344, 0.118142255, 0.118142255),
Sdf.ValueTypeNames.Color3f,
)
omni.usd.create_material_input(backside_mtl_prim, "reflection_roughness_constant", 0.27, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(backside_mtl_prim, "specular_level", 0.163, Sdf.ValueTypeNames.Float)
# create EmissiveMat
mtl_name = "EmissiveMat"
emissive_mtl_path = omni.usd.get_stage_next_free_path(
stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False
)
omni.kit.commands.execute(
"CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=emissive_mtl_path
)
emissive_mtl_prim = stage.GetPrimAtPath(emissive_mtl_path)
shader = UsdShade.Material(emissive_mtl_prim).ComputeSurfaceSource("mdl")[0]
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
omni.usd.create_material_input(
emissive_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0, 0, 0), Sdf.ValueTypeNames.Color3f
)
omni.usd.create_material_input(emissive_mtl_prim, "reflection_roughness_constant", 1, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(emissive_mtl_prim, "specular_level", 0, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(emissive_mtl_prim, "enable_emission", True, Sdf.ValueTypeNames.Bool)
omni.usd.create_material_input(emissive_mtl_prim, "emissive_color", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f)
omni.usd.create_material_input(emissive_mtl_prim, "emissive_intensity", 15000, Sdf.ValueTypeNames.Float)
# create studiohemisphere
hemisphere_path = omni.usd.get_stage_next_free_path(stage, "{}/studiohemisphere".format(rootname), False)
omni.kit.commands.execute(
"CreatePrim", prim_path=hemisphere_path, prim_type="Xform", select_new_prim=False, attributes={}
)
hemisphere_prim = stage.GetPrimAtPath(hemisphere_path)
UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
Usd.ModelAPI(hemisphere_prim).SetKind("group")
# create sphere
hemisphere_sphere_path = omni.usd.get_stage_next_free_path(
stage, "{}/studiohemisphere/Sphere".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=hemisphere_sphere_path,
prim_type="Sphere",
select_new_prim=False,
attributes={UsdGeom.Tokens.radius: 100},
)
hemisphere_prim = stage.GetPrimAtPath(hemisphere_sphere_path)
Usd.ModelAPI(hemisphere_prim).SetKind("assembly")
# set transform
hemisphere_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(2500, 2500, 2500))
hemisphere_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"])
UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=hemisphere_sphere_path,
material_path=mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create floor
hemisphere_floor_path = omni.usd.get_stage_next_free_path(
stage, "{}/studiohemisphere/Floor".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=hemisphere_floor_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100},
)
hemisphere_floor_prim = stage.GetPrimAtPath(hemisphere_floor_path)
# set transform
hemisphere_floor_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(2500, 0.1, 2500)
)
hemisphere_floor_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"])
UsdGeom.PrimvarsAPI(hemisphere_floor_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=hemisphere_floor_path,
material_path=mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create LightPivot_01
light_pivot1_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_01".format(rootname), False)
omni.kit.commands.execute(
"CreatePrim", prim_path=light_pivot1_path, prim_type="Xform", select_new_prim=False, attributes={}
)
light_pivot1_prim = stage.GetPrimAtPath(light_pivot1_path)
UsdGeom.PrimvarsAPI(light_pivot1_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# set transform
light_pivot1_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
light_pivot1_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(-30.453436397207547, 16.954190666353664, 9.728788165428536)
)
light_pivot1_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0.9999999445969171, 1.000000574567198, 0.9999995086845976)
)
light_pivot1_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
# create AreaLight
light_pivot1_al_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_01/AreaLight".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim", prim_path=light_pivot1_al_path, prim_type="Xform", select_new_prim=False, attributes={}
)
light_pivot1_al_prim = stage.GetPrimAtPath(light_pivot1_al_path)
UsdGeom.PrimvarsAPI(light_pivot1_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# set transform
light_pivot1_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0, 0, 800)
)
light_pivot1_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
light_pivot1_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(4.5, 4.5, 4.5)
)
light_pivot1_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
# create AreaLight RectLight
light_pivot1_alrl_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_01/AreaLight/RectLight".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=light_pivot1_alrl_path,
prim_type="RectLight",
select_new_prim=False,
attributes={},
)
light_pivot1_alrl_prim = stage.GetPrimAtPath(light_pivot1_alrl_path)
# set values
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
# https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(15000)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180)
else:
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(15000)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180)
# create AreaLight Backside
backside_albs_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_01/AreaLight/Backside".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=backside_albs_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
backside_albs_prim = stage.GetPrimAtPath(backside_albs_path)
# set values
backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1))
backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02))
backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=backside_albs_path,
material_path=backside_mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create AreaLight EmissiveSurface
backside_ales_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_01/AreaLight/EmissiveSurface".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=backside_ales_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
backside_ales_prim = stage.GetPrimAtPath(backside_ales_path)
# set values
backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0, 0, 0.002)
)
backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02))
backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=backside_ales_path,
material_path=emissive_mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create LightPivot_02
light_pivot2_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_02".format(rootname), False)
omni.kit.commands.execute(
"CreatePrim", prim_path=light_pivot2_path, prim_type="Xform", select_new_prim=False, attributes={}
)
light_pivot2_prim = stage.GetPrimAtPath(light_pivot2_path)
UsdGeom.PrimvarsAPI(light_pivot2_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# set transform
light_pivot2_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
light_pivot2_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(-149.8694695859529, 35.87684189578612, -18.78499937937383)
)
light_pivot2_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0.9999999347425043, 0.9999995656418647, 1.0000001493100235)
)
light_pivot2_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
# create AreaLight
light_pivot2_al_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_02/AreaLight".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim", prim_path=light_pivot2_al_path, prim_type="Xform", select_new_prim=False, attributes={}
)
light_pivot2_al_prim = stage.GetPrimAtPath(light_pivot2_al_path)
UsdGeom.PrimvarsAPI(light_pivot2_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# set transform
light_pivot2_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0, 0, 800)
)
light_pivot2_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
light_pivot2_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(1.5, 1.5, 1.5)
)
light_pivot2_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
# create AreaLight RectLight
light_pivot2_alrl_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_02/AreaLight/RectLight".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=light_pivot2_alrl_path,
prim_type="RectLight",
select_new_prim=False,
attributes={},
)
light_pivot2_alrl_prim = stage.GetPrimAtPath(light_pivot2_alrl_path)
# set values
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
# https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(55000)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180)
else:
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(55000)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180)
# create AreaLight Backside
backside_albs_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_02/AreaLight/Backside".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=backside_albs_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
backside_albs_prim = stage.GetPrimAtPath(backside_albs_path)
# set values
backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1))
backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02))
backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=backside_albs_path,
material_path=backside_mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create AreaLight EmissiveSurface
backside_ales_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_02/AreaLight/EmissiveSurface".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=backside_ales_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
backside_ales_prim = stage.GetPrimAtPath(backside_ales_path)
# set values
backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0, 0, 0.002)
)
backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02))
backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=backside_ales_path,
material_path=emissive_mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
| 20,064 | Python | 48.178921 | 126 | 0.707835 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/__init__.py | from .test_commands import *
from .create_prims import *
| 57 | Python | 18.333327 | 28 | 0.754386 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/test_commands.py | import random
import omni.kit.test
import omni.kit.commands
import omni.kit.undo
from pxr import Usd, UsdGeom, Kind
class TestCommands(omni.kit.test.AsyncTestCase):
def check_visibillity(self, visible_set, invisible_set):
context = omni.usd.get_context()
stage = context.get_stage()
for prim in stage.TraverseAll():
if prim and not prim.GetMetadata("hide_in_stage_window"):
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
continue
imageable = UsdGeom.Imageable(prim)
if imageable:
if imageable.ComputeVisibility() == UsdGeom.Tokens.invisible:
self.assertTrue((prim.GetPath().pathString in invisible_set))
else:
self.assertTrue((prim.GetPath().pathString in visible_set))
def get_parent_prims(self, prim):
stage = omni.usd.get_context().get_stage()
parent_prims = []
while prim.GetParent():
parent_prims.append(prim.GetParent().GetPath().pathString)
prim = prim.GetParent()
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
break
return parent_prims
def get_all_children(self, prim, child_list):
for child in prim.GetAllChildren():
child_list.append(child.GetPath().pathString)
self.get_all_children(child, child_list)
def get_all_prims(self):
all_prims = []
stage = omni.usd.get_context().get_stage()
for prim in stage.TraverseAll():
if not prim.GetMetadata("hide_in_stage_window"):
all_prims.append(prim.GetPath().pathString)
return all_prims
async def setUp(self):
# Disable logging for the time of tests to avoid spewing errors
await omni.usd.get_context().new_stage_async()
omni.kit.selection.tests.create_test_stage()
async def tearDown(self):
pass
async def test_command_select_all(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_root_prims = []
all_prims = []
material_prims = []
cube_prims = []
sphere_prims = []
children_iterator = iter(stage.TraverseAll())
for prim in children_iterator:
all_root_prims.append(prim.GetPath().pathString)
children_iterator.PruneChildren()
for prim in stage.TraverseAll():
if prim.GetMetadata("hide_in_stage_window"):
continue
all_prims.append(prim.GetPath().pathString)
if prim.GetTypeName() == "Material":
material_prims.append(prim.GetPath().pathString)
if prim.GetTypeName() == "Cube":
cube_prims.append(prim.GetPath().pathString)
if prim.GetTypeName() == "Sphere":
sphere_prims.append(prim.GetPath().pathString)
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
# SelectAllCommand Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectAll")
self.assertListEqual(selection.get_selected_prim_paths(), all_root_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
# SelectAllCommand "Material" Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectAll", type="Material")
self.assertListEqual(selection.get_selected_prim_paths(), material_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
# SelectAllCommand "Cube" Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectAll", type="Cube")
self.assertListEqual(selection.get_selected_prim_paths(), cube_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
# SelectAllCommand "Sphere" Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectAll", type="Sphere")
self.assertListEqual(selection.get_selected_prim_paths(), sphere_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
# SelectSimilarCommand: "Sphere" and "Cube"
prim_paths = [sphere_prims[0], cube_prims[0]]
selection.set_selected_prim_paths(prim_paths, True)
omni.kit.commands.execute("SelectSimilar")
all_prims = sphere_prims.copy()
all_prims.extend(cube_prims)
self.assertListEqual(selection.get_selected_prim_paths(), all_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), prim_paths)
async def test_command_select_none(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = self.get_all_prims()
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
inverse_prims = [item for item in all_prims if item not in subset_prims]
# SelectNoneCommand Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectNone")
self.assertListEqual(selection.get_selected_prim_paths(), [])
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
async def test_command_select_invert(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = []
for prim in stage.TraverseAll():
if not prim.GetMetadata("hide_in_stage_window") and stage.HasDefaultPrim() and not stage.GetDefaultPrim() == prim:
all_prims.append(prim.GetPath().pathString)
# if selected path as children and none of the children are selected, then all the children are selected..
subset_count = int(len(all_prims) >> 1)
subset_prims = []
for prim_path in sorted(random.sample(all_prims, subset_count), reverse=True):
prim = stage.GetPrimAtPath(prim_path)
if prim:
subset_prims.append(prim_path)
child_list = []
self.get_all_children(prim, child_list)
if not set(subset_prims).intersection(set(child_list)):
subset_prims += child_list
# SelectInvertCommand Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectInvert")
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
async def test_command_hide_unselected(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = self.get_all_prims()
# if selected path as children and none of the children are selected, then all the children are selected..
subset_prims = set()
for prim_path in sorted(random.sample(all_prims, 3), reverse=True):
# we need to remove "/World" from the sampled result since it is the parent of all prims
if prim_path == '/World':
continue
prim = stage.GetPrimAtPath(prim_path)
if prim:
subset_prims.add(prim_path)
child_list = []
self.get_all_children(prim, child_list)
subset_prims.update(child_list)
# HideUnselectedCommand Execute and undo
visible_prims = set()
for prim_path in subset_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim:
visible_prims.add(prim.GetPath().pathString)
visible_prims.update(self.get_parent_prims(prim))
invisible_prims = set([item for item in all_prims if item not in visible_prims])
selection.set_selected_prim_paths(list(subset_prims), True)
omni.kit.commands.execute("HideUnselected")
self.check_visibillity(visible_prims, invisible_prims)
omni.kit.undo.undo()
self.check_visibillity(all_prims, [])
async def test_command_select_parent(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = self.get_all_prims()
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
parent_prims = set()
for prim_path in subset_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim and prim.GetParent() is not None:
parent_prims.add(prim.GetParent().GetPath().pathString)
parent_prims = list(parent_prims)
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectParent")
self.assertListEqual(selection.get_selected_prim_paths(), sorted(parent_prims))
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
async def test_command_select_kind(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = []
group_prims = []
for prim in stage.TraverseAll():
if Kind.Registry.IsA(Usd.ModelAPI(prim).GetKind(), "group"):
group_prims.append(prim.GetPath().pathString)
if not prim.GetMetadata("hide_in_stage_window"):
all_prims.append(prim.GetPath().pathString)
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectKind", kind="group")
self.assertListEqual(selection.get_selected_prim_paths(), sorted(group_prims))
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
async def test_command_select_hierarchy(self):
context = omni.usd.get_context()
selection = context.get_selection()
selection.set_selected_prim_paths(['/World'], True)
omni.kit.commands.execute("SelectHierarchy")
self.assertListEqual(selection.get_selected_prim_paths(), sorted(self.get_all_prims()))
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
async def test_command_select_list(self):
context = omni.usd.get_context()
selection = context.get_selection()
all_prims = self.get_all_prims()
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
selection.set_selected_prim_paths(['/World'], True)
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
# with no kwargs it should clear the selection
omni.kit.commands.execute("SelectList")
self.assertListEqual(selection.get_selected_prim_paths(), [])
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
# with kwarg it should swap the selection to the new list
omni.kit.commands.execute("SelectList", selection=subset_prims)
self.assertListEqual(sorted(selection.get_selected_prim_paths()), sorted(subset_prims))
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
async def test_command_select_leaf(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
selection.set_selected_prim_paths(['/World'], True)
omni.kit.commands.execute("SelectLeaf")
selected = selection.get_selected_prim_paths()
for leaf in selected:
self.assertFalse(stage.GetPrimAtPath(leaf).GetChildren())
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
| 12,583 | Python | 41.948805 | 126 | 0.629739 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/simple_tool_button.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.ui
import weakref
from .hotkey import Hotkey
from .widget_group import WidgetGroup
class SimpleToolButton(WidgetGroup):
"""
A helper class to create simple WidgetGroup that contains only one ToolButton.
Args:
name: Name of the ToolButton.
tooltip: Tooltip of the ToolButton.
icon_path: The icon to be used when button is not checked.
icon_checked_path: The icon to be used when button is checked.
hotkey: HotKey to toggle the button (optional).
toggled_fn: Callback function when button is toggled. Signature: on_toggled(checked) (optional).
model: Model for the ToolButton (optional).
additional_style: Additional styling to apply to the ToolButton (optional).
"""
def __init__(
self,
name,
tooltip,
icon_path,
icon_checked_path,
hotkey=None,
toggled_fn=None,
model=None,
additional_style=None,
):
super().__init__()
self._name = name
self._tooltip = tooltip
self._icon_path = icon_path
self._icon_checked_path = icon_checked_path
self._hotkey = hotkey
self._toggled_fn = toggled_fn
self._model = model
self._additional_style = additional_style
self._hotkey = None
if hotkey:
def on_hotkey_changed(hotkey: str):
self._tool_button.tooltip = f"{self._tooltip} ({hotkey})"
self._select_hotkey = Hotkey(
f"{name}::hotkey",
hotkey,
lambda: self._on_hotkey(),
lambda: self._tool_button.enabled and self._is_in_context(),
on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey),
)
def clean(self):
super().clean()
self._value_sub = None
self._tool_button = None
if self._select_hotkey:
self._select_hotkey.clean()
self._select_hotkey = None
def get_style(self):
style = {
f"Button.Image::{self._name}": {"image_url": self._icon_path},
f"Button.Image::{self._name}:checked": {"image_url": self._icon_checked_path},
}
if self._additional_style:
style.update(self._additional_style)
return style
def create(self, default_size):
def on_value_changed(model, widget):
widget = widget()
if widget is not None:
if model.get_value_as_bool():
self._acquire_toolbar_context()
else:
self._release_toolbar_context()
widget._toggled_fn(model.get_value_as_bool())
self._tool_button = omni.ui.ToolButton(
name=self._name, model=self._model, tooltip=self._tooltip, width=default_size, height=default_size
)
if self._toggled_fn is not None:
self._value_sub = self._tool_button.model.subscribe_value_changed_fn(
lambda model, widget=weakref.ref(self): on_value_changed(model, widget)
)
# return a dictionary of name -> widget if you want to expose it to other widget_group
return {self._name: self._tool_button}
def get_tool_button(self):
return self._tool_button
def _on_hotkey(self):
self._tool_button.model.set_value(not self._tool_button.model.get_value_as_bool())
| 3,858 | Python | 34.081818 | 110 | 0.604458 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/widget_group.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
from abc import abstractmethod
import omni.kit.widget.toolbar
import omni.kit.app
import omni.ui as ui
from .context_menu import ContextMenuEvent
class WidgetGroup:
"""
Base class to create a group of widgets on Toolbar
"""
def __init__(self):
self._context = ""
self._context_token = None
self._show_menu_task = None
self._toolbar_ext_path = (
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar")
)
@abstractmethod
def clean(self):
"""
Clean up function to be called before destorying the object.
"""
if self._context_token:
self._release_toolbar_context()
self._context_token = None
self._context = ""
if self._show_menu_task: # pragma: no cover
self._show_menu_task.cancel()
self._show_menu_task = None
@abstractmethod
def get_style(self) -> dict:
"""
Gets the style of all widgets defined in this Widgets group.
"""
pass # pragma: no cover (Abstract)
@abstractmethod
def create(self, default_size):
"""
Main function to creates widget.
If you want to export widgets and allow external code to fetch and manipulate them, return a Dict[str, Widget] mapping from name to instance at the end of the function.
"""
pass # pragma: no cover (Abstract)
def on_toolbar_context_changed(self, context: str):
"""
Called when toolbar's effective context has changed.
Args:
context: new toolbar context.
"""
pass
def on_added(self, context):
"""
Called when widget is added to toolbar when calling Toolbar.add_widget
Args:
context: the context used to add widget when calling Toolbar.add_widget.
"""
self._context = context
def on_removed(self):
"""
Called when widget is removed from toolbar when calling Toolbar.remove_widget
"""
pass
def _acquire_toolbar_context(self):
"""
Request toolbar to switch to current widget's context.
"""
self._context_token = omni.kit.widget.toolbar.get_instance().acquire_toolbar_context(self._context)
def _release_toolbar_context(self):
"""
Release the ownership of toolbar context and reset to default. If the ownership was preemptively taken by other owner, release does nothing.
"""
omni.kit.widget.toolbar.get_instance().release_toolbar_context(self._context_token)
def _is_in_context(self):
"""
Checks if the Toolbar is in default context or owned by current widget's context.
Override this function if you want to customize the behavior.
Returns:
True if toolbar is either in default context or owned by current widget.
False otherwise.
"""
toolbar_context = omni.kit.widget.toolbar.get_instance().get_context()
return toolbar_context == omni.kit.widget.toolbar.Toolbar.DEFAULT_CONTEXT or self._context == toolbar_context
def _invoke_context_menu(self, button_id: str, min_menu_entries: int = 1):
"""
Function to invoke context menu.
Args:
button_id: button_id of the context menu to be invoked.
min_menu_entries: minimal number of menu entries required for menu to be visible (default 1).
"""
event = ContextMenuEvent()
event.payload["widget_name"] = button_id
event.payload["min_menu_entries"] = min_menu_entries
omni.kit.widget.toolbar.get_instance().context_menu.on_mouse_event(event)
def _on_mouse_pressed(self, button, button_id: str, min_menu_entries: int = 2):
"""
Function to handle flyout menu. Either with LMB long press or RMB click.
Args:
button_id: button_id of the context menu to be invoked.
min_menu_entries: minimal number of menu entries required for menu to be visible (default 1).
"""
self._acquire_toolbar_context()
if button == 1: # Right click, show immediately
self._invoke_context_menu(button_id, min_menu_entries)
elif button == 0: # Schedule a task if hold LMB long enough
self._show_menu_task = asyncio.ensure_future(self._schedule_show_menu(button_id))
def _on_mouse_released(self, button):
if button == 0:
if self._show_menu_task:
self._show_menu_task.cancel()
async def _schedule_show_menu(self, button_id: str, min_menu_entries: int = 2):
await asyncio.sleep(0.3)
self._invoke_context_menu(button_id, min_menu_entries)
self._show_menu_task = None
def _build_flyout_indicator(
self, width, height, index: str, extension_id: str = "omni.kit.widget.toolbar", padding=7, min_menu_count=2
):
import carb
import omni.kit.context_menu
indicator_size = 3
with ui.Placer(offset_x=width - indicator_size - padding, offset_y=height - indicator_size - padding):
indicator = ui.Image(
f"{self._toolbar_ext_path}/data/icon/flyout_indicator_dark.svg",
width=indicator_size,
height=indicator_size,
)
def on_menu_changed(evt: carb.events.IEvent):
try:
menu_list = omni.kit.context_menu.get_menu_dict(index, extension_id)
# because we moved separated the widget from the window extension, we need to still grab the menu from
# the window extension
menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(index, "omni.kit.window.toolbar")
if menu_list_backward_compatible and evt.payload.get("extension_id", None) == "omni.kit.window.toolbar": # pragma: no cover
omni.kit.app.log_deprecation(
'Adding menu using "add_menu(menu, index, "omni.kit.window.toolbar")" is deprecated. '
'Please use "add_menu(menu, index, "omni.kit.widget.toolbar")"'
)
# TODO check the actual menu entry visibility with show_fn
indicator.visible = len(menu_list + menu_list_backward_compatible) >= min_menu_count
except AttributeError as exc: # pragma: no cover
carb.log_warn(f"on_menu_changed error {exc}")
# Check initial state
on_menu_changed(None)
event_stream = omni.kit.context_menu.get_menu_event_stream()
return event_stream.create_subscription_to_pop(on_menu_changed)
| 7,173 | Python | 38.202186 | 176 | 0.625401 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/commands.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.timeline
import omni.kit.commands
class ToolbarPlayButtonClickedCommand(omni.kit.commands.Command):
"""
On clicked toolbar play button **Command**.
"""
def do(self):
omni.timeline.get_timeline_interface().play()
class ToolbarPauseButtonClickedCommand(omni.kit.commands.Command):
"""
On clicked toolbar pause button **Command**.
"""
def do(self):
omni.timeline.get_timeline_interface().pause()
class ToolbarStopButtonClickedCommand(omni.kit.commands.Command):
"""
On clicked toolbar stop button **Command**.
"""
def do(self):
omni.timeline.get_timeline_interface().stop()
class ToolbarPlayFilterCheckedCommand(omni.kit.commands.Command):
"""
Change settings depending on the status of play filter checkboxes **Command**.
Args:
path: Path to the setting to change.
enabled: New value to change to.
"""
def __init__(self, setting_path, enabled):
self._setting_path = setting_path
self._enabled = enabled
def do(self):
omni.kit.commands.execute("ChangeSetting", path=self._setting_path, value=self._enabled)
def undo(self):
pass # pragma: no cover
class ToolbarPlayFilterSelectAllCommand(omni.kit.commands.Command): # pragma: no cover
"""
Sets all play filter settings to True **Command**.
Args:
settings: Paths to the settings.
"""
def __init__(self, settings):
self._settings = settings
def do(self):
for setting in self._settings:
omni.kit.commands.execute("ChangeSetting", path=setting, value=True)
def undo(self):
pass
omni.kit.commands.register_all_commands_in_module(__name__)
| 2,165 | Python | 26.075 | 96 | 0.684988 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/extension.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 carb
import omni.ext
from functools import lru_cache
from pathlib import Path
from .toolbar import Toolbar
_toolbar_instance = None
@lru_cache()
def get_data_path() -> Path:
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path_by_module("omni.kit.widget.toolbar")
return Path(extension_path).joinpath("data")
def get_instance():
return _toolbar_instance
class WidgetToolBarExtension(omni.ext.IExt):
"""omni.kit.widget.toolbar ext"""
def on_startup(self, ext_id):
global _toolbar_instance
carb.log_info("[omni.kit.widget.toolbar] Startup")
_toolbar_instance = Toolbar()
def on_shutdown(self):
carb.log_info("[omni.kit.widget.toolbar] Shutdown")
global _toolbar_instance
if _toolbar_instance:
_toolbar_instance.destroy()
_toolbar_instance = None
| 1,338 | Python | 29.431818 | 84 | 0.720478 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/__init__.py | from .extension import *
from .toolbar import *
from omni.kit.widget.toolbar.simple_tool_button import * # backward compatible
from .widget_group import * # backward compatible
| 179 | Python | 34.999993 | 79 | 0.776536 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/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 carb
import omni.kit.context_menu
from omni import ui
class ContextMenuEvent:
"""The object comatible with ContextMenu"""
def __init__(self):
self.type = 0
self.payload = {}
class ContextMenu:
def on_mouse_event(self, event):
# check its expected event
if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): # pragma: no cover
return
# get context menu core functionality & check its enabled
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None: # pragma: no cover
carb.log_error("context_menu is disabled!")
return
# setup objects, this is passed to all functions
objects = {}
objects.update(event.payload)
widget_name = objects.get("widget_name", None)
menu_list = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.widget.toolbar")
# because we moved separated the widget from the window extension, we need to still grab the menu from
# the window extension
menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.window.toolbar")
for menu_list_backward in menu_list_backward_compatible: # pragma: no cover
if menu_list_backward not in menu_list:
menu_list.append(menu_list_backward)
# For some tool buttons, the context menu only shows if additional (>1) menu entries are added.
min_menu_entries = event.payload.get("min_menu_entries", 0)
# show menu
context_menu.show_context_menu("toolbar", objects, menu_list, min_menu_entries, delegate=ui.MenuDelegate())
| 2,117 | Python | 38.962263 | 115 | 0.683987 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/toolbar.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 carb
import carb.settings
import omni.kit.app
import omni.ui as ui
import omni.usd
from omni.ui import color as cl
from typing import Callable
from .builtin_tools.builtin_tools import BuiltinTools
from .commands import *
from .context_menu import *
from .widget_group import WidgetGroup # backward compatible
import typing
if typing.TYPE_CHECKING: # pragma: no cover
import weakref
GRAB_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/Grab/enabled"
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class Toolbar:
WINDOW_NAME = "Main ToolBar"
DEFAULT_CONTEXT = ""
DEFAULT_CONTEXT_TOKEN = 0
DEFAULT_SIZE = 38
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self):
self._settings = carb.settings.get_settings()
self.__root_frame = None
self._toolbar_widget_groups = []
self._toolbar_widgets = {}
self._toolbar_dirty = False
self._axis = ui.ToolBarAxis.X
self._rebuild_task = None
self._grab_stack = None
self._context_menu = ContextMenu()
self._context_token_pool = 1
self._context = Toolbar.DEFAULT_CONTEXT
self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN
self._context_token_owner_count = 0
self.__init_shades()
self._builtin_tools = BuiltinTools(self)
def __init_shades(self):
"""Style colors"""
cl.toolbar_button_background = cl.shade(0x0)
cl.toolbar_button_background_checked = cl.shade(0xFF1F2123)
cl.toolbar_button_background_pressed = cl.shade(0xFF4B4B4B)
cl.toolbar_button_background_hovered = cl.shade(0xFF383838)
@property
def context_menu(self):
return self._context_menu
def destroy(self):
if self._rebuild_task is not None: # pragma: no cover
self._rebuild_task.cancel()
self._toolbar_widgets = {}
if self._builtin_tools:
self._builtin_tools.destroy()
self._builtin_tools = None
self._toolbar_widget_groups = []
def add_widget(self, widget_group: "WidgetGroup", priority: int, context: str = ""):
self._toolbar_widget_groups.append((priority, widget_group))
widget_group.on_added(context)
self._set_toolbar_dirty()
def remove_widget(self, widget_group: "WidgetGroup"):
for widget in self._toolbar_widget_groups:
if widget[1] == widget_group:
self._toolbar_widget_groups.remove(widget)
widget_group.on_removed()
self._set_toolbar_dirty()
break
def get_widget(self, name: str):
return self._toolbar_widgets.get(name, None)
def acquire_toolbar_context(self, context: str):
"""
Request toolbar to switch to given context.
It takes the context preemptively even if previous context owner has not release the context.
Args:
context (str): Context to switch to.
Returns:
A token to be used to release_toolbar_context
"""
if self._context == context:
self._context_token_owner_count += 1
return self._context_token
# preemptively take current context, regardless of previous owner/count
self._context = context
if context == Toolbar.DEFAULT_CONTEXT:
self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN
else:
self._context_token_pool += 1
self._context_token = self._context_token_pool
self._context_token_owner_count = 1
for widget in self._toolbar_widget_groups:
widget[1].on_toolbar_context_changed(context)
return self._context_token
def release_toolbar_context(self, token: int):
"""
Request toolbar to release context associated with token.
If token is expired (already released or context ownership taken by others), this function does nothing.
Args:
token (int): Context token to release.
"""
if token == self._context_token:
self._context_token_owner_count -= 1
else:
carb.log_info("Releasing expired context token, ignoring")
return
if self._context_token_owner_count <= 0:
self._context = Toolbar.DEFAULT_CONTEXT
self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN
self._context_token_owner_count = 0
for widget in self._toolbar_widget_groups:
widget[1].on_toolbar_context_changed(self._context)
def get_context(self):
return self._context
def _set_toolbar_dirty(self):
self._toolbar_dirty = True
if self._rebuild_task is None:
self._rebuild_task = asyncio.ensure_future(self._delayed_rebuild())
def set_axis(self, axis):
self._axis = axis
# delay rebuild so widgets added within one frame are rebuilt together
@omni.usd.handle_exception
async def _delayed_rebuild(self):
await omni.kit.app.get_app().next_update_async()
if self._toolbar_dirty:
self.rebuild_toolbar()
self._toolbar_dirty = False
self._rebuild_task = None
def rebuild_toolbar(self, root_frame=None):
if root_frame:
self.__root_frame = root_frame
if not self.__root_frame:
carb.log_warn("No root frame specified. Please specify a root frame for this widget")
return
axis = self._axis
self._toolbar_widgets = {}
self._toolbar_widget_groups.sort(key=lambda x: x[0]) # sort by priority
with self.__root_frame:
stack = None
style = {
"Button": {"background_color": cl.toolbar_button_background, "border_radius": 4, "margin": 2, "padding": 3},
"Button:checked": {"background_color": cl.toolbar_button_background_checked},
"Button:pressed": {"background_color": cl.toolbar_button_background_pressed},
"Button:hovered": {"background_color": cl.toolbar_button_background_hovered},
"Button.Image::disabled": {"color": 0x608A8777},
"Line::grab": {"color": 0xFF2E2E2E, "border_width": 2, "margin": 2},
"Line::separator": {"color": 0xFF555555},
"Tooltip": {
"background_color": 0xFFC7F5FC,
"color": 0xFF4B493B,
"border_width": 1,
"margin_width": 2,
"margin_height": 1,
"padding": 1,
},
}
for widget in self._toolbar_widget_groups:
style.update(widget[1].get_style())
default_size = self.DEFAULT_SIZE
if axis == ui.ToolBarAxis.X:
stack = ui.HStack(style=style, height=default_size, width=ui.Percent(100))
else:
stack = ui.VStack(style=style, height=ui.Percent(100), width=default_size)
with stack:
if self._settings.get(GRAB_ENABLED_SETTING_PATH):
self._create_grab(axis)
ui.Spacer(width=3, height=3)
last_priority = None
for widget in self._toolbar_widget_groups:
this_priority = widget[0]
if last_priority is not None and this_priority - last_priority >= 10:
self._create_separator(axis)
public_widgets = widget[1].create(default_size=default_size)
if public_widgets is not None:
self._toolbar_widgets.update(public_widgets)
last_priority = this_priority
def _create_separator(self, axis):
if axis == ui.ToolBarAxis.X:
ui.Line(width=1, name="separator", alignment=ui.Alignment.LEFT)
else:
ui.Line(height=1, name="separator", alignment=ui.Alignment.TOP)
def subscribe_grab_mouse_pressed(self, function: Callable[[int, "weakref.ref"], None]):
if self._grab_stack:
self._grab_stack.set_mouse_pressed_fn(function)
def _create_grab(self, axis):
grab_area_size = 20
if axis == ui.ToolBarAxis.X:
self._grab_stack = ui.HStack(width=grab_area_size)
else:
self._grab_stack = ui.VStack(height=grab_area_size)
with self._grab_stack:
if axis == ui.ToolBarAxis.X:
ui.Spacer(width=5)
ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT)
ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT)
ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT)
ui.Spacer(width=3)
else:
ui.Spacer(height=5)
ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP)
ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP)
ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP)
ui.Spacer(height=3)
def add_custom_select_type(self, entry_name: str, selection_types: list):
self._builtin_tools.add_custom_select_type(entry_name, selection_types)
def remove_custom_select(self, entry_name):
self._builtin_tools.remove_custom_select(entry_name)
| 10,132 | Python | 37.973077 | 124 | 0.606001 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/hotkey.py | # Copyright (c) 2020-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 __future__ import annotations
from typing import Callable
import carb.events
import carb.input
import omni.appwindow
import omni.kit.actions.core
import omni.kit.app
class Hotkey:
def __init__(
self,
action_name: str,
hotkey: carb.input.KeyboardInput,
on_action_fn: Callable[[], None],
hotkey_enabled_fn: Callable[[], None],
modifiers: int = 0,
on_hotkey_changed_fn: Callable[[str], None] = None,
):
self._action_registry = omni.kit.actions.core.get_action_registry()
self._settings = carb.settings.get_settings()
self._action_name = action_name
self._hotkey = hotkey
self._modifiers = modifiers
self._on_hotkey_changed_fn = on_hotkey_changed_fn
self._registered_hotkey = None
self._manager = omni.kit.app.get_app().get_extension_manager()
self._extension_name = omni.ext.get_extension_name(self._manager.get_extension_id_by_module(__name__))
def action_trigger():
if not hotkey_enabled_fn():
return
if on_action_fn:
on_action_fn()
# Register a test action that invokes a Python function.
self._action = self._action_registry.register_action(
self._extension_name,
action_name,
lambda *_: action_trigger(),
display_name=action_name,
tag="Toolbar",
)
self._hooks = self._manager.subscribe_to_extension_enable(
lambda _: self._register_hotkey(),
lambda _: self._unregister_hotkey(),
ext_name="omni.kit.hotkeys.core",
hook_name=f"toolbar hotkey {action_name} listener",
)
def clean(self):
self._unregister_hotkey()
self._action_registry.deregister_action(self._action)
self._hooks = None
self._on_hotkey_changed_fn = None
def get_as_string(self, default:str):
if self._registered_hotkey:
return self._registered_hotkey.key_text
return default
def _on_hotkey_changed(self, event: carb.events.IEvent):
from omni.kit.hotkeys.core import KeyCombination
if (
event.payload["hotkey_ext_id"] == self._extension_name
and event.payload["action_ext_id"] == self._extension_name
and event.payload["action_id"] == self._action_name
):
new_key = event.payload["key"]
# refresh _registered_hotkey with newly registered key?
hotkey_combo = KeyCombination(new_key)
self._registered_hotkey = self._hotkey_registry.get_hotkey(self._extension_name, hotkey_combo)
if self._on_hotkey_changed_fn:
self._on_hotkey_changed_fn(new_key)
def _register_hotkey(self):
try:
from omni.kit.hotkeys.core import HOTKEY_CHANGED_EVENT, KeyCombination, get_hotkey_registry
self._hotkey_registry = get_hotkey_registry()
hotkey_combo = KeyCombination(self._hotkey, self._modifiers)
self._registered_hotkey = self._hotkey_registry.register_hotkey(
self._extension_name, hotkey_combo, self._extension_name, self._action_name
)
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._change_event_sub = event_stream.create_subscription_to_pop_by_type(
HOTKEY_CHANGED_EVENT, self._on_hotkey_changed
)
except ImportError: # pragma: no cover
pass
def _unregister_hotkey(self):
if not self._registered_hotkey or not self._hotkey_registry:
return
try:
self._hotkey_registry.deregister_hotkey(self._registered_hotkey)
self._registered_hotkey = None
self._change_event_sub = None
except Exception: # pragma: no cover
pass
| 4,357 | Python | 34.430894 | 110 | 0.620151 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/play_button_group.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 carb.dictionary
import carb.settings
import omni.timeline
import omni.ui as ui
from carb.input import KeyboardInput as Key
from omni.kit.commands import execute
from omni.kit.widget.toolbar.hotkey import Hotkey
from omni.kit.widget.toolbar.widget_group import WidgetGroup
from .models.timeline_model import TimelinePlayPauseModel
PLAY_TOOL_NAME = "Play"
PAUSE_TOOL_NAME = "Pause"
class PlayButtonGroup(WidgetGroup):
PLAY_ANIMATIONS_SETTING = "/app/player/playAnimations"
PLAY_AUDIO_SETTING = "/app/player/audio/enabled"
PLAY_SIMULATIONS_SETTING = "/app/player/playSimulations"
PLAY_COMPUTEGRAPH_SETTING = "/app/player/playComputegraph"
all_settings_paths = [
PLAY_ANIMATIONS_SETTING,
PLAY_AUDIO_SETTING,
PLAY_SIMULATIONS_SETTING,
PLAY_COMPUTEGRAPH_SETTING,
]
def __init__(self):
super().__init__()
self._play_button = None
self._play_hotkey = None
self._stop_button = None
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._timeline_play_pause_model = TimelinePlayPauseModel()
self._timeline = omni.timeline.get_timeline_interface()
self._settings.set_default_bool(self.PLAY_ANIMATIONS_SETTING, True)
self._settings.set_default_bool(self.PLAY_AUDIO_SETTING, True)
self._settings.set_default_bool(self.PLAY_SIMULATIONS_SETTING, True)
self._settings.set_default_bool(self.PLAY_COMPUTEGRAPH_SETTING, True)
stream = self._timeline.get_timeline_event_stream()
self._sub = stream.create_subscription_to_pop(self._on_timeline_event)
self._register_context_menu()
self._show_menu_task = None
self._visible = True
def clean(self):
super().clean()
self._sub = None
if self._timeline_play_pause_model:
self._timeline_play_pause_model.clean()
self._timeline_play_pause_model = None
self._play_button = None
self._stop_button = None
self._animations_menu = None
self._audio_menu = None
self._simulations_menu = None
self._compute_graph_menu = None
self._play_filter_menu = None
self._filter_menu = None
self._sep_menu = None
self._sep_menu2 = None
self._select_all_menu = None
if self._show_menu_task: # pragma: no cover
self._show_menu_task.cancel()
self._show_menu_task = None
if self._play_hotkey:
self._play_hotkey.clean()
self._play_hotkey = None
self._visible = True
def get_style(self):
style = {
"Button.Image::play": {"image_url": "${glyphs}/toolbar_play.svg"},
"Button.Image::play:checked": {"image_url": "${glyphs}/toolbar_pause.svg"},
"Button.Image::stop": {"image_url": "${glyphs}/toolbar_stop.svg"},
}
return style
def create(self, default_size):
# Build Play button
self._play_button = ui.ToolButton(
model=self._timeline_play_pause_model,
name="play",
tooltip=f"{PLAY_TOOL_NAME} ('Space')",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "play"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
checked=self._timeline_play_pause_model.get_value_as_bool(),
)
def on_play_hotkey_changed(hotkey: str):
if self._play_button:
self._play_button.tooltip = f"{PLAY_TOOL_NAME} ({hotkey})"
# Assign Play button Hotkey
self._play_hotkey = Hotkey(
"toolbar::play",
Key.SPACE,
lambda: self._timeline_play_pause_model.set_value(not self._timeline_play_pause_model.get_value_as_bool()),
lambda: self._play_button is not None and self._play_button.enabled and self._is_in_context(),
on_hotkey_changed_fn=lambda hotkey: on_play_hotkey_changed(hotkey),
)
self._visible = True
def on_stop_clicked(*_):
self._acquire_toolbar_context()
execute("ToolbarStopButtonClicked")
self._stop_button = ui.Button(
name="stop",
tooltip="Stop",
width=default_size,
height=default_size,
visible=False,
clicked_fn=on_stop_clicked,
)
return {"play": self._play_button, "stop": self._stop_button}
def _on_setting_changed(self, item, event_type, menu_item): # pragma: no cover
menu_item.checked = self._dict.get(item)
def _on_timeline_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.PLAY):
if self._play_button:
self._play_button.set_tooltip(f"{PAUSE_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})")
if self._stop_button:
self._stop_button.visible = self._visible
if e.type == int(omni.timeline.TimelineEventType.PAUSE):
if self._play_button:
self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})")
if e.type == int(omni.timeline.TimelineEventType.STOP):
if self._stop_button:
self._stop_button.visible = False
if self._play_button:
self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})")
if hasattr(omni.timeline.TimelineEventType, 'DIRECTOR_CHANGED') and\
e.type == int(omni.timeline.TimelineEventType.DIRECTOR_CHANGED): # pragma: no cover
self._visible = not e.payload['hasDirector']
if self._stop_button:
self._stop_button.visible = self._visible
if self._play_button:
self._play_button.visible = self._visible
def _on_filter_changed(self, filter_setting, enabled): # pragma: no cover
execute("ToolbarPlayFilterChecked", setting_path=filter_setting, enabled=enabled)
def _select_all(self): # pragma: no cover
execute("ToolbarPlayFilterSelectAll", settings=self.all_settings_paths)
def _register_context_menu(self):
context_menu = omni.kit.context_menu.get_instance()
def is_button(objects: dict, button_name: str): # pragma: no cover
return objects.get("widget_name", None) == button_name
def create_menu_entry(name, setting_path):
menu = {
"name": name,
"show_fn": [lambda object: is_button(object, "play")],
"onclick_fn": lambda object: self._on_filter_changed(
setting_path, not self._settings.get(setting_path)
),
"checked_fn": lambda object: self._settings.get(setting_path),
}
return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
def create_seperator(name=""):
menu = {
"name": name,
"show_fn": [lambda object: is_button(object, "play")],
}
return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
if context_menu:
menu = {
"name": "Filter",
"show_fn": [lambda object: is_button(object, "play")],
"enabled_fn": lambda object: False,
}
self._filter_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
self._sep_menu = create_seperator("sep/")
self._animations_menu = create_menu_entry("Animation", self.PLAY_ANIMATIONS_SETTING)
self._audio_menu = create_menu_entry("Audio", self.PLAY_AUDIO_SETTING)
self._simulations_menu = create_menu_entry("Simulations", self.PLAY_SIMULATIONS_SETTING)
self._compute_graph_menu = create_menu_entry("OmniGraph", self.PLAY_COMPUTEGRAPH_SETTING)
self._sep_menu2 = create_seperator("sep2/")
menu = {
"name": "Select All",
"show_fn": [lambda object: is_button(object, "play")],
"onclick_fn": lambda object: self._select_all(),
}
self._select_all_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
| 8,842 | Python | 40.32243 | 119 | 0.604275 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/builtin_tools.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 carb.dictionary
import carb.settings
from .select_button_group import SelectButtonGroup
from .snap_button_group import LegacySnapButtonGroup
from .transform_button_group import TransformButtonGroup
from .play_button_group import PlayButtonGroup
import typing
if typing.TYPE_CHECKING: # pragma: no cover
from ..toolbar import Toolbar
SELECT_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/enabled"
TRANSFORM_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/TransformButton/enabled"
PLAY_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/PlayButton/enabled"
LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW = "/exts/omni.kit.window.toolbar/legacySnapButton/enabled"
LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET = "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled"
class BuiltinTools:
def __init__(self, toolbar: "Toolbar"):
self._dict = carb.dictionary.get_dictionary()
self._settings = carb.settings.get_settings()
self._sub_window = self._settings.subscribe_to_node_change_events(
LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, self._on_legacy_snap_setting_changed_window
)
self._toolbar = toolbar
self._select_button_group = None
if self._settings.get(SELECT_BUTTON_ENABLED_SETTING_PATH):
self._select_button_group = SelectButtonGroup()
toolbar.add_widget(self._select_button_group, 0)
self._transform_button_group = None
if self._settings.get(TRANSFORM_BUTTON_ENABLED_SETTING_PATH):
self._transform_button_group = TransformButtonGroup()
toolbar.add_widget(self._transform_button_group, 1)
self._snap_button_group = None
if self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET):
self._add_snap_button()
self._play_button_group = None
if self._settings.get(PLAY_BUTTON_ENABLED_SETTING_PATH):
self._play_button_group = PlayButtonGroup()
toolbar.add_widget(self._play_button_group, 21)
self._sub_widget = self._settings.subscribe_to_node_change_events(
LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, self._on_legacy_snap_setting_changed
)
def destroy(self):
if self._select_button_group:
self._toolbar.remove_widget(self._select_button_group)
self._select_button_group.clean()
self._select_button_group = None
if self._transform_button_group:
self._toolbar.remove_widget(self._transform_button_group)
self._transform_button_group.clean()
self._transform_button_group = None
if self._snap_button_group:
self._remove_snap_button()
if self._play_button_group:
self._toolbar.remove_widget(self._play_button_group)
self._play_button_group.clean()
self._play_button_group = None
if self._sub_window:
self._settings.unsubscribe_to_change_events(self._sub_window)
self._sub_window = None
if self._sub_widget:
self._settings.unsubscribe_to_change_events(self._sub_widget)
self._sub_widget = None
def __del__(self):
self.destroy()
def _add_snap_button(self):
self._snap_button_group = LegacySnapButtonGroup()
self._toolbar.add_widget(self._snap_button_group, 11)
def _remove_snap_button(self):
self._toolbar.remove_widget(self._snap_button_group)
self._snap_button_group.clean()
self._snap_button_group = None
def _on_legacy_snap_setting_changed_window(self, *args, **kwargs):
"""
If the old setting is set, we forward it into the new settings.
"""
enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW)
if enabled_legacy_snap is not None:
carb.log_warn(
'Deprecated, please use "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled" setting'
)
self._settings.set(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, enabled_legacy_snap)
def _on_legacy_snap_setting_changed(self, *args, **kwargs):
enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET)
if self._snap_button_group is None and enabled_legacy_snap:
self._add_snap_button()
elif self._snap_button_group is not None and not enabled_legacy_snap:
self._remove_snap_button()
def add_custom_select_type(self, entry_name: str, selection_types: list):
self._select_button_group.add_custom_select_type(entry_name, selection_types)
def remove_custom_select(self, entry_name):
self._select_button_group.remove_custom_select(entry_name)
| 5,263 | Python | 41.796748 | 105 | 0.67984 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/transform_button_group.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 carb.input
import carb.dictionary
import carb.settings
import omni.kit.context_menu
import omni.ui as ui
from carb.input import KeyboardInput as Key
from omni.kit.widget.toolbar.hotkey import Hotkey
from omni.kit.widget.toolbar.widget_group import WidgetGroup
from .models.transform_mode_model import LocalGlobalTransformModeModel, TransformModeModel
MOVE_TOOL_NAME = "Move"
ROTATE_TOOL_NAME = "Rotate"
SCALE_TOOL_NAME = "Scale"
class TransformButtonGroup(WidgetGroup):
TRANSFORM_MOVE_MODE_SETTING = "/app/transform/moveMode"
TRANSFORM_ROTATE_MODE_SETTING = "/app/transform/rotateMode"
def __init__(self):
super().__init__()
self._input = carb.input.acquire_input_interface()
self._settings = carb.settings.get_settings()
self._settings.set_default_string(TransformModeModel.TRANSFORM_OP_SETTING, TransformModeModel.TRANSFORM_OP_MOVE)
self._settings.set_default_string(
self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
)
self._settings.set_default_string(
self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
)
self._move_op_model = LocalGlobalTransformModeModel(
op=TransformModeModel.TRANSFORM_OP_MOVE, op_space_setting_path=self.TRANSFORM_MOVE_MODE_SETTING
)
self._rotate_op_model = LocalGlobalTransformModeModel(
op=TransformModeModel.TRANSFORM_OP_ROTATE, op_space_setting_path=self.TRANSFORM_ROTATE_MODE_SETTING
)
self._scale_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SCALE)
def on_hotkey_changed(hotkey: str, button, tool_name: str):
button.tooltip = f"{tool_name} ({hotkey})"
self._move_hotkey = Hotkey(
"toolbar::move",
Key.W,
lambda: self._move_op_model.set_value(not self._move_op_model.get_value_as_bool()),
lambda: self._move_button.enabled
and self._is_in_context()
and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON)
== 0, # when RMB is down, it's possible viewport WASD navigation is going on, and don't trigger it if W is pressed
on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._move_button, MOVE_TOOL_NAME),
)
self._rotate_hotkey = Hotkey(
"toolbar::rotate",
Key.E,
lambda: self._rotate_op_model.set_value(not self._rotate_op_model.get_value_as_bool()),
lambda: self._rotate_button.enabled and self._is_in_context()
and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON)
== 0,
on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._rotate_button, ROTATE_TOOL_NAME),
)
self._scale_hotkey = Hotkey(
"toolbar::scale",
Key.R,
lambda: self._scale_op_model.set_value(True),
lambda: self._scale_button.enabled and self._is_in_context(),
on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._scale_button, SCALE_TOOL_NAME),
)
self._register_context_menu()
def get_style(self):
style = {
"Button.Image::move_op_global": {"image_url": "${glyphs}/toolbar_move_global.svg"},
"Button.Image::move_op_local": {"image_url": "${glyphs}/toolbar_move_local.svg"},
"Button.Image::rotate_op_global": {"image_url": "${glyphs}/toolbar_rotate_global.svg"},
"Button.Image::rotate_op_local": {"image_url": "${glyphs}/toolbar_rotate_local.svg"},
"Button.Image::scale_op": {"image_url": "${glyphs}/toolbar_scale.svg"},
}
return style
def create(self, default_size):
self._sub_move, self._move_button = self._create_local_global_button(
self._move_op_model,
f"{MOVE_TOOL_NAME} ({self._move_hotkey.get_as_string('W')})",
"move_op",
self.TRANSFORM_MOVE_MODE_SETTING,
"move_op_global",
"move_op_local",
default_size,
)
self._sub_rotate, self._rotate_button = self._create_local_global_button(
self._rotate_op_model,
f"{ROTATE_TOOL_NAME} ({self._rotate_hotkey.get_as_string('E')})",
"rotate_op",
self.TRANSFORM_ROTATE_MODE_SETTING,
"rotate_op_global",
"rotate_op_local",
default_size,
)
self._scale_button = ui.ToolButton(
model=self._scale_op_model,
name="scale_op",
tooltip=f"{SCALE_TOOL_NAME} ({self._scale_hotkey.get_as_string('R')})",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda *_: self._acquire_toolbar_context(),
)
return {"move_op": self._move_button, "rotate_op": self._rotate_button, "scale_op": self._scale_button}
def clean(self):
super().clean()
self._move_button = None
self._rotate_button = None
self._scale_button = None
self._sub_move = None
self._sub_rotate = None
self._move_op_model.clean()
self._move_op_model = None
self._rotate_op_model.clean()
self._rotate_op_model = None
self._scale_op_model.clean()
self._scale_op_model = None
self._move_hotkey.clean()
self._move_hotkey = None
self._rotate_hotkey.clean()
self._rotate_hotkey = None
self._scale_hotkey.clean()
self._scale_hotkey = None
self._move_global_menu_entry = None
self._move_local_menu_entry = None
self._rotate_global_menu_entry = None
self._rotate_local_menu_entry = None
def _get_op_button_name(self, model, global_name, local_name):
if model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL:
return global_name
else: # pragma: no cover
return local_name
def _create_local_global_button(
self, op_model, tooltip, button_name, op_setting_path, global_name, local_name, default_size
):
op_button = ui.ToolButton(
name=self._get_op_button_name(op_model, global_name, local_name),
model=op_model,
tooltip=tooltip,
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, button_name),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
checked=op_model.get_value_as_bool(),
)
def on_op_button_value_change(model):
op_button.name = self._get_op_button_name(model, global_name, local_name)
return op_model.subscribe_value_changed_fn(on_op_button_value_change), op_button
def _register_context_menu(self):
context_menu = omni.kit.context_menu.get_instance()
def is_button(objects: dict, button_name: str): # pragma: no cover
return objects.get("widget_name", None) == button_name
def on_mode(objects: dict, op_setting_path: str, desired_value): # pragma: no cover
self._settings.set(op_setting_path, desired_value)
def checked(objects: dict, op_setting_path: str, desired_value: str): # pragma: no cover
return self._settings.get(op_setting_path) == desired_value
if context_menu:
menu = {
"name": "Global (W)",
"show_fn": [lambda object: is_button(object, "move_op")],
"onclick_fn": lambda object: on_mode(
object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
),
"checked_fn": lambda object: checked(
object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
),
}
self._move_global_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar")
menu = {
"name": "Local (W)",
"show_fn": [lambda object: is_button(object, "move_op")],
"onclick_fn": lambda object: on_mode(
object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL
),
"checked_fn": lambda object: checked(
object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL
),
}
self._move_local_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar")
menu = {
"name": "Global (E)",
"show_fn": [lambda object: is_button(object, "rotate_op")],
"onclick_fn": lambda object: on_mode(
object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
),
"checked_fn": lambda object: checked(
object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
),
}
self._rotate_global_menu_entry = omni.kit.context_menu.add_menu(
menu, "rotate_op", "omni.kit.widget.toolbar"
)
menu = {
"name": "Local (E)",
"show_fn": [lambda object: is_button(object, "rotate_op")],
"onclick_fn": lambda object: on_mode(
object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL
),
"checked_fn": lambda object: checked(
object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL
),
}
self._rotate_local_menu_entry = omni.kit.context_menu.add_menu(menu, "rotate_op", "omni.kit.widget.toolbar")
| 10,527 | Python | 43.8 | 127 | 0.605016 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/snap_button_group.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 carb.dictionary
import carb.settings
import omni.kit.context_menu
import omni.ui as ui
from omni.kit.widget.toolbar.widget_group import WidgetGroup
from .models.setting_model import BoolSettingModel, FloatSettingModel
class LegacySnapButtonGroup(WidgetGroup):
SNAP_ENABLED_SETTING = "/app/viewport/snapEnabled"
SNAP_MOVE_X_SETTING = "/persistent/app/viewport/stepMove/x"
SNAP_MOVE_Y_SETTING = "/persistent/app/viewport/stepMove/y"
SNAP_MOVE_Z_SETTING = "/persistent/app/viewport/stepMove/z"
SNAP_ROTATE_SETTING = "/persistent/app/viewport/stepRotate"
SNAP_SCALE_SETTING = "/persistent/app/viewport/stepScale"
SNAP_TO_SURFACE_SETTING = "/persistent/app/viewport/snapToSurface"
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(self.SNAP_ENABLED_SETTING, False)
self._settings.set_default_float(self.SNAP_MOVE_X_SETTING, 50.0)
self._settings.set_default_float(self.SNAP_MOVE_Y_SETTING, 50.0)
self._settings.set_default_float(self.SNAP_MOVE_Z_SETTING, 50.0)
self._settings.set_default_float(self.SNAP_ROTATE_SETTING, 1.0)
self._settings.set_default_float(self.SNAP_SCALE_SETTING, 1.0)
self._dict = carb.dictionary.get_dictionary()
self._snap_setting_model = BoolSettingModel(self.SNAP_ENABLED_SETTING, False)
self._snap_move_x_settings_model = FloatSettingModel(self.SNAP_MOVE_X_SETTING)
self._snap_move_y_settings_model = FloatSettingModel(self.SNAP_MOVE_Y_SETTING)
self._snap_move_z_settings_model = FloatSettingModel(self.SNAP_MOVE_Z_SETTING)
self._snap_rotate_settings_model = FloatSettingModel(self.SNAP_ROTATE_SETTING)
self._snap_scale_settings_model = FloatSettingModel(self.SNAP_SCALE_SETTING)
self._create_snap_increment_setting_window()
self._register_context_menu()
self._show_menu_task = None
self._button = None
def clean(self):
super().clean()
self._snap_setting_model.clean()
self._snap_setting_model = None
# workaround delayed toolbar rebuild after group is destroyed and access null model
if self._button:
self._button.model = ui.SimpleBoolModel()
self._button = None
self._snap_move_x_settings_model.clean()
self._snap_move_x_settings_model = None
self._snap_move_y_settings_model.clean()
self._snap_move_y_settings_model = None
self._snap_move_z_settings_model.clean()
self._snap_move_z_settings_model = None
self._snap_rotate_settings_model.clean()
self._snap_rotate_settings_model = None
self._snap_scale_settings_model.clean()
self._snap_scale_settings_model = None
self._snap_increment_setting_window = None
self._snap_setting_menu = None
self._snap_settings = None
self._snap_to_increment_menu = None
self._snap_to_face_menu = None
if self._show_menu_task: # pragma: no cover
self._show_menu_task.cancel()
self._show_menu_task = None
self._snap_settings_menu_entry = None
self._snap_to_increment_menu_entry = None
self._snap_to_face_menu_entry = None
def get_style(self):
style = {"Button.Image::snap": {"image_url": "${glyphs}/toolbar_snap.svg"}}
return style
def create(self, default_size):
self._button = ui.ToolButton(
model=self._snap_setting_model,
name="snap",
tooltip="Snap",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "snap"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
checked=self._snap_setting_model.get_value_as_bool(),
)
return {"snap": self._button}
def _on_snap_on_off(self, model): # pragma: no cover (Never called anywhere it seems)
self._snap_settings.enabled = self._snap_setting_model.get_value_as_bool()
def _on_snap_setting_change(self, item, event_type): # pragma: no cover (Never called anywhere it seems)
snap_to_face = self._dict.get(item)
self._snap_to_increment_menu.checked = not snap_to_face
self._snap_to_face_menu.checked = snap_to_face
self._snap_settings.enabled = not snap_to_face
def _on_snap_setting_menu_clicked(self, snap_to_face): # pragma: no cover
self._settings.set(self.SNAP_TO_SURFACE_SETTING, snap_to_face)
def _on_show_snap_increment_setting_window(self): # pragma: no cover
self._snap_increment_setting_window.visible = True
def _create_snap_increment_setting_window(self):
self._snap_increment_setting_window = ui.Window(
"Snap Increment Settings Menu",
width=400,
height=0,
flags=ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR,
visible=False,
)
with self._snap_increment_setting_window.frame:
with ui.VStack(spacing=8, height=0, name="frame_v_stack"):
ui.Label("Snap Settings - Increments", enabled=False)
ui.Separator()
with ui.HStack():
with ui.HStack(width=120):
ui.Label("Position", width=50)
ui.Spacer()
all_axis = ["X", "Y", "Z"]
all_axis_model = {
"X": self._snap_move_x_settings_model,
"Y": self._snap_move_y_settings_model,
"Z": self._snap_move_z_settings_model,
}
colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F}
for axis in all_axis:
with ui.HStack():
with ui.ZStack(width=15):
ui.Rectangle(
width=15,
height=20,
style={
"background_color": colors[axis],
"border_radius": 3,
"corner_flag": ui.CornerFlag.LEFT,
},
)
ui.Label(axis, alignment=ui.Alignment.CENTER)
ui.FloatDrag(model=all_axis_model[axis], min=0, max=1000000, step=0.01)
ui.Circle(width=20, radius=3.5, size_policy=ui.CircleSizePolicy.FIXED)
with ui.HStack():
with ui.HStack(width=120):
ui.Label("Rotation", width=50)
ui.Spacer()
ui.FloatDrag(model=self._snap_rotate_settings_model, min=0, max=1000000, step=0.01)
with ui.HStack():
with ui.HStack(width=120):
ui.Label("Scale", width=50)
ui.Spacer()
ui.FloatDrag(model=self._snap_scale_settings_model, min=0, max=1000000, step=0.01)
def _register_context_menu(self):
context_menu = omni.kit.context_menu.get_instance()
def is_button(objects: dict, button_name: str): # pragma: no cover
return objects.get("widget_name", None) == button_name
if context_menu:
menu = {
"name": f"Snap Settings {ui.get_custom_glyph_code('${glyphs}/cog.svg')}",
"show_fn": [lambda object: is_button(object, "snap")],
"onclick_fn": lambda object: self._on_show_snap_increment_setting_window(),
"enabled_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING),
}
self._snap_settings_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar")
menu = {
"name": "Snap to Increment",
"show_fn": [lambda object: is_button(object, "snap")],
"onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=False),
"checked_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING),
}
self._snap_to_increment_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar")
menu = {
"name": "Snap to Face",
"show_fn": [lambda object: is_button(object, "snap")],
"onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=True),
"checked_fn": lambda object: self._settings.get(self.SNAP_TO_SURFACE_SETTING),
}
self._snap_to_face_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar")
| 9,363 | Python | 47.518134 | 120 | 0.583574 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/select_button_group.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 carb.input
import omni.kit.context_menu
import omni.ui as ui
import pathlib
from pxr import Kind
from carb.input import KeyboardInput as Key
from omni.kit.widget.toolbar.hotkey import Hotkey
from omni.kit.widget.toolbar.widget_group import WidgetGroup
from .models.select_mode_model import SelectModeModel
from .models.select_no_kinds_model import SelectNoKindsModel
from .models.select_include_ref_model import SelectIncludeRefModel
from .models.transform_mode_model import TransformModeModel
SELECT_PRIM_MODE_TOOL_NAME = "Prim"
SELECT_MODEL_MODE_TOOL_NAME = "Model"
SELECT_TOOL_NAME = "Select"
LIGHT_TYPES = "type:CylinderLight;type:DiskLight;type:DistantLight;type:DomeLight;type:GeometryLight;type:Light;type:RectLight;type:SphereLight"
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar")
)
SELECT_MODE_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/SelectMode/enabled"
class SelectButtonGroup(WidgetGroup):
def __init__(self):
super().__init__()
self._input = carb.input.acquire_input_interface()
self._select_mode_model = SelectModeModel()
self._select_no_kinds_model = SelectNoKindsModel()
self._select_include_ref_model = SelectIncludeRefModel()
self._select_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SELECT)
self._select_op_menu_entry = None
self._custom_types = []
self._settings = carb.settings.get_settings()
self._icon_path = str(EXTENSION_FOLDER_PATH / "data" / "icon")
self._settings = carb.settings.get_settings()
self._select_mode_button = None
self._mode_hotkey = None
if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH):
def hotkey_change():
current_mode = self._select_mode_model.get_value_as_string()
if current_mode == "models" or current_mode == "kind:model.ALL":
self._select_mode_model.set_value("type:ALL")
else:
self._select_mode_model.set_value("kind:model.ALL")
self._update_selection_mode_button()
def on_select_mode_hotkey_changed(hotkey: str):
self._select_mode_button.tooltip = self._get_select_mode_tooltip()
self._mode_hotkey = Hotkey(
"toolbar::select_mode",
Key.T,
hotkey_change,
lambda: self._select_mode_button.enabled and self._is_in_context(),
on_hotkey_changed_fn=on_select_mode_hotkey_changed,
)
# only replace the tooltip part so that "Paint Select" registered from select brush can still have correct label
def on_select_hotkey_changed(hotkey: str):
self._select_op_button.tooltip = (
self._select_op_button.tooltip.rsplit("(", 1)[0] + f"({self._select_hotkey.get_as_string('Q')})"
)
self._select_hotkey = Hotkey(
"toolbar::select",
Key.Q,
lambda: self._select_op_button.model.set_value(True),
lambda: self._select_op_button.enabled and self._is_in_context()
and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON)
== 0,
on_hotkey_changed_fn=lambda hotkey: on_select_hotkey_changed(hotkey),
)
self._sub_menu = []
self._register_context_menu()
def get_style(self):
style = {
"Button.Image::select_mode": {"image_url": "${glyphs}/toolbar_select_prim.svg"},
"Button.Image::select_op_models": {"image_url": "${glyphs}/toolbar_select_models.svg"},
"Button.Image::select_op_prims": {"image_url": "${glyphs}/toolbar_select_prims.svg"},
"Button.Image::all_prim_types": {"image_url": f"{self._icon_path}/all_prim_types.svg"},
"Button.Image::meshes": {"image_url": f"{self._icon_path}/meshes.svg"},
"Button.Image::lights": {"image_url": f"{self._icon_path}/lights.svg"},
"Button.Image::cameras": {"image_url": f"{self._icon_path}/cameras.svg"},
"Button.Image::model_kinds": {"image_url": f"{self._icon_path}/model_kinds.svg"},
"Button.Image::assembly": {"image_url": f"{self._icon_path}/assembly.svg"},
"Button.Image::group": {"image_url": f"{self._icon_path}/group.svg"},
"Button.Image::component": {"image_url": f"{self._icon_path}/component.svg"},
"Button.Image::sub_component": {"image_url": f"{self._icon_path}/sub_component.svg"},
"Button.Image::payload_reference": {"image_url": f"{self._icon_path}/payload_reference.svg"},
"Button.Image::custom_kind": {"image_url": f"{self._icon_path}/custom_kind.svg"},
"Button.Image::custom_type": {"image_url": f"{self._icon_path}/custom_type.svg"},
}
return style
def create(self, default_size):
def select_enabled(): # pragma: no cover (Unused, it's commened out below - I am just adding coverage! '^^)
return True
def on_select_mode_change(model):
self._update_selection_mode_button()
result = {}
if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH):
self._select_mode_button = ui.ToolButton(
model=self._select_mode_model,
name="select_mode",
tooltip=self._get_select_mode_tooltip(),
width=default_size,
height=default_size,
# checked=select_enabled,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_mode"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
)
self._model_changed_sub = self._select_mode_model.subscribe_value_changed_fn(on_select_mode_change)
result["select_mode"] = self._select_mode_button
with ui.ZStack(width=0, height=0):
self._select_op_button = ui.ToolButton(
model=self._select_op_model,
name=self._get_select_op_button_name(self._select_mode_model),
tooltip=self._get_select_tooltip(),
width=default_size,
height=default_size,
checked=self._select_op_model.get_value_as_bool(),
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_op"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
)
# Follow the pattern here (ZStack + _build_flyout_indicator) for other buttons if they want dynamic flyout indicator
self._select_op_menu_sub = self._build_flyout_indicator(default_size, default_size, "select_op")
result["select_op"] = self._select_op_button
self._update_selection_mode_button()
return result
def clean(self):
super().clean()
self._select_mode_button = None
self._select_op_button = None
self._select_mode_model.clean()
self._select_mode_model = None
self._select_no_kinds_model.clean()
self._select_no_kinds_model = None
self._select_include_ref_model.clean()
self._select_include_ref_model = None
self._select_op_model.clean()
self._select_op_model = None
self._model_changed_sub = None
if self._mode_hotkey:
self._mode_hotkey.clean()
self._mode_hotkey = None
self._select_hotkey.clean()
self._select_hotkey = None
self._select_mode_menu_entry.release()
self._select_mode_menu_entry = None
if self._select_op_menu_entry:
self._select_op_menu_entry.release()
self._select_op_menu_entry = None
self._select_op_menu_sub = None
for menu in self._sub_menu:
menu.release()
self._sub_menu = []
def _get_select_op_button_name(self, model):
return "select_op_prims" if model.get_value_as_bool() else "select_op_models"
def _get_select_tooltip(self):
return f"{SELECT_TOOL_NAME} ({self._select_hotkey.get_as_string('Q')})"
def _get_select_mode_button_name(self):
mode_name = {
"type:ALL": "all_prim_types",
"type:Mesh": "meshes",
LIGHT_TYPES: "lights",
"type:Camera": "cameras",
"kind:model.ALL": "model_kinds",
"kind:assembly": "assembly",
"kind:group": "group",
"kind:component": "component",
"kind:subcomponent": "sub_component",
"ref:reference;ref:payload": "custom_type",
}
mode = self._select_mode_model.get_value_as_string()
if mode in mode_name:
return mode_name[mode]
else: # pragma: no cover
if mode[:4] == "kind":
return "custom_kind"
else:
return "custom_type"
def _get_select_mode_tooltip(self):
mode_data = {
"type:ALL": "All Prim Types",
"type:Mesh": "Meshes",
LIGHT_TYPES: "Lights",
"type:Camera": "Camera",
"kind:model.ALL": "All Model Kinds",
"kind:assembly": "Assembly",
"kind:group": "Group",
"kind:component": "Component",
"kind:subcomponent": "Subcomponent",
"ref:reference;ref:payload": "Subcomponent",
}
mode = self._select_mode_model.get_value_as_string()
if mode in mode_data:
tooltip = mode_data[mode]
else: # pragma: no cover
if mode[:4] == "kind":
tooltip = "Custom Kind"
else:
tooltip = "Custom type"
return tooltip + f" ({self._mode_hotkey.get_as_string('T')})"
def _usd_kinds(self):
return ["model", "assembly", "group", "component", "subcomponent"]
def _enable_no_kinds_option(self, b): # pragma: no cover
mode = self._select_mode_model.get_value_as_string()
return mode[:4] == "kind"
def _usd_kinds_display(self): # pragma: no cover
return self._usd_kinds()[1:]
def _plugin_kinds(self):
all_kinds = set(Kind.Registry.GetAllKinds())
return all_kinds - set(self._usd_kinds())
def _create_selection_list(self, selections):
results = ""
delimiter = ";"
first_selection = True
for s in selections:
if not first_selection: # pragma: no cover (This seemingly can never happen, since first_selection is initialized with True oO)
first_selection = True
else:
results += delimiter
results += s
return results
def _update_selection_mode_button(self):
if self._select_mode_button:
self._select_mode_button.name = self._get_select_mode_button_name()
self._select_mode_button.tooltip = self._get_select_mode_tooltip()
if self._select_op_button:
self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model)
def _update_select_menu(self):
for menu in self._sub_menu:
menu.release()
self._sub_menu = []
def create_menu_entry(name, value, add_hotkey=False):
menu = {
"name": name,
"onclick_fn": lambda object: self._select_mode_model.set_value(value),
"checked_fn": lambda object, name=name, value=value: self._select_mode_model.get_value_as_string() == value,
"additional_kwargs": {
"style": {"Menu.Item.CheckMark": {"image_url": omni.kit.context_menu.style.get_radio_mark_url()}}
},
}
if add_hotkey:
menu["hotkey"] = (carb.input.KeyboardInput.T)
return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")
def create_header(header=""):
menu = {
"header": header,
"name": "",
}
return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")
self._sub_menu.append(create_header(header="Select by Type"))
self._sub_menu.append(create_menu_entry("All Prim Types", "type:ALL", True))
self._sub_menu.append(create_menu_entry("Meshes", "type:Mesh"))
self._sub_menu.append(create_menu_entry("Lights", LIGHT_TYPES))
self._sub_menu.append(create_menu_entry("Camera", "type:Camera"))
if self._custom_types:
for name, types in self._custom_types:
self._sub_menu.append(create_menu_entry(name, types))
self._sub_menu.append(create_header(header="Select by Model Kind"))
self._sub_menu.append(create_menu_entry("All Model Kinds", "kind:model.ALL"))
self._sub_menu.append(create_menu_entry("Assembly", "kind:assembly"))
self._sub_menu.append(create_menu_entry("Group", "kind:group"))
self._sub_menu.append(create_menu_entry("Component", "kind:component"))
self._sub_menu.append(create_menu_entry("Subcomponent", "kind:subcomponent"))
plugin_kinds = self._plugin_kinds()
if (len(plugin_kinds)) > 0:
for k in plugin_kinds: # pragma: no cover
self._sub_menu.append(create_menu_entry(str(k), str(key).capitalize(), f"kind:{k}"))
self._sub_menu.append(create_header(header=""))
menu = {
"name": "Include Prims with no Kind",
"onclick_fn": lambda object: self._select_no_kinds_model.set_value(not self._select_no_kinds_model.get_value_as_bool()),
"checked_fn": lambda object: self._select_no_kinds_model.get_value_as_bool(),
"enabled_fn": self._enable_no_kinds_option,
}
self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar"))
menu = {
"name": "Include References and Payloads",
"onclick_fn": lambda object: self._select_include_ref_model.set_value(not self._select_include_ref_model.get_value_as_bool()),
"checked_fn": lambda object: self._select_include_ref_model.get_value_as_bool(),
"enabled_fn": self._enable_no_kinds_option,
}
self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar"))
def _register_context_menu(self):
context_menu = omni.kit.context_menu.get_instance()
def is_button(objects: dict, button_name: str): # pragma: no cover
return objects.get("widget_name", None) == button_name
if context_menu:
def on_clicked_select(): # pragma: no cover
self._select_op_model.set_value(True)
self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model)
self._select_op_button.set_tooltip(self._get_select_tooltip())
self._select_op_button.model = self._select_op_model
menu = {
"name": "Select",
"show_fn": [lambda object: is_button(object, "select_op")],
"onclick_fn": lambda object: on_clicked_select(),
"checked_fn": lambda object: self._select_op_button.name == "select_op_prims"
or self._select_op_button.name == "select_op_models",
}
self._select_mode_menu_entry = omni.kit.context_menu.add_menu(menu, "select_op", "omni.kit.widget.toolbar")
if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH):
menu = {
"name": "Select Mode",
"show_fn": [lambda object: is_button(object, "select_mode")],
}
self._select_op_menu_entry = omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")
self._update_select_menu()
def add_custom_select_type(self, entry_name: str, selection_types: list):
selection = []
for s in selection_types:
selection.append(f"type:{s}")
selection_string = self._create_selection_list(selection)
self._custom_types.append((entry_name, selection_string))
self._update_select_menu()
def remove_custom_select(self, entry_name):
for index, (entry, selection_string) in enumerate(self._custom_types):
if entry == entry_name:
del self._custom_types[index]
self._update_select_menu()
return
| 17,097 | Python | 44.473404 | 144 | 0.592151 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/transform_mode_model.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.ui as ui
import carb
import carb.dictionary
import carb.settings
class TransformModeModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the prim select mode"""
TRANSFORM_OP_SETTING = "/app/transform/operation"
TRANSFORM_OP_SELECT = "select"
TRANSFORM_OP_MOVE = "move"
TRANSFORM_OP_ROTATE = "rotate"
TRANSFORM_OP_SCALE = "scale"
def __init__(self, op):
super().__init__()
self._op = op
self._settings = carb.settings.get_settings()
self._settings.set_default_string(self.TRANSFORM_OP_SETTING, self.TRANSFORM_OP_MOVE)
self._dict = carb.dictionary.get_dictionary()
self._op_sub = self._settings.subscribe_to_node_change_events(self.TRANSFORM_OP_SETTING, self._on_op_change)
self._selected_op = self._settings.get(self.TRANSFORM_OP_SETTING)
def clean(self):
self._settings.unsubscribe_to_change_events(self._op_sub)
def _on_op_change(self, item, event_type):
self._selected_op = self._dict.get(item)
self._value_changed()
def _on_op_space_changed(self, item, event_type): # pragma: no cover (Seems to never be used, is overwritten in the inherited model where it is used.)
self._op_space = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._selected_op == self._op
def set_value(self, value):
"""Reimplemented set bool"""
if value:
self._settings.set(self.TRANSFORM_OP_SETTING, self._op)
class LocalGlobalTransformModeModel(TransformModeModel):
TRANSFORM_MODE_GLOBAL = "global"
TRANSFORM_MODE_LOCAL = "local"
def __init__(self, op, op_space_setting_path):
super().__init__(op=op)
self._setting_path = op_space_setting_path
self._op_space_sub = self._settings.subscribe_to_node_change_events(
self._setting_path, self._on_op_space_changed
)
self._op_space = self._settings.get(self._setting_path)
def clean(self):
self._settings.unsubscribe_to_change_events(self._op_space_sub)
super().clean()
def _on_op_space_changed(self, item, event_type):
self._op_space = self._dict.get(item)
self._value_changed()
def get_op_space_mode(self):
return self._op_space
def set_value(self, value):
if not value:
self._settings.set(
self._setting_path,
self.TRANSFORM_MODE_LOCAL
if self._op_space == self.TRANSFORM_MODE_GLOBAL
else self.TRANSFORM_MODE_GLOBAL,
)
super().set_value(value)
| 3,104 | Python | 33.5 | 155 | 0.653351 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/setting_model.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.ui as ui
import carb
import carb.dictionary
import carb.settings
class BoolSettingModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch a bool setting path"""
def __init__(self, setting_path, inverted):
super().__init__()
self._setting_path = setting_path
self._inverted = inverted
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change)
self._value = self._settings.get(self._setting_path)
if self._inverted:
self._value = not self._value
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._value = self._dict.get(item)
if self._inverted:
self._value = not self._value
self._value_changed()
def get_value_as_bool(self):
return self._value
def set_value(self, value):
"""Reimplemented set bool"""
if self._inverted:
value = not value
self._settings.set(self._setting_path, value)
if self._inverted:
self._value = value
class FloatSettingModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch a float setting path"""
def __init__(self, setting_path):
super().__init__()
self._setting_path = setting_path
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change)
self._value = self._settings.get(self._setting_path)
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._value = self._dict.get(item)
self._value_changed()
def get_value_as_float(self):
return self._value
def set_value(self, value):
"""Reimplemented set float"""
self._settings.set(self._setting_path, value)
| 2,654 | Python | 34.4 | 112 | 0.662773 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/timeline_model.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.ui as ui
import carb
import omni.timeline
from omni.kit.commands import execute
class TimelinePlayPauseModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch a bool setting path"""
def __init__(self):
super().__init__()
self._timeline = omni.timeline.get_timeline_interface()
self._is_playing = self._timeline.is_playing()
self._is_stopped = self._timeline.is_stopped()
stream = self._timeline.get_timeline_event_stream()
self._sub = stream.create_subscription_to_pop(self._on_timeline_event)
def clean(self):
self._sub = None
def get_value_as_bool(self):
return self._is_playing and not self._is_stopped
def set_value(self, value):
"""Reimplemented set bool"""
if value:
execute("ToolbarPlayButtonClicked")
else:
execute("ToolbarPauseButtonClicked")
def _on_timeline_event(self, e):
is_playing = self._timeline.is_playing()
is_stopped = self._timeline.is_stopped()
if is_playing != self._is_playing or is_stopped != self._is_stopped:
self._is_playing = self._timeline.is_playing()
self._is_stopped = self._timeline.is_stopped()
self._value_changed()
| 1,732 | Python | 34.367346 | 86 | 0.67552 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_mode_model.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.ui as ui
import carb
import carb.dictionary
import carb.settings
class SelectModeModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the prim select mode"""
PICKING_MODE_SETTING = "/persistent/app/viewport/pickingMode"
PICKING_MODE_MODELS = "kind:model.ALL"
PICKING_MODE_PRIMS = "type:ALL"
# new default
PICKING_MODE_DEFAULT = PICKING_MODE_PRIMS
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_string(self.PICKING_MODE_SETTING, self.PICKING_MODE_DEFAULT)
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_SETTING, self._on_change)
self.set_value(self._settings.get(self.PICKING_MODE_SETTING))
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._mode = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._mode == self.PICKING_MODE_PRIMS
def get_value_as_string(self):
return self._mode
def set_value(self, value):
if isinstance(value, bool):
if value:
self._mode = self.PICKING_MODE_PRIMS
else:
self._mode = self.PICKING_MODE_MODELS
else:
self._mode = value
self._settings.set(self.PICKING_MODE_SETTING, self._mode)
| 1,993 | Python | 32.79661 | 119 | 0.67988 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_no_kinds_model.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import carb.dictionary
import carb.settings
class SelectNoKindsModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the prim select mode"""
PICKING_MODE_NO_KINDS_SETTING = "/persistent/app/viewport/pickingModeNoKinds"
# new default
PICKING_MODE_NO_KINDS_DEFAULT = True
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(self.PICKING_MODE_NO_KINDS_SETTING, self.PICKING_MODE_NO_KINDS_DEFAULT)
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_NO_KINDS_SETTING, self._on_change)
self.set_value(self._settings.get(self.PICKING_MODE_NO_KINDS_SETTING))
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._mode = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._mode
def set_value(self, value):
self._mode = value
self._settings.set(self.PICKING_MODE_NO_KINDS_SETTING, self._mode)
| 1,680 | Python | 34.765957 | 128 | 0.713095 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/helpers.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.settings
def reset_toolbar_settings():
settings = carb.settings.get_settings()
vals = {
"/app/transform/operation": "move",
"/persistent/app/viewport/pickingMode": "type:ALL",
"/app/viewport/snapEnabled": False,
}
for key, val in vals.items():
settings.set(key, val)
| 759 | Python | 32.043477 | 76 | 0.724638 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_api.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 asyncio
import carb.settings
import omni.appwindow
import omni.kit.app
import omni.kit.test
import omni.timeline
import omni.kit.ui_test as ui_test
import omni.kit.widget.toolbar
import omni.kit.context_menu
import omni.kit.hotkeys.core
import omni.ui as ui
from carb.input import KeyboardInput as Key
from carb.input import KEYBOARD_MODIFIER_FLAG_SHIFT
from omni.kit.ui_test import Vec2
from omni.kit.widget.toolbar import Hotkey, SimpleToolButton, Toolbar, WidgetGroup, get_instance
from .helpers import reset_toolbar_settings
test_message_queue = []
class TestSimpleToolButton(SimpleToolButton):
"""
Test of how to use SimpleToolButton
"""
def __init__(self, icon_path):
def on_toggled(c):
test_message_queue.append(f"Test button toggled {c}")
super().__init__(
name="test_simple_tool_button",
tooltip="Test Simple ToolButton",
icon_path=f"{icon_path}/plus.svg",
icon_checked_path=f"{icon_path}/plus.svg",
hotkey=Key.U,
toggled_fn=on_toggled,
additional_style={"Button": { "color": 0xffffffff }}
)
class TestToolButtonGroup(WidgetGroup):
"""
Test of how to create two ToolButton in one WidgetGroup
"""
def __init__(self, icon_path):
super().__init__()
self._icon_path = icon_path
def clean(self):
self._sub1 = None
self._sub2 = None
self._hotkey.clean()
self._hotkey = None
super().clean()
def get_style(self):
style = {
"Button.Image::test1": {"image_url": f"{self._icon_path}/plus.svg"},
"Button.Image::test1:checked": {"image_url": f"{self._icon_path}/minus.svg"},
"Button.Image::test2": {"image_url": f"{self._icon_path}/minus.svg"},
"Button.Image::test2:checked": {"image_url": f"{self._icon_path}/plus.svg"},
}
return style
def create(self, default_size):
def on_value_changed(index, model):
if model.get_value_as_bool():
self._acquire_toolbar_context()
else:
self._release_toolbar_context()
test_message_queue.append(f"Group button {index} clicked")
self._menu1 = omni.kit.context_menu.add_menu({ "name": "Test 1", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar")
self._menu2 = omni.kit.context_menu.add_menu({ "name": "Test 2", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar")
button1 = ui.ToolButton(
name="test1",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "test1"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
)
self._sub1 = button1.model.subscribe_value_changed_fn(lambda model, index=1: on_value_changed(index, model))
button2 = ui.ToolButton(
name="test2",
width=default_size,
height=default_size,
)
self._sub2 = button2.model.subscribe_value_changed_fn(lambda model, index=2: on_value_changed(index, model))
self._hotkey = Hotkey(
"toolbar::test2",
Key.K,
lambda: button2.model.set_value(not button2.model.get_value_as_bool()),
lambda: self._is_in_context(),
)
# return a dictionary of name -> widget if you want to expose it to other widget_group
return {"test1": button1, "test2": button2}
_MAIN_WINDOW_INSTANCE = None
class ToolbarApiTest(omni.kit.test.AsyncTestCase):
WINDOW_NAME = "Main Toolbar Test"
async def setUp(self):
reset_toolbar_settings()
self._icon_path = omni.kit.widget.toolbar.get_data_path().absolute().joinpath("icon").absolute()
self._app = omni.kit.app.get_app()
test_message_queue.clear()
# If the instance doesn't exist, we need to create it for the test
# Create a tmp window with the widget inside, Y axis because the tests are in the Y axis
global _MAIN_WINDOW_INSTANCE
if _MAIN_WINDOW_INSTANCE is None:
_MAIN_WINDOW_INSTANCE = ui.ToolBar(
self.WINDOW_NAME, noTabBar=False, padding_x=3, padding_y=3, margin=5, axis=ui.ToolBarAxis.Y
)
self._widget = get_instance()
self._widget.set_axis(ui.ToolBarAxis.Y)
self._widget.rebuild_toolbar(root_frame=_MAIN_WINDOW_INSTANCE.frame)
await self._app.next_update_async()
await self._app.next_update_async()
self._main_dockspace = ui.Workspace.get_window("DockSpace")
self._toolbar_handle = ui.Workspace.get_window(self.WINDOW_NAME)
self._toolbar_handle.undock()
await self._app.next_update_async()
self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.LEFT)
await self._app.next_update_async()
async def test_api(self):
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
widget_simple = TestSimpleToolButton(self._icon_path)
widget = TestToolButtonGroup(self._icon_path)
toolbar.add_widget(widget, -100)
toolbar.add_widget(widget_simple, -200)
await self._app.next_update_async()
self.assertIsNotNone(widget_simple.get_tool_button())
# Check widgets are added and can be fetched
self.assertIsNotNone(toolbar.get_widget("test_simple_tool_button"))
self.assertIsNotNone(toolbar.get_widget("test1"))
self.assertIsNotNone(toolbar.get_widget("test2"))
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
manager = omni.kit.app.get_app().get_extension_manager()
extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__))
hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry()
hotkey = self._get_hotkey('test_simple_tool_button::hotkey')
self.assertIsNotNone(hotkey)
hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button")
tool_test1_pos = self._get_widget_center(toolbar, "test1")
tool_test2_pos = self._get_widget_center(toolbar, "test2")
# Test click on first simple button
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
# Test hot key on first simple button
await self._emulate_keyboard_press(Key.U, KEYBOARD_MODIFIER_FLAG_SHIFT)
await self._app.next_update_async()
# Test click on 1/2 group button
await self._emulate_click(tool_test1_pos)
await self._app.next_update_async()
# Test click on 2/2 group button
await self._emulate_click(tool_test2_pos)
await self._app.next_update_async()
# Test click on 2/2 group button again
await self._emulate_click(tool_test2_pos)
await self._app.next_update_async()
self.assertIsNone(ui.Menu.get_current())
# Test right click on 1/2 group button
await self._emulate_click(tool_test1_pos, right_click=True)
await self._app.next_update_async()
self.assertIsNotNone(ui.Menu.get_current())
# Test left click on 1/2 group button to close the menu
await self._emulate_click(tool_test1_pos, right_click=False)
await self._app.next_update_async()
self.assertIsNone(ui.Menu.get_current())
# Test hold-left-click click on 1/2 group button
await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.MOVE, Vec2(*tool_test1_pos))
await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_DOWN)
await self._app.next_update_async()
await asyncio.sleep(0.4)
await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_UP)
await self._app.next_update_async()
self.assertIsNotNone(ui.Menu.get_current())
# Test left click on 1/2 group button to close the menu
await self._emulate_click(tool_test1_pos)
await self._app.next_update_async()
self.assertIsNone(ui.Menu.get_current())
# Making sure all button are triggered by checking the message queue
expected_messages = [
"Test button toggled True",
"Test button toggled False",
"Group button 1 clicked",
"Group button 2 clicked",
"Group button 2 clicked",
]
self.assertEqual(expected_messages, test_message_queue)
test_message_queue.clear()
hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=0), None)
toolbar.remove_widget(widget)
toolbar.remove_widget(widget_simple)
widget.clean()
widget_simple.clean()
await self._app.next_update_async()
# Check widgets are cleared
self.assertIsNone(toolbar.get_widget("test_simple_tool_button"))
self.assertIsNone(toolbar.get_widget("test1"))
self.assertIsNone(toolbar.get_widget("test2"))
# Change the Hotkey for the Play button
play_hotkey = self._get_hotkey('toolbar::play')
self.assertIsNotNone(play_hotkey)
hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
tooltip_after_change = toolbar.get_widget('play').tooltip
hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=0), None)
await self._app.next_update_async()
tooltip_after_revert = toolbar.get_widget('play').tooltip
self.assertEqual(tooltip_after_change, "Play (SHIFT + SPACE)")
self.assertEqual(tooltip_after_revert, "Play (SPACE)")
# Change the Hotkey for the Select Mode button
select_mode_hotkey = self._get_hotkey('toolbar::select_mode')
self.assertIsNotNone(select_mode_hotkey)
hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
tooltip_after_change = toolbar.get_widget('select_mode').tooltip
hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=0), None)
await self._app.next_update_async()
tooltip_after_revert = toolbar.get_widget('select_mode').tooltip
self.assertEqual(tooltip_after_change, "All Prim Types (SHIFT + T)")
self.assertEqual(tooltip_after_revert, "All Prim Types (T)")
# Change the Hotkey for the Move button
move_op_hotkey = self._get_hotkey('toolbar::move')
self.assertIsNotNone(move_op_hotkey)
hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
tooltip_after_change = toolbar.get_widget('move_op').tooltip
hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=0), None)
await self._app.next_update_async()
tooltip_after_revert = toolbar.get_widget('move_op').tooltip
from ..builtin_tools.transform_button_group import MOVE_TOOL_NAME
self.assertEqual(tooltip_after_change, f"{MOVE_TOOL_NAME} (SHIFT + W)")
self.assertEqual(tooltip_after_revert, f"{MOVE_TOOL_NAME} (W)")
# Test the Select Mode hotkey button
settings = carb.settings.get_settings()
from ..builtin_tools.models.select_mode_model import SelectModeModel
self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS)
await self._emulate_keyboard_press(Key.T)
await self._app.next_update_async()
self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_MODELS)
await self._emulate_keyboard_press(Key.T)
await self._app.next_update_async()
self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS)
# Test changing the Select hotkey
select_hotkey = self._get_hotkey('toolbar::select')
self.assertIsNotNone(select_hotkey)
hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=0), None)
await self._app.next_update_async()
async def test_context(self):
toolbar = omni.kit.widget.toolbar.get_instance()
widget_simple = TestSimpleToolButton(self._icon_path)
widget = TestToolButtonGroup(self._icon_path)
test_context = "test_context"
toolbar.add_widget(widget, -100)
toolbar.add_widget(widget_simple, -200, test_context)
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button")
tool_test1_pos = self._get_widget_center(toolbar, "test1")
# Test click on first simple button
# Add "Test button toggled True" to queue
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), test_context)
# Test hot key on 2/2 group button
# It should have no effect since it's not "in context"
# Add nothing to queue
await self._emulate_keyboard_press(Key.K)
await self._app.next_update_async()
# Test click on first simple button again, should exit context
# Add "Test button toggled False" to queue
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT)
# Test hot key on 2/2 group button again
# It should have effect because it's in default context
# Add "Group button 2 clicked" to queue
await self._emulate_keyboard_press(Key.K)
await self._app.next_update_async()
# Test click on first simple button again
# Add "Test button toggled True" to queue
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), test_context)
# Test click on 1/2 group button so it takes context by force.
# Add "Group button 1 clicked" to queue
await self._emulate_click(tool_test1_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT)
# Test hot key on first simple button, it should still work on default context.
# Releasing an expired context.
# Add "Test button toggled False" to queue
await self._emulate_keyboard_press(Key.U)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT)
# Test hot key on first simple button, it should still work on default context.
# Add "Test button toggled True" to queue
await self._emulate_keyboard_press(Key.U)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), test_context)
expected_messages = [
"Test button toggled True",
"Test button toggled False",
"Group button 2 clicked",
"Test button toggled True",
"Group button 1 clicked",
"Test button toggled False",
"Test button toggled True",
]
self.assertEqual(expected_messages, test_message_queue)
toolbar.remove_widget(widget)
toolbar.remove_widget(widget_simple)
widget.clean()
widget_simple.clean()
await self._app.next_update_async()
def _get_widget_center(self, toolbar, id: str):
return (
toolbar.get_widget(id).screen_position_x + toolbar.get_widget(id).width / 2,
toolbar.get_widget(id).screen_position_y + toolbar.get_widget(id).height / 2,
)
def _get_hotkey(self, action_id: str):
manager = omni.kit.app.get_app().get_extension_manager()
extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__))
hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry()
for hotkey in hotkey_registry.get_all_hotkeys_for_extension(extension_name):
if hotkey.action_id == action_id:
return hotkey
async def _emulate_click(self, pos, right_click: bool = False):
await ui_test.emulate_mouse_move_and_click(Vec2(*pos), right_click=right_click)
async def _emulate_keyboard_press(self, key: Key, modifier: int = 0):
await ui_test.emulate_keyboard_press(key, modifier)
async def test_custom_select_types(self):
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
entry_name = 'TestType'
toolbar.add_custom_select_type(entry_name, ['test_type'])
menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar")
self.assertIn(entry_name, [item['name'] for item in menu_dict])
toolbar.remove_custom_select(entry_name)
menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar")
self.assertNotIn(entry_name, [item['name'] for item in menu_dict])
async def test_toolbar_methods(self):
from ..context_menu import ContextMenu
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
self.assertIsInstance(toolbar.context_menu, ContextMenu)
toolbar.set_axis(ui.ToolBarAxis.X)
toolbar.rebuild_toolbar()
await ui_test.human_delay()
toolbar.set_axis(ui.ToolBarAxis.Y)
toolbar.rebuild_toolbar()
await ui_test.human_delay()
toolbar.subscribe_grab_mouse_pressed(None)
async def test_toolbar_play_stop_button(self):
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
timeline = omni.timeline.get_timeline_interface()
# Click the stop button
toolbar.get_widget("stop").call_clicked_fn()
await ui_test.human_delay()
self.assertTrue(timeline.is_stopped())
| 19,485 | Python | 39.17732 | 146 | 0.651014 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/__init__.py | from .test_api import *
from .test_models import * | 50 | Python | 24.499988 | 26 | 0.74 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_models.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.timeline
import carb.settings
import omni.kit.commands
from omni.kit import ui_test
class ToolbarTestModels(omni.kit.test.AsyncTestCase):
async def test_setting_pass_through(self):
from ..builtin_tools.builtin_tools import LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET
settings = carb.settings.get_settings()
orig_value = settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET)
settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, True)
self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET))
settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, False)
self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET))
settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, orig_value)
async def test_select_include_ref_model(self):
from ..builtin_tools.models.select_include_ref_model import SelectIncludeRefModel
model = SelectIncludeRefModel()
orig_value = model.get_value_as_bool()
model.set_value(not orig_value)
self.assertEqual(model.get_value_as_bool(), not orig_value)
model.set_value(orig_value)
async def test_select_mode_model(self):
from ..builtin_tools.models.select_mode_model import SelectModeModel
model = SelectModeModel()
orig_value = model.get_value_as_string()
model.set_value(True)
self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS)
model.set_value(False)
self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_MODELS)
model.set_value(SelectModeModel.PICKING_MODE_PRIMS)
self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS)
model.set_value(orig_value)
async def test_select_no_kinds_model(self):
from ..builtin_tools.models.select_no_kinds_model import SelectNoKindsModel
model = SelectNoKindsModel()
orig_value = model.get_value_as_bool()
model.set_value(not orig_value)
self.assertEqual(model.get_value_as_bool(), not orig_value)
model.set_value(orig_value)
async def test_setting_model(self):
from ..builtin_tools.models.setting_model import BoolSettingModel, FloatSettingModel
settings = carb.settings.get_settings()
bool_setting_path = '/exts/omni.kit.widget.toolbar/test/boolSetting'
float_setting_path = '/exts/omni.kit.widget.toolbar/test/floatSetting'
bool_model = BoolSettingModel(bool_setting_path, False)
bool_model.set_value(True)
self.assertEqual(bool_model.get_value_as_bool(), True)
self.assertEqual(settings.get(bool_setting_path), True)
bool_model.set_value(False)
self.assertEqual(bool_model.get_value_as_bool(), False)
self.assertEqual(settings.get(bool_setting_path), False)
inverted_bool_model = BoolSettingModel(bool_setting_path, True)
inverted_bool_model.set_value(True)
self.assertEqual(inverted_bool_model.get_value_as_bool(), not True)
self.assertEqual(settings.get(bool_setting_path), not True)
inverted_bool_model.set_value(False)
self.assertEqual(inverted_bool_model.get_value_as_bool(), not False)
self.assertEqual(settings.get(bool_setting_path), not False)
float_model = FloatSettingModel(float_setting_path)
float_model.set_value(42.0)
self.assertEqual(float_model.get_value_as_float(), 42.0)
self.assertEqual(settings.get(float_setting_path), 42.0)
float_model.set_value(21.0)
self.assertEqual(float_model.get_value_as_float(), 21.0)
self.assertEqual(settings.get(float_setting_path), 21.0)
async def test_timeline_model(self):
from ..builtin_tools.models.timeline_model import TimelinePlayPauseModel
model = TimelinePlayPauseModel()
model.set_value(True)
await ui_test.human_delay()
self.assertTrue(model.get_value_as_bool())
model.set_value(False)
await ui_test.human_delay()
self.assertFalse(model.get_value_as_bool())
async def test_transform_mode_model(self):
from ..builtin_tools.models.transform_mode_model import TransformModeModel, LocalGlobalTransformModeModel
model = TransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE)
model.set_value(True)
self.assertTrue(model.get_value_as_bool())
settings = carb.settings.get_settings()
setting_path = '/exts/omni.kit.widget.toolbar/test/localGlobalTransformOp'
settings.set(setting_path, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL)
model = LocalGlobalTransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE, setting_path)
model.set_value(False)
self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL)
model.set_value(False)
self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL)
async def test_play_pause_stop_commands(self):
timeline = omni.timeline.get_timeline_interface()
omni.kit.commands.execute("ToolbarPlayButtonClicked")
await ui_test.human_delay()
self.assertTrue(timeline.is_playing())
omni.kit.commands.execute("ToolbarPauseButtonClicked")
await ui_test.human_delay()
self.assertFalse(timeline.is_playing())
omni.kit.commands.execute("ToolbarStopButtonClicked")
await ui_test.human_delay()
self.assertTrue(timeline.is_stopped())
settings = carb.settings.get_settings()
setting_path = '/exts/omni.kit.widget.toolbar/test/playFilter'
omni.kit.commands.execute("ToolbarPlayFilterChecked", setting_path=setting_path, enabled=True)
self.assertTrue(settings.get(setting_path))
| 6,629 | Python | 43.496644 | 148 | 0.706291 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/prompt_ui.py | import urllib
import carb
import carb.settings
import omni.ui as ui
from typing import List
class Prompt:
def __init__(
self, title: str, text: str, button_text: list, button_fn: list, modal: bool = False,
callback_addons: List = [], callback_destroy: List = [], decode_text: bool = True
):
self._title = title
self._text = urllib.parse.unquote(text) if decode_text else text
self._button_list = []
self._modal = modal
self._callback_addons = callback_addons
self._callback_destroy = callback_destroy
self._buttons = []
for name, fn in zip(button_text, button_fn):
self._button_list.append((name, fn))
self._build_ui()
def destroy(self):
self._cancel_button_fn = None
self._ok_button_fn = None
self._button_list = []
if self._window:
self._window.destroy()
del self._window
self._window = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
self._callback_addons = []
for callback in self._callback_destroy:
if callback and callable(callback):
callback()
self._callback_destroy = []
def __del__(self):
self.destroy()
def __enter__(self):
self.show()
if self._modal:
settings = carb.settings.get_settings()
# Only use first word as a reason (e.g. "Creating, Openning"). URL won't work as a setting key.
operation = self._text.split(" ")[0].lower()
self._hang_detector_disable_key = "/app/hangDetector/disableReasons/{0}".format(operation)
settings.set(self._hang_detector_disable_key, "1")
settings.set("/crashreporter/data/appState", operation)
return self
def __exit__(self, type, value, trace):
self.hide()
if self._modal:
settings = carb.settings.get_settings()
settings.destroy_item(self._hang_detector_disable_key)
settings.set("/crashreporter/data/appState", "started")
def show(self):
self._window.visible = True
def hide(self):
self._window.visible = False
def is_visible(self):
return self._window.visible
def set_text(self, text):
self._text_label.text = text
def _build_ui(self):
self._window = ui.Window(
self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED, raster_policy=ui.RasterPolicy.NEVER
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
| ui.WINDOW_FLAGS_NO_CLOSE
)
if self._modal:
self._window.flags |= ui.WINDOW_FLAGS_MODAL
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(widht=10, height=0)
self._text_label = ui.Label(
self._text,
width=ui.Percent(100),
height=0,
word_wrap=True,
alignment=ui.Alignment.CENTER,
)
ui.Spacer(widht=10, height=0)
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(height=0)
for name, fn in self._button_list:
if name:
button = ui.Button(name)
if fn:
button.set_clicked_fn(lambda on_fn=fn: (self.hide(), on_fn()))
else:
button.set_clicked_fn(lambda: self.hide())
self._buttons.append(button)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
for callback in self._callback_addons:
if callback and callable(callback):
callback()
| 4,295 | Python | 32.302325 | 128 | 0.518743 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/share_window.py | import carb
import omni.ui as ui
class ShareWindow(ui.Window):
def __init__(self, copy_button_text="Copy Path to Clipboard", copy_button_fn=None, modal=True, url=None):
self._title = "Share Omniverse USD Path"
self._copy_button_text = copy_button_text
self._copy_button_fn = copy_button_fn
self._status_text = "Copy and paste this path to another user to share the location of this USD file."
self._stage_url = url
self._stage_string_box = None
super().__init__(self._title, visible=url is not None, width=600, height=140, dockPreference=ui.DockPreference.DISABLED)
self.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
)
if modal:
self.flags = self.flags | ui.WINDOW_FLAGS_MODAL
self.frame.set_build_fn(self._build_ui)
def _build_ui(self):
with self.frame:
with ui.VStack():
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Spacer()
self._status_label = ui.Label(self._status_text, width=0)
ui.Spacer()
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Spacer()
self._stage_string_box = ui.StringField(width=550)
self._stage_string_box.model.set_value(self._stage_url)
ui.Spacer()
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer()
copy_button = ui.Button(self._copy_button_text, width=165)
copy_button.set_clicked_fn(self._on_copy_button_fn)
ui.Spacer()
ui.Spacer(height=10)
def _on_copy_button_fn(self):
self.visible = False
if self._stage_string_box:
try:
import omni.kit.clipboard # type: ignore
try:
omni.kit.clipboard.copy(self._stage_string_box.model.as_string)
except:
carb.log_warn("clipboard copy failed")
except ImportError:
carb.log_warn("Could not import omni.kit.clipboard. Cannot copy scene URL to the clipboard.")
@property
def url(self):
return self._stage_url
@url.setter
def url(self, value: str) -> None:
self._stage_url = value
if self._stage_string_box:
self._stage_string_box.model.set_value(value)
self.visible = True
| 2,688 | Python | 37.971014 | 128 | 0.541295 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/save_stage_ui.py | import asyncio
import weakref
import urllib
import carb.settings
import omni.client
import omni.ui
from omni.kit.widget.versioning import CheckpointHelper
class CheckBoxStatus:
def __init__(self, checkbox, layer_identifier, layer_is_writable):
self.checkbox = checkbox
self.layer_identifier = layer_identifier
self.layer_is_writable = layer_is_writable
self.is_checking = False
class StageSaveDialog:
WINDOW_WIDTH = 580
MAX_VISIBLE_LAYER_COUNT = 10
def __init__(self, on_save_fn=None, on_dont_save_fn=None, on_cancel_fn=None, enable_dont_save=False):
self._usd_context = omni.usd.get_context()
self._save_fn = on_save_fn
self._dont_save_fn = on_dont_save_fn
self._cancel_fn = on_cancel_fn
self._checkboxes_status = []
self._select_all_checkbox_is_checking = False
self._selected_layers = []
self._checkpoint_marks = {}
flags = (
omni.ui.WINDOW_FLAGS_NO_COLLAPSE
| omni.ui.WINDOW_FLAGS_NO_SCROLLBAR
| omni.ui.WINDOW_FLAGS_MODAL
)
self._window = omni.ui.Window(
"Select Files to Save##file.py",
visible=False,
width=0,
height=0,
flags=flags,
auto_resize=True,
padding_x=10,
dockPreference=omni.ui.DockPreference.DISABLED,
)
with self._window.frame:
with omni.ui.VStack(height=0, width=StageSaveDialog.WINDOW_WIDTH):
self._layers_scroll_frame = omni.ui.ScrollingFrame(height=160)
omni.ui.Spacer(width=0, height=10)
self._checkpoint_comment_frame = omni.ui.Frame()
with self._checkpoint_comment_frame:
with omni.ui.VStack(height=0, spacing=5):
omni.ui.Label("*) File(s) that will be Checkpointed with a comment.")
with omni.ui.ZStack():
self._description_field = omni.ui.StringField(multiline=True, height=60)
self._description_field_hint_label = omni.ui.Label(
" Description", alignment=omni.ui.Alignment.LEFT_TOP, style={"color": 0xFF3F3F3F}
)
self._description_begin_edit_sub = self._description_field.model.subscribe_begin_edit_fn(
self._on_description_begin_edit
)
self._description_end_edit_sub = self._description_field.model.subscribe_end_edit_fn(
self._on_description_end_edit
)
self._checkpoint_comment_spacer = omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(height=0)
self._save_selected_button = omni.ui.Button("Save Selected", width=0, height=0)
self._save_selected_button.set_clicked_fn(self._on_save_fn)
omni.ui.Spacer(width=5, height=0)
if enable_dont_save:
self._dont_save_button = omni.ui.Button("Don't Save", width=0, height=0)
self._dont_save_button.set_clicked_fn(self._on_dont_save_fn)
omni.ui.Spacer(width=5, height=0)
self._cancel_button = omni.ui.Button("Cancel", width=0, height=0)
self._cancel_button.set_clicked_fn(self._on_cancel_fn)
omni.ui.Spacer(height=0)
omni.ui.Spacer(height=5)
def destroy(self):
self._usd_context = None
self._save_fn = None
self._dont_save_fn = None
self._cancel_fn = None
self._checkboxes_status = None
self._selected_layers = None
self._checkpoint_marks = None
if self._window:
del self._window
self._window = None
def __del__(self):
self.destroy()
def _on_save_fn(self):
if self._save_fn:
self._save_fn(
self._selected_layers,
comment=self._description_field.model.get_value_as_string()
if self._checkpoint_comment_frame.visible
else "",
)
self._window.visible = False
self._selected_layers = []
def _on_dont_save_fn(self):
if self._dont_save_fn:
self._dont_save_fn(self._description_field.model.get_value_as_string())
self._window.visible = False
self._selected_layers = []
def _on_cancel_fn(self):
if self._cancel_fn:
self._cancel_fn(self._description_field.model.get_value_as_string())
self._window.visible = False
self._selected_layers = []
def _on_select_all_fn(self, model):
if self._select_all_checkbox_is_checking:
return
self._select_all_checkbox_is_checking = True
if model.get_value_as_bool():
for checkbox_status in self._checkboxes_status:
checkbox_status.checkbox.model.set_value(True)
else:
for checkbox_status in self._checkboxes_status:
checkbox_status.checkbox.model.set_value(False)
self._select_all_checkbox_is_checking = False
def _check_and_select_all(self, select_all_check_box):
select_all = True
for checkbox_status in self._checkboxes_status:
if checkbox_status.layer_is_writable and not checkbox_status.checkbox.model.get_value_as_bool():
select_all = False
break
if select_all:
self._select_all_checkbox_is_checking = True
select_all_check_box.model.set_value(True)
self._select_all_checkbox_is_checking = False
def _on_checkbox_fn(self, model, check_box_index, select_all_check_box):
check_box_status = self._checkboxes_status[check_box_index]
if check_box_status.is_checking:
return
check_box_status.is_checking = True
if not check_box_status.layer_is_writable:
model.set_value(False)
elif model.get_value_as_bool():
self._selected_layers.append(check_box_status.layer_identifier)
self._check_and_select_all(select_all_check_box)
else:
self._selected_layers.remove(check_box_status.layer_identifier)
self._select_all_checkbox_is_checking = True
select_all_check_box.model.set_value(False)
self._select_all_checkbox_is_checking = False
check_box_status.is_checking = False
def show(self, layer_identifiers=None):
self._layers_scroll_frame.clear()
self._checkpoint_marks.clear()
self._checkpoint_comment_frame.visible = False
self._checkpoint_comment_spacer.visible = False
settings = carb.settings.get_settings()
enable_versioning = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False
# make a copy
self._selected_layers.extend(layer_identifiers)
self._checkboxes_status = []
#build layers_scroll_frame
self._first_item_stack = None
with self._layers_scroll_frame:
with omni.ui.VStack(height=0):
omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(width=20, height=0)
self._select_all_checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16})
self._select_all_checkbox.model.set_value(True)
omni.ui.Label("File Name", alignment=omni.ui.Alignment.LEFT)
omni.ui.Spacer(width=20, height=0)
omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(width=20, height=0)
omni.ui.Separator(height=0, style={"color": 0xFF808080})
omni.ui.Spacer(width=20, height=0)
omni.ui.Spacer(width=0, height=5)
for i in range(len(layer_identifiers)):
layer_identifier = layer_identifiers[i]
# TODO Move version related code
if enable_versioning:
# Check if the server support checkpoint
self._check_checkpoint_enabled(layer_identifier)
style = {}
layer_is_writable = omni.usd.is_layer_writable(layer_identifier)
layer_is_locked = omni.usd.is_layer_locked(self._usd_context, layer_identifier)
if not layer_is_writable or layer_is_locked:
self._selected_layers.remove(layer_identifier)
style = {"background_color": 0xFF808080, "color": 0xFF808080}
label_text = urllib.parse.unquote(layer_identifier).replace("\\", "/")
if not layer_is_writable or layer_is_locked:
label_text += " (Read-Only)"
omni.ui.Spacer(width=0, height=5)
stack = omni.ui.HStack(height=0, style=style)
if self._first_item_stack is None:
self._first_item_stack = stack
with stack:
omni.ui.Spacer(width=20, height=0)
checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16})
checkbox.model.set_value(True)
omni.ui.Label(label_text, word_wrap=False, elided_text=True, alignment=omni.ui.Alignment.LEFT)
check_point_label = omni.ui.Label("*", width=3, alignment=omni.ui.Alignment.LEFT, visible=False)
omni.ui.Spacer(width=20, height=0)
self._checkpoint_marks[layer_identifier] = check_point_label
checkbox.model.add_value_changed_fn(
lambda a, b=i, c=self._select_all_checkbox: self._on_checkbox_fn(a, b, c)
)
self._checkboxes_status.append(CheckBoxStatus(checkbox, layer_identifier, layer_is_writable))
self._select_all_checkbox.model.add_value_changed_fn(lambda a: self._on_select_all_fn(a))
self._window.visible = True
async def __delay_adjust_window_size(weak_self):
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
__self = weak_self()
if not __self:
return
y0 = __self._layers_scroll_frame.screen_position_y
y1 = __self._first_item_stack.screen_position_y
fixed_height = y1 - y0 + 5
item_height = __self._first_item_stack.computed_content_height + 5
count = min(StageSaveDialog.MAX_VISIBLE_LAYER_COUNT, len(__self._checkpoint_marks))
scroll_frame_new_height = fixed_height + count * item_height
__self._layers_scroll_frame.height = omni.ui.Pixel(scroll_frame_new_height)
if len(layer_identifiers) > 0:
asyncio.ensure_future(__delay_adjust_window_size(weakref.ref(self)))
def is_visible(self):
return self._window.visible
def _on_description_begin_edit(self, model):
self._description_field_hint_label.visible = False
def _on_description_end_edit(self, model):
if len(model.get_value_as_string()) == 0:
self._description_field_hint_label.visible = True
def _check_checkpoint_enabled(self, url):
async def check_server_support(weak_self, url):
_self = weak_self()
if not _self:
return
if await CheckpointHelper.is_checkpoint_enabled_async(url):
_self._checkpoint_comment_frame.visible = True
_self._checkpoint_comment_spacer.visible = True
label = _self._checkpoint_marks.get(url, None)
if label:
label.visible = True
asyncio.ensure_future(check_server_support(weakref.ref(self), url))
| 12,233 | Python | 43.813187 | 120 | 0.563803 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/style.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 carb
import omni.ui as ui
try:
THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle")
except Exception:
THEME = None
finally:
THEME = THEME or "NvidiaDark"
def get_style():
if THEME == "NvidiaLight": # pragma: no cover
BACKGROUND_COLOR = 0xFF535354
BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E
BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E
FIELD_BACKGROUND_COLOR = 0xFF1F2124
SECONDARY_COLOR = 0xFFE0E0E0
BORDER_COLOR = 0xFF707070
TITLE_COLOR = 0xFF707070
TEXT_COLOR = 0xFF8D760D
TEXT_HINT_COLOR = 0xFFD6D6D6
else:
BACKGROUND_COLOR = 0xFF23211F
BACKGROUND_SELECTED_COLOR = 0xFF8A8777
BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A
SECONDARY_COLOR = 0xFF9E9E9E
BORDER_COLOR = 0xFF8A8777
TITLE_COLOR = 0xFFCECECE
TEXT_COLOR = 0xFF9E9E9E
TEXT_HINT_COLOR = 0xFF7A7A7A
style = {
"Button": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
"margin": 0,
"padding": 0
},
"Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"Button.Label": {"color": TEXT_COLOR},
"Field": {"background_color": BACKGROUND_COLOR, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"Field.Hint": {"background_color": 0x0, "color": TEXT_HINT_COLOR, "margin_width": 4},
"Label": {"background_color": 0x0, "color": TEXT_COLOR},
"CheckBox": {"alignment": ui.Alignment.CENTER},
}
return style
| 2,126 | Python | 36.982142 | 161 | 0.659454 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.