file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "${ext_title}" description="A simple python extension example to use as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import ${python_module}". [[python.module]] name = "${python_module}" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,570
TOML
31.729166
118
0.73949
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/docs/README.md
# Python Extension Example [${ext_id}] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
168
Markdown
32.799993
126
0.761905
omniverse-code/kit/exts/omni.kit.window.extensions/config/extension.toml
[package] title = "Extensions" description = "Customize and personalize Kit with extensions" version = "1.1.1" category = "Internal" feature = true changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.async_engine" = {} "omni.kit.clipboard" = {} "omni.kit.commands" = {} "omni.kit.test" = {} "omni.kit.widget.graph" = {} "omni.ui" = {} "omni.client" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.window.extensions" [settings] # Enable publish and unpublish from UI feature: persistent.exts."omni.kit.window.extensions".publishingEnabled = false # Open folders and files in VSCode instead of OS file explorer: persistent.exts."omni.kit.window.extensions".openInVSCode = false exts."omni.kit.window.extensions".docUrlInternal = "http://omniverse-docs.s3-website-us-east-1.amazonaws.com/${extName}/${version}" exts."omni.kit.window.extensions".docUrlExternal = "https://docs.omniverse.nvidia.com/kit/docs/${extName}/${version}" # Show Community extensions tab. Just always show or have an option to manually enable. exts."omni.kit.window.extensions".communityTabEnabled = true exts."omni.kit.window.extensions".communityTabOption = true # Links to create menu entries for under '+' exts."omni.kit.window.extensions".openExampleLinks = [ ["Open Extension Template On Github", "https://github.com/NVIDIA-Omniverse/kit-extension-template"] ] [[test]] args = ["--reset-user"] pythonTests.unreliable = [ "*UNRELIABLE*" ] #See https://nvidia-omniverse.atlassian.net/browse/OM-46331 stdoutFailPatterns.exclude = [ "*Failed to acquire interface*while unloading all plugins*" ] unreliable = true # OM-59453
1,637
TOML
32.428571
131
0.736103
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/common.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 asyncio import os import os.path from enum import Enum from functools import lru_cache from string import Template from typing import Callable, Dict, List, Tuple import carb.events import carb.settings import carb.tokens import omni.kit.app from . import ext_controller from .utils import get_ext_info_dict, get_extpath_git_ext, get_setting, set_default_and_get_setting, show_ok_popup # Extension root path. Set when extension starts. EXT_ROOT = None REGISTRIES_CHANGED_EVENT = carb.events.type_from_string("omni.kit.registry.nucleus.REGISTRIES_CHANGED_EVENT") REGISTRIES_SETTING = "/exts/omni.kit.registry.nucleus/registries" USER_REGISTRIES_SETTING = "/persistent/exts/omni.kit.registry.nucleus/userRegistries" EXTENSION_PULL_STARTED_EVENT = carb.events.type_from_string("omni.kit.window.extensions.EXTENSION_PULL_STARTED_EVENT") COMMUNITY_TAB_TOGGLE_EVENT = carb.events.type_from_string("omni.kit.window.extensions.COMMUNITY_TAB_TOGGLE_EVENT") REMOTE_IMAGE_SUPPORTED_EXTS = {".png"} def path_is_parent(parent_path, child_path): try: return os.path.commonpath([parent_path]) == os.path.commonpath([parent_path, child_path]) except ValueError: return False def is_in_omni_documents(path): return path_is_parent(get_omni_documents_path(), path) @lru_cache() def get_icons_path() -> str: assert EXT_ROOT is not None, "This function should be called only after EXT_ROOT is set" return f"{EXT_ROOT}/icons" @lru_cache() def get_omni_documents_path() -> str: return os.path.abspath(carb.tokens.get_tokens_interface().resolve("${omni_documents}")) @lru_cache() def get_kit_path() -> str: return os.path.abspath(carb.tokens.get_tokens_interface().resolve("${kit}")) @lru_cache() def get_categories() -> Dict: icons_path = get_icons_path() categories = { "animation": {"name": "Animation", "image": f"{icons_path}/data/category-animation.png"}, "graph": {"name": "Graph", "image": f"{icons_path}/data/category-graph.png"}, "rendering": {"name": "Lighting & Rendering", "image": f"{icons_path}/data/category-rendering.png"}, "audio": {"name": "Audio", "image": f"{icons_path}/data/category-audio.png"}, "simulation": {"name": "Simulation", "image": f"{icons_path}/data/category-simulation.png"}, "services": {"name": "Services", "image": f"{icons_path}/data/category-internal.png"}, "core": {"name": "Core", "image": f"{icons_path}/data/category-core.png"}, "example": {"name": "Example", "image": f"{icons_path}/data/category-example.png"}, "internal": {"name": "Internal", "image": f"{icons_path}/data/category-internal.png", "hidden": False}, "legacy": {"name": "Legacy", "image": f"{icons_path}/data/category-legacy.png"}, "other": {"name": "Other", "image": f"{icons_path}/data/category-internal.png"}, } return categories class ExtSource(Enum): NVIDIA = 0 THIRD_PARTY = 1 def get_ui_name(self): return "NVIDIA" if self == ExtSource.NVIDIA else "THIRD PARTY" class ExtAuthorGroup(Enum): NVIDIA = 0 PARTNER = 1 COMMUNITY_VERIFIED = 2 COMMUNITY_UNVERIFIED = 3 USER = 4 def get_ui_name(self): if self == ExtAuthorGroup.NVIDIA: return "NVIDIA" if self == ExtAuthorGroup.PARTNER: return "PARTNER" if self == ExtAuthorGroup.USER: return "USER" return "COMMUNITY" def get_registries(): settings = carb.settings.get_settings() settings_dict = settings.get_settings_dictionary("") for key, is_user in [(REGISTRIES_SETTING, False), (USER_REGISTRIES_SETTING, True)]: for r in settings_dict.get(key[1:], []): name = r.get("name", "") url = r.get("url", "") url = carb.tokens.get_tokens_interface().resolve(url) yield name, url, is_user @lru_cache() def get_registry_url(registry_name): version = get_setting("/app/extensions/registryVersion", "NOT_SET") for name, url, _ in get_registries(): if name == registry_name: return f"{url}/{version}" return None class ExtensionCommonInfo: def __init__(self, ext_id, ext_info, is_local): self.id = ext_id package_dict = ext_info.get("package", {}) self.fullname = package_dict["name"] self.title = package_dict.get("title", "").upper() or self.fullname self.name = self.title.lower() # used for sorting self.description = package_dict.get("description", "") or "No Description" self.version = package_dict.get("version", None) self.keywords = package_dict.get("keywords", []) self.toggleable = package_dict.get("toggleable", True) self.feature = package_dict.get("feature", False) self.authors = package_dict.get("authors", "") self.repository = package_dict.get("repository", "") self.package_id = package_dict.get("packageId", "") self.is_kit_file = ext_info.get("isKitFile", False) self.is_app = ("app" in self.keywords) or package_dict.get("app", self.is_kit_file) self.is_startup = ext_controller.is_startup_ext(self.fullname) self.is_startup_version = ext_controller.is_startup_ext(ext_id) self.is_featured = ext_controller.is_featured_ext(self.fullname) self.is_local = is_local state_dict = ext_info.get("state", {}) self.failed = state_dict.get("failed", False) self.enabled = state_dict.get("enabled", False) self.reloadable = state_dict.get("reloadable", False) self.is_pulled = state_dict.get("isPulled", False) self.is_toggle_blocked = (self.enabled and not self.reloadable) or (not self.toggleable) self.path = ext_info.get("path", "") self.provider_name = None # Only if solve_extensions is called self.non_toggleable_deps = [] self.solver_error = "" self.category = package_dict.get("category", "other").lower() # Ext sources if package_dict.get("exchange", False): if package_dict.get("partner", False): self.author_group = ExtAuthorGroup.PARTNER else: self.author_group = ExtAuthorGroup.COMMUNITY_VERIFIED elif not package_dict.get("trusted", True): self.author_group = ExtAuthorGroup.COMMUNITY_UNVERIFIED else: self.author_group = ExtAuthorGroup.NVIDIA # Extension location tag for UI and user extensions self.location_tag = "" if is_local: abs_path = os.path.abspath(self.path) if ext_info.get("isInCache", False): self.location_tag = "INSTALLED" elif self.author_group == ExtAuthorGroup.NVIDIA and ( ext_info.get("isUser", False) or is_in_omni_documents(abs_path) ): self.author_group = ExtAuthorGroup.USER else: git_ext = get_extpath_git_ext() if git_ext and path_is_parent(git_ext.get_cache_path(), abs_path): self.location_tag = "GIT" # Finalize source self.ext_source = ExtSource.NVIDIA if self.author_group == ExtAuthorGroup.NVIDIA else ExtSource.THIRD_PARTY self.is_untrusted = self.author_group == ExtAuthorGroup.COMMUNITY_UNVERIFIED # Remote exts if not is_local: self.location_tag = "REMOTE" self.provider_name = ext_info.get("registryProviderName", None) # If unknown category -> fallback to other categories = get_categories() if self.category not in categories: self.category = "other" # For icon by default use category icon, can be overriden with custom: self.icon_path = self._build_image_resource_path(package_dict, "icon", categories[self.category]["image"]) # For preview image there is no default self.preview_image_path = self._build_image_resource_path(package_dict, "preview_image") def _build_image_resource_path(self, package_dict, key, default_path=None): resource_path = default_path if self.is_local: path = package_dict.get(key, None) if path: icon_path = os.path.join(self.path, path) if os.path.exists(icon_path): resource_path = icon_path else: path = package_dict.get(key + "_remote", None) if path: if os.path.splitext(path)[1] not in REMOTE_IMAGE_SUPPORTED_EXTS: return default_path url = get_registry_url(self.provider_name) if url: resource_path = url + "/" + path return resource_path def solve_extensions(self): # This function is costly, so we don't run it for each item. Only on demand when UI shows selected extension. manager = omni.kit.app.get_app().get_extension_manager() result, exts, err = manager.solve_extensions([self.id], add_enabled=True, return_only_disabled=True) if not result: self.failed = True self.non_toggleable_deps = [] self.solver_error = err if result: for ext in exts: ext_dict, _ = get_ext_info_dict(manager, ext) if not ext_dict.get("package", {}).get("toggleable", True): self.non_toggleable_deps.append(ext["id"]) def build_ext_info(ext_id, package_id=None) -> Tuple[ExtensionCommonInfo, dict]: manager = omni.kit.app.get_app().get_extension_manager() package_id = package_id or ext_id ext_info_remote = manager.get_registry_extension_dict(package_id) ext_info_local = manager.get_extension_dict(ext_id) is_local = ext_info_local is not None ext_info = ext_info_local or ext_info_remote if not ext_info: return None, None ext_info = ext_info.get_dict() # convert to python dict to prolong lifetime return ExtensionCommonInfo(ext_id, ext_info, is_local), ext_info def check_can_be_toggled(ext_id: str, for_autoload=False): ext_item, _ = build_ext_info(ext_id) if ext_item: ext_item.solve_extensions() # Error to solve? if ext_item.solver_error: text = "Failed to solve all extension dependencies:" text += f"\n{ext_item.solver_error}" asyncio.ensure_future(show_ok_popup("Error", text)) return False if not for_autoload and ext_item.non_toggleable_deps: text = "This extension cannot be enabled at runtime.\n" text += "Some of dependencies require an app restart to be enabled (toggleable=false):\n\n" for ext in ext_item.non_toggleable_deps: text += f" * {ext}" text += "\n\n" text += "Set this extension to autoload and restart an app to enable it." asyncio.ensure_future(show_ok_popup("Warning", text)) return False return True def toggle_extension(ext_id: str, enable: bool): if enable and not check_can_be_toggled(ext_id): return False omni.kit.commands.execute("ToggleExtension", ext_id=ext_id, enable=enable) return True async def pull_extension_async(ext_item: ExtensionCommonInfo, on_pull_started_fn: Callable = None): if ext_item.is_untrusted: cancel = False def on_cancel(dialog): nonlocal cancel cancel = True dialog.hide() message = """ ATTENTION: UNVERIFIED COMMUNITY EXTENSION This extension will be installed directly from the repository (see "Repo Url"). It is not verified by NVIDIA and may contain bugs or malicious code. Do you want to proceed? """ await show_ok_popup( "Warning", message, ok_label="Install", cancel_label="Cancel", disable_cancel_button=False, cancel_handler=on_cancel, width=600, ) if cancel: return ext_manager = omni.kit.app.get_app().get_extension_manager() ext_manager.pull_extension_async(ext_item.id) omni.kit.app.get_app().get_message_bus_event_stream().push(EXTENSION_PULL_STARTED_EVENT) if on_pull_started_fn: on_pull_started_fn() class SettingBoolValue: def __init__(self, path: str, default: bool): self._path = path self._value = set_default_and_get_setting(path, default) def get(self) -> bool: return self._value def set_bool(self, value: bool): self._value = value carb.settings.get_settings().set(self._path, self._value) def __bool__(self): return self.get() def build_doc_urls(ext_item: ExtensionCommonInfo) -> List[str]: """Produce possible candiates for doc urls""" # Base url if omni.kit.app.get_app().is_app_external(): doc_url = get_setting("/exts/omni.kit.window.extensions/docUrlExternal", "") else: doc_url = get_setting("/exts/omni.kit.window.extensions/docUrlInternal", "") if not doc_url: return [] # Build candidates. Prefer exact version, fallback to just a link to latest candidates = [] for v in [ext_item.version, "latest", ""]: candidates.append(Template(doc_url).safe_substitute({"version": v, "extName": ext_item.fullname})) return candidates @lru_cache() def is_community_tab_always_enabled() -> bool: return get_setting("/exts/omni.kit.window.extensions/communityTabEnabled", True) def is_community_tab_enabled_as_option() -> bool: if is_community_tab_always_enabled(): return False return get_setting("/exts/omni.kit.window.extensions/communityTabOption", True) class ExtOptions: def __init__(self): self.community_tab = None if is_community_tab_enabled_as_option(): self.community_tab = SettingBoolValue( "/persistent/exts/omni.kit.window.extensions/communityTabEnabled", default=False ) self.publishing = SettingBoolValue( "/persistent/exts/omni.kit.window.extensions/publishingEnabled", default=False ) @lru_cache() def get_options() -> ExtOptions: return ExtOptions() def is_community_tab_enabled() -> bool: # Can be either always enabled, or as a toggleable preference if is_community_tab_always_enabled(): return True return get_options().community_tab is not None and get_options().community_tab @lru_cache() def get_open_example_links(): return get_setting("/exts/omni.kit.window.extensions/openExampleLinks", [])
15,092
Python
36.451613
118
0.633316
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_properties_paths.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.kit.app import omni.ui as ui from .styles import get_style from .utils import cleanup_folder, copy_text, get_extpath_git_ext PATH_TYPE_TO_LABEL = { omni.ext.ExtensionPathType.COLLECTION: "[dir]", omni.ext.ExtensionPathType.COLLECTION_USER: "[user dir]", omni.ext.ExtensionPathType.COLLECTION_CACHE: "[cache dir]", omni.ext.ExtensionPathType.DIRECT_PATH: "[ext]", omni.ext.ExtensionPathType.EXT_1_FOLDER: "[exts 1.0]", } PATH_TYPE_TO_COLOR = { omni.ext.ExtensionPathType.COLLECTION: 0xFF29A9A9, omni.ext.ExtensionPathType.COLLECTION_USER: 0xFF1989A9, omni.ext.ExtensionPathType.COLLECTION_CACHE: 0xFFA9A929, omni.ext.ExtensionPathType.DIRECT_PATH: 0xFF29A929, omni.ext.ExtensionPathType.EXT_1_FOLDER: 0xFF2929A9, } PATHS_COLUMNS = ["", "name", "type", "edit"] class PathItem(ui.AbstractItem): def __init__(self, path, path_type: omni.ext.ExtensionPathType, add_dummy=False): super().__init__() self.path_model = ui.SimpleStringModel(path) self.type = path_type self.is_user = path_type == omni.ext.ExtensionPathType.COLLECTION_USER self.is_cache = path_type == omni.ext.ExtensionPathType.COLLECTION_CACHE self.add_dummy = add_dummy git_ext = get_extpath_git_ext() if git_ext and git_ext.is_git_path(path): self.is_git = True self.local_path = git_ext.get_local_path(path) else: self.is_git = False self.local_path = path class PathsModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._ext_manager = omni.kit.app.get_app().get_extension_manager() self._children = [] self._load() self._add_dummy = PathItem("", omni.ext.ExtensionPathType.COLLECTION_USER, add_dummy=True) def destroy(self): self._children = [] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: return [] return self._children + [self._add_dummy] def get_item_value_model_count(self, item): """The number of columns""" return 4 def get_item_value_model(self, item, column_id): if column_id == 1: return item.path_model return None def _load(self): self._children = [] folders = self._ext_manager.get_folders() for folder in folders: path = folder["path"] path_type = folder["type"] item = PathItem(path, path_type) self._children.append(item) self._item_changed(None) def add_empty(self): self._children.append(PathItem("", omni.ext.ExtensionPathType.COLLECTION_USER)) self._item_changed(None) def remove_item(self, item): self._children.remove(item) self.save() self._item_changed(None) def clean_cache(self, item): path = item.local_path print(f"Cleaning up cache: {path}") cleanup_folder(path) def update_git(self, item): path = item.path_model.as_string get_extpath_git_ext().update_git_path(path) def save(self): current = [ folder["path"] for folder in self._ext_manager.get_folders() if folder["type"] == omni.ext.ExtensionPathType.COLLECTION_USER ] paths = [c.path_model.as_string for c in self._children if c.is_user] if current != paths: # remove and add again. We can only apply diff here, but then it is impossible to preserve the order. for p in current: self._ext_manager.remove_path(p) for p in paths: self._ext_manager.add_path(p, omni.ext.ExtensionPathType.COLLECTION_USER) get_extpath_git_ext.cache_clear() class EditableDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._subscription = None self._context_menu = ui.Menu("Context menu") def destroy(self): self._subscription = None self._context_menu = None def _show_copy_context_menu(self, x, y, button, modifier, text): if button != 1: return self._context_menu.clear() with self._context_menu: ui.MenuItem("Copy", triggered_fn=lambda: copy_text(text)) self._context_menu.show() def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" with ui.HStack(width=20): if column_id == 0 and not item.add_dummy: def open_path(item_=item): # Import it here instead of on the file root because it has long import time. path = item_.local_path if path: import webbrowser webbrowser.open(path) ui.Button("open", width=0, clicked_fn=open_path, tooltip="Open path using OS file explorer.") elif column_id == 1 and not item.add_dummy: value_model = model.get_item_value_model(item, column_id) stack = ui.ZStack(height=20) with stack: label = ui.Label(value_model.as_string, width=500, name=("config" if item.is_user else "builtin")) field = ui.StringField(value_model, visible=False) # Start editing when double clicked stack.set_mouse_double_clicked_fn( lambda x, y, b, _, f=field, l=label, m=model, i=item: self.on_double_click(b, f, l, m, i) ) # Right click is copy menu stack.set_mouse_pressed_fn( lambda x, y, b, m, t=value_model.as_string: self._show_copy_context_menu(x, y, b, m, t) ) elif column_id == 2 and not item.add_dummy: ui.Label(PATH_TYPE_TO_LABEL[item.type], style={"color": PATH_TYPE_TO_COLOR[item.type]}) elif column_id == 3: if item.is_user: def on_click(item_=item): if item.add_dummy: model.add_empty() else: model.remove_item(item_) ui.Spacer(width=10) ui.Button( name=("add" if item.add_dummy else "remove"), style_type_name_override="ItemButton", width=20, height=20, clicked_fn=on_click, ) ui.Spacer(width=4) elif item.is_cache: def clean_cache(item_=item): model.clean_cache(item_) ui.Spacer(width=10) ui.Button( name="clean", style_type_name_override="ItemButton", width=20, height=20, clicked_fn=clean_cache, ) ui.Spacer(width=4) if item.is_git: def update_git(item_=item): model.update_git(item_) ui.Button( name="update", style_type_name_override="ItemButton", width=20, height=20, clicked_fn=update_git, ) ui.Spacer() def on_double_click(self, button, field, label, model, item): """Called when the user double-clicked the item in TreeView""" if button != 0: return if item.add_dummy: return if not item.is_user: copy_text(field.model.as_string) return # Make Field visible when double clicked field.visible = True field.focus_keyboard() # When editing is finished (enter pressed of mouse clicked outside of the viewport) self._subscription = field.model.subscribe_end_edit_fn( lambda m, f=field, l=label, md=model: self.on_end_edit(m.as_string, f, l, md) ) def on_end_edit(self, text, field, label, model): """Called when the user is editing the item and pressed Enter or clicked outside of the item""" field.visible = False label.text = text self._subscription = None if text: model.save() def build_header(self, column_id): with ui.HStack(): ui.Spacer(width=10) ui.Label(PATHS_COLUMNS[column_id], name="header") class ExtsPathsWidget: def __init__(self): self._model = PathsModel() self._delegate = EditableDelegate() with ui.VStack(style=get_style(self)): ui.Spacer(height=20) with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style_type_name_override="TreeView", ): tree_view = ui.TreeView( self._model, delegate=self._delegate, root_visible=False, header_visible=True, ) tree_view.column_widths = [ui.Pixel(46), ui.Fraction(1), ui.Pixel(70), ui.Pixel(60)] ui.Spacer(height=10) def destroy(self): self._model.destroy() self._model = None self._delegate.destroy() self._delegate = None
10,223
Python
35.127208
118
0.55023
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/styles.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. # from functools import lru_cache from typing import Dict import omni.ui as ui from omni.ui import color as cl from .common import get_icons_path # Common size constants: EXT_ICON_SIZE = (70, 70) EXT_ICON_SIZE_LARGE = (100, 100) CATEGORY_ICON_SIZE = (70, 70) EXT_LIST_ITEM_H = 106 EXT_LIST_ITEMS_MARGIN_H = 3 EXT_ITEM_TITLE_BAR_H = 27 EXT_LIST_ITEM_ICON_ZONE_W = 87 @lru_cache() def get_styles() -> Dict: icons_path = get_icons_path() styles = { "ExtensionToggle": { "Image::Failed": {"image_url": f"{icons_path}/exclamation.svg", "color": 0xFF2222DD, "margin": 5}, "Button": {"margin": 0, "padding": 0, "background_color": 0x0}, "Button:checked": {"background_color": 0x0}, "Button.Image::nonclickable": {"color": 0x60FFFFFF, "image_url": f"{icons_path}/toggle-off.svg"}, "Button.Image::nonclickable:checked": {"color": 0x60FFFFFF, "image_url": f"{icons_path}/toggle-on.svg"}, "Button.Image::clickable": {"image_url": f"{icons_path}/toggle-off.svg", "color": 0xFFFFFFFF}, "Button.Image::clickable:checked": {"image_url": f"{icons_path}/toggle-on.svg"}, "Label::EnabledLabel": {"font_size": 16, "color": 0xFF71A376}, "Label::DisabledLabel": {"font_size": 16, "color": 0xFFB9B9B9}, "Button::InstallButton": {"background_color": 0xFF00B976, "border_radius": 4}, "Button::InstallButton:checked": {"background_color": 0xFF06A66B}, "Button.Label::InstallButton": {"color": 0xFF3E3E3E, "font_size": 14}, "Button::DownloadingButton": {"background_color": 0xFF008253, "border_radius": 4}, "Button.Label::DownloadingButton": {"color": 0xFF3E3E3E, "font_size": 8}, "Button::LaunchButton": {"background_color": 0xFF00B976, "border_radius": 4}, "Button.Label::LaunchButton": {"color": 0xFF3E3E3E, "font_size": 14}, }, "SimpleCheckBox": { "Button": {"margin": 0, "padding": 0, "background_color": 0x0}, "Button:hovered": {"background_color": 0x0}, "Button:checked": {"background_color": 0x0}, "Button:pressed": {"background_color": 0x0}, "Button.Image": {"image_url": f"{icons_path}/checkbox-off.svg", "color": 0xFFA8A8A8}, "Button.Image:hovered": {"color": 0xFF929292}, "Button.Image:pressed": {"color": 0xFFA4A4A4}, "Button.Image:checked": {"image_url": f"{icons_path}/checkbox-on.svg", "color": 0xFFA8A8A8}, "Image::disabled_checked": {"image_url": f"{icons_path}/checkbox-on.svg", "color": 0x3FA8A8A8}, "Image::disabled_unchecked": {"image_url": f"{icons_path}/checkbox-off.svg", "color": 0x3FA8A8A8}, "Label::disabled": {"font_size": 12, "color": 0xFF444444}, "Label": {"font_size": 16, "color": 0xFFC4C4C4}, }, "SearchWidget": { "SearchField": { "background_color": 0xFF212121, "color": 0xFFA2A2A2, "border_radius": 0, "font_size": 16, "margin": 0, "padding": 5, }, "Image::SearchIcon": {"image_url": f"{icons_path}/search.svg", "color": 0xFF646464}, "Label::Search": {"color": 0xFF646464}, "Button.Image::ClearSearch": { "image_url": f"{icons_path}/close.svg", "color": 0xFF646464, }, "Button.Image::ClearSearch:hovered": { "image_url": f"{icons_path}/close.svg", "color": 0xFF929292, }, "Button.Image::ClearSearch:pressed": { "image_url": f"{icons_path}/close.svg", "color": 0xFFC4C4C4, }, "Button::ClearSearch": { "margin": 0, "border_radius": 0, "border_width": 0, "padding": 3, "background_color": 0x00000000, }, "Button::ClearSearch:hovered": { "background_color": 0x00000000, }, "Button::ClearSearch:pressed": { "background_color": 0x00000000, }, }, "MarkdownText": { "Label": {"font_size": 16, "color": 0xFFCCCCCC}, "Label::text": {"font_size": 16, "color": 0xFFCCCCCC}, "Label::H1": {"font_size": 32, "color": 0xFFCCCCCC}, "Label::H2": {"font_size": 28, "color": 0xFFCCCCCC}, "Label::H3": {"font_size": 24, "color": 0xFFCCCCCC}, "Label::H4": {"font_size": 20, "color": 0xFFCCCCCC}, }, "ExtsWindow": { "ExtensionDescription.Button": {"background_color": 0xFF090969}, "ExtensionDescription.Title": {"font_size": 18, "color": 0xFFCCCCCC, "margin": 5}, "ExtensionDescription.Header": {"font_size": 20, "color": 0xFF409656}, "ExtensionDescription.Content": {"font_size": 16, "color": 0xFFCCCCCC, "margin": 5}, "ExtensionDescription.ContentError": {"font_size": 16, "color": 0xFF4056C6, "margin": 5}, "ExtensionDescription.ContentValue": {"font_size": 16, "color": 0xFF409656}, "ExtensionDescription.ContentLink": {"font_size": 16, "color": 0xFF82C994}, "ExtensionDescription.ContentLink:hovered": {"color": 0xFFB8E0C2}, "ExtensionList.Label::Description": {"font_size": 16}, "ExtensionList.Label::Name": {"font_size": 12}, "ExtensionDescription.Background": {"background_color": 0xFF363636, "border_radius": 4}, "ExtensionDescription.ContentBackground": {"background_color": 0xFF23211F}, "ExtensionList.Background": { "background_color": 0xFF212121, "border_radius": 0, "corner_flag": ui.CornerFlag.BOTTOM, }, "Rectangle::ExtensionListGroup": { "background_color": 0xFF303030, }, "Rectangle::ExtensionListGroup:hovered": { "background_color": 0xFF404040, }, "Rectangle::ExtensionListGroup:pressed": { "background_color": 0xFF303030, }, "ExtensionList.Group.Label": {"font_size": 16, "color": 0xFFC0C0C0}, "ExtensionList.Group.Icon::expanded": {"image_url": f"{icons_path}/expanded.svg"}, "ExtensionList.Group.Icon": {"image_url": f"{icons_path}/collapsed.svg"}, "ExtensionList.Separator": {"background_color": 0xFF000000}, # "ExtensionList.Background:hovered": {"background_color": 0xFF191919}, "ExtensionList.Background:selected": {"background_color": 0xFF8A8777}, "ExtensionList.Foreground": { "background_color": 0xFF2F2F2F, "border_width": 0, "border_radius": 0, "corner_flag": ui.CornerFlag.BOTTOM_RIGHT, }, "ExtensionList.Foreground:selected": {"background_color": 0xFF9F9B8A}, "ExtensionList.Label": {"font_size": 16, "color": 0xFF878787}, "ExtensionList.Label:selected": {"color": 0xFF212121}, "ExtensionList.Label::Title": {"font_size": 20, "margin_width": 10}, "ExtensionList.Label::Title:selected": {"color": 0xFFE0E0E0}, "ExtensionList.Label::Category": {"font_size": 16, "margin_width": 10}, "ExtensionList.Label::Id": {"font_size": 16, "margin_width": 10}, "ExtensionList.Label::Version": {"font_size": 16, "margin_width": 10, "margin_height": 5}, "TreeView": { "background_color": 0xFF23211F, "background_selected_color": 0xFF23211F, "secondary_color": 0xFF989898, # Scroll knob "alignment": ui.Alignment.RIGHT, }, "TreeView.ScrollingFrame": {"background_color": 0xFF4A4A4A}, "ComboBox": { "background_color": 0xFF212121, "border_radius": 0, "font_size": 16, "margin": 0, "color": 0xFF929292, "padding": 0, }, "ComboBox:hovered": {"background_color": 0xFF2F2F2F}, "ComboBox:selected": {"background_color": 0xFF2F2F2F}, "ExtensionDescription.Label": {"color": 0xFFC4C4C4, "margin": 2, "font_size": 16}, "ExtensionDescription.Id::Name": {"background_color": 0xFF000000, "color": 0xFFC4C4C4, "font_size": 14}, "ExtensionDescription.Rectangle::Name": {"background_color": 0xFF24211F, "border_radius": 2}, "ExtensionDescription.UpdateButton": {"background_color": 0xFF00B976, "border_radius": 4}, "ExtensionDescription.UpdateButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.RestartButton": {"background_color": 0xFF00B976, "border_radius": 4}, "ExtensionDescription.RestartButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.UpToDateButton": {"background_color": 0xFF747474, "border_radius": 4}, "ExtensionDescription.UpToDateButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.InstallButton": {"background_color": 0xFF00B976, "border_radius": 4}, "ExtensionDescription.InstallButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.DownloadingButton": {"background_color": 0xFF00754A, "border_radius": 4}, "ExtensionDescription.DownloadingButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.CommunityRectangle": {"background_color": 0xFF1F1F1F, "border_radius": 2}, "ExtensionDescription.CommunityImage": { "image_url": f"{icons_path}/community.svg", "color": cl(180, 180, 180), }, "ExtensionDescription.CommunityLabel": {"color": 0xFFA4A4A4, "font_size": 16}, "ExtensionDescription.UnverifiedRectangle": {"background_color": 0xFF000038, "border_radius": 2}, "ExtensionDescription.UnverifiedLabel": {"color": 0xFFC4C4C4, "margin_width": 30, "font_size": 16}, "Button::create": {"background_color": 0x0, "margin": 0}, "Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976}, "Button.Image::create:hovered": {"color": 0xFF00D976}, "Button::options": {"background_color": 0x0, "margin": 0}, "Button.Image::options": {"image_url": f"{icons_path}/options.svg", "color": 0xFF989898}, "Button.Image::options:hovered": {"color": 0xFFC2C2C2}, "Button::filter": {"background_color": 0x0, "margin": 0}, "Button.Image::filter": {"image_url": f"{icons_path}/filter_grey.svg", "color": 0xFF989898}, "Button.Image::filter:hovered": {"color": 0xFFC2C2C2}, "Button::filter_on": {"background_color": 0x0, "margin": 0}, "Button.Image::filter_on": {"image_url": f"{icons_path}/filter.svg", "color": 0xFF989898}, "Button.Image::filter_on:hovered": {"color": 0xFFC2C2C2}, "Button::sortby": {"background_color": 0x0, "margin": 0}, "Button.Image::sortby": {"image_url": f"{icons_path}/sort_by_grey.svg", "color": 0xFF989898}, "Button.Image::sortby:hovered": {"color": 0xFFC2C2C2}, "Button::sortby_on": {"background_color": 0x0, "margin": 0}, "Button.Image::sortby_on": {"image_url": f"{icons_path}/sort_by.svg", "color": 0xFF989898}, "Button.Image::sortby_on:hovered": {"color": 0xFFC2C2C2}, "ExtensionDescription.Tab": {"background_color": 0x0}, "ExtensionDescription.Tab.Label": {"color": 0xFF8D8D8D, "font_size": 16}, "ExtensionDescription.Tab.Label:pressed": {"color": 0xFFF3F2EC}, "ExtensionDescription.Tab.Label:selected": {"color": 0xFFF3F2EC}, "ExtensionDescription.Tab.Label:hovered": {"color": 0xFFADADAD}, "ExtensionDescription.TabLine": {"color": 0xFF00B976, "border_width": 1}, "ExtensionDescription.TabLineFull": {"color": 0xFF707070}, "ExtensionVersionMenu.MenuItem": {"color": 0x0, "margin": 0}, "IconButton": {"margin": 0, "padding": 0, "background_color": 0x0}, "IconButton:hovered": {"background_color": 0x0}, "IconButton:checked": {"background_color": 0x0}, "IconButton:pressed": {"background_color": 0x0}, "IconButton.Image": {"color": 0xFFA8A8A8}, "IconButton.Image:hovered": {"color": 0xFF929292}, "IconButton.Image:pressed": {"color": 0xFFA4A4A4}, "IconButton.Image:checked": {"color": 0xFFFFFFFF}, "IconButton.Image::OpenDoc": {"image_url": f"{icons_path}/question.svg"}, "IconButton.Image::OpenFolder": {"image_url": f"{icons_path}/open-folder.svg"}, "IconButton.Image::OpenConfig": {"image_url": f"{icons_path}/open-config.svg"}, "IconButton.Image::OpenInVSCode": {"image_url": f"{icons_path}/vscode.svg"}, "IconButton.Image::Export": {"image_url": f"{icons_path}/export.svg"}, "Image::UpdateAvailable": { "image_url": f"{icons_path}/update-available.svg", "color": 0xFFFFFFFF, "spacing": 50, }, "Label::UpdateAvailable": {"color": 0xFF00B977, "margin": 10}, "Label::LocationTag": {"color": 0xFF00B977, "margin": 10, "font_size": 16}, "Image::Community": {"image_url": f"{icons_path}/community.svg", "color": cl(255, 255, 255)}, "Image::Community:selected": {"color": cl("#ddefff")}, "Label::Community": {"color": 0xFFA4A4A4, "margin": 10, "font_size": 16}, "Rectangle::Splitter": {"background_color": 0x0, "margin": 3, "border_radius": 2}, "Rectangle::Splitter:hovered": {"background_color": 0xFFB0703B}, "Rectangle::Splitter:pressed": {"background_color": 0xFFB0703B}, "Image::UNKNOWN": {"color": 0xFFFFFFFF, "image_url": f"{icons_path}/question.svg"}, "Image::RUNNING": {"color": 0xFFFF7D7D, "image_url": f"{icons_path}/spinner.svg"}, "Image::PASSED": {"color": 0xFF00FF00, "image_url": f"{icons_path}/check_solid.svg"}, "Image::FAILED": {"color": 0xFF0000FF, "image_url": f"{icons_path}/exclamation.svg"}, }, "ExtsPropertiesWidget": { "Properies.Background": {"background_color": 0xFF24211F, "border_radius": 4}, }, "ExtsRegistriesWidget": { "TreeView": { "background_color": 0xFF23211F, "background_selected_color": 0xFF444444, }, "TreeView.Item": {"margin": 14, "color": 0xFF000055}, "Field": {"background_color": 0xFF333322}, "Label::header": {"margin": 4}, "Label": {"margin": 5}, "Label::builtin": {"color": 0xFF909090}, "Label::config": {"color": 0xFFDDDDDD}, "ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4}, "ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B}, "ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6}, "ItemButton:hovered": {"background_color": 0xFF333333}, "ItemButton:pressed": {"background_color": 0xFF222222}, }, "ExtsPathsWidget": { "TreeView": { "background_color": 0xFF23211F, "background_selected_color": 0xFF444444, }, "TreeView.Item": {"margin": 14, "color": 0xFF000055}, "Field": {"background_color": 0xFF333322}, "Label::header": {"margin": 4}, "Label": {"margin": 5}, "Label::builtin": {"color": 0xFF909090}, "Label::config": {"color": 0xFFDDDDDD}, "ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4}, "ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B}, "ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6}, "ItemButton.Image::clean": {"image_url": f"{icons_path}/broom.svg", "color": 0xFF5EDAFA}, "ItemButton.Image::update": {"image_url": f"{icons_path}/refresh.svg", "color": 0xFF5EDAFA}, "ItemButton:hovered": {"background_color": 0xFF333333}, "ItemButton:pressed": {"background_color": 0xFF222222}, }, } return styles def get_style(instance): return get_styles()[instance.__class__.__name__]
17,286
Python
57.402027
116
0.571272
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_test_tab.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.settings import omni.kit.app import omni.ui as ui from omni.kit.test import TestRunStatus from .ext_components import SimpleCheckBox DEFAULT_TEST_APP = "${kit}/apps/omni.app.test_ext.kit" class ExtTestTab: def __init__(self): self.test_status = {} # options self.info_log = False self.wait_for_debugger = False self.python_debugger = False self.wait_for_python_debugger = False self.ui_mode = False self.do_not_exit = False self.coverage = False self.tests_filter = "" self._test_filter_model = None self._app_combo = None self.apps = [f"{DEFAULT_TEST_APP} (empty)"] manager = omni.kit.app.get_app_interface().get_extension_manager() all_exts = [(manager.get_extension_dict(e["id"]), e["id"]) for e in manager.get_extensions()] self.apps += [ext_id for d, ext_id in all_exts if d.get("isKitFile", False)] def destroy(self): pass def build_cb(self, attr, name): SimpleCheckBox( getattr(self, attr), lambda v: setattr(self, attr, not getattr(self, attr)), name, ) def _update_test_args(self): args = [] if self.info_log: args += ["-v"] if self.wait_for_debugger: args += ["-d"] if self.wait_for_python_debugger: self.python_debugger = True args += ["--/exts/omni.kit.debug.python/break=1"] if self.python_debugger: args += ["--enable", "omni.kit.debug.python"] if self.do_not_exit: args += ["--/exts/omni.kit.test/doNotQuit=1"] self.tests_filter = self._test_filter_model.as_string args += [f"--/exts/omni.kit.test/runTestsFilter='{self.tests_filter}'"] settings = carb.settings.get_settings() selected_app = self._app_combo.model.get_item_value_model().as_int app = self.apps[selected_app] if selected_app > 0 else DEFAULT_TEST_APP settings.set("/exts/omni.kit.test/testExtApp", app) settings.set("/exts/omni.kit.test/testExtArgs", args) settings.set("/exts/omni.kit.test/testExtUIMode", self.ui_mode) settings.set("/exts/omni.kit.test/testExtGenerateCoverageReport", self.coverage) settings.set("/exts/omni.kit.test/testExtCleanOutputPath", self.coverage) # todo offer a way to pick reliable/unreliable/both # settings.set("/exts/omni.kit.test/testExtRunUnreliableTests", 2) def build(self, ext_info): ext_id = ext_info.get("package").get("id") with ui.VStack(height=0): ui.Spacer(height=20) ui.Label("Options:", height=0, width=50, style_type_name_override="ExtensionDescription.Label") ui.Spacer(height=10) self.build_cb("info_log", "info log") self.build_cb("ui_mode", "ui mode (test selection)") self.build_cb("coverage", "generate coverage report") self.build_cb("wait_for_debugger", "wait for native debugger") self.build_cb("python_debugger", "enable python debugger") self.build_cb("wait_for_python_debugger", "enable python debugger and wait") self.build_cb("do_not_exit", "do not exit after tests") ui.Spacer(height=10) with ui.HStack(): ui.Spacer(width=10) ui.Label( "filter (e.g.: *test_usd*):", height=0, width=50, style_type_name_override="ExtensionDescription.Label", ) self._test_filter_model = ui.StringField(width=250).model self._test_filter_model.as_string = self.tests_filter ui.Spacer(height=20) with ui.HStack(): ui.Spacer(width=10) ui.Label("app:", height=0, width=50, style_type_name_override="ExtensionDescription.Label") self._app_combo = ui.ComboBox(0, *self.apps, style={"padding": 4}, width=400) ui.Spacer(height=20) with ui.HStack(): status_image = None def _refresh_test_status(): status = self.test_status.get(ext_id, TestRunStatus.UNKNOWN) status_image.name = str(status.name) def on_status(test_id, status, **_): self.test_status[ext_id] = status _refresh_test_status() def on_finish(status, *_): if self.coverage: omni.kit.test.generate_report() def on_click(ext_id=ext_id): self._update_test_args() omni.kit.test.run_ext_tests([ext_id], on_finish, on_status) ui.Button( "RUN EXTENSION TESTS", style_type_name_override="ExtensionDescription.InstallButton", width=80, height=20, clicked_fn=on_click, ) ui.Spacer(width=20) ui.Label("Result:", width=0, style_type_name_override="ExtensionDescription.Label") status_image = ui.Image( name="TestStatus", width=20, height=20, alignment=ui.Alignment.RIGHT_CENTER, ) _refresh_test_status()
5,923
Python
36.025
107
0.564072
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_info_widget.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. # # pylint: disable=protected-access, access-member-before-definition import abc import asyncio import contextlib import os import weakref from datetime import datetime, timezone from typing import Callable import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui from . import ext_controller from .common import ( ExtAuthorGroup, ExtensionCommonInfo, build_ext_info, check_can_be_toggled, get_categories, get_options, pull_extension_async, toggle_extension, ) from .ext_components import ExtensionToggle, SimpleCheckBox, add_doc_link_button from .ext_data_fetcher import get_ext_data_fetcher from .ext_export_import import export_ext from .ext_test_tab import ExtTestTab from .exts_graph_window import ExtsGraphWidget from .markdown_renderer import MarkdownText from .styles import CATEGORY_ICON_SIZE, EXT_ICON_SIZE_LARGE from .utils import clip_text, is_vscode_installed, open_in_vscode_if_enabled, version_to_str ICON_ZONE_WIDTH = 120 CATEGORY_ZONE_WIDTH = 120 def get_ext_text_content(key: str, ext_info, ext_item: ExtensionCommonInfo): """Get extension readme/changelog from either local dict or registry extra data""" content_str = "" # Get the data if ext_item.is_local: content_str = ext_info.get("package", {}).get(key, "") else: fetcher = get_ext_data_fetcher() ext_data = fetcher.get_ext_data(ext_item.package_id) if ext_data: content_str = ext_data.get("package", {}).get(key, "") # Figure out if it is a path to a file or actual data if content_str and "\n" not in content_str: ext_path = ext_info.get("path", "") # If it is a path -> load file content readme_file = os.path.join(ext_path, content_str) if os.path.exists(readme_file): with open(readme_file, "r", encoding="utf-8") as f: content_str = f.read() return content_str class PageBase: """ Interface for any classes adding Tabs to the Extension Manager UI """ @abc.abstractmethod def build_tab(self, ext_info: dict, ext_item: ExtensionCommonInfo) -> None: """Build the Tab.""" @abc.abstractmethod def destroy(self) -> None: """Teardown the Tab.""" @staticmethod @abc.abstractmethod def get_tab_name() -> str: """Get the name used for the tab name in the UI""" def build_package_info(ext_info): if ext_info is None: return package_dict = ext_info.get("package", {}) publish_dict = package_dict.get("publish", {}) def add_info(name, value): if not value: return if isinstance(value, (tuple, list)): value = ", ".join(value) if isinstance(value, dict): value = str(value) with ui.HStack(): ui.Label(name, width=100, style_type_name_override="ExtensionDescription.Content") if value.startswith("http://") or value.startswith("https://"): def open_link(): import webbrowser webbrowser.open(value) ui.Label( value, style_type_name_override="ExtensionDescription.ContentLink", mouse_pressed_fn=lambda x, y, b, a: b == 0 and open_link(), ) else: ui.Label(value, style_type_name_override="ExtensionDescription.ContentValue") def add_package_info(name, key): add_info(name, package_dict.get(key, None)) # Package info add_package_info("Authors", "authors") add_package_info("Keywords", "keywords") add_info("Repo Name", publish_dict.get("repoName", None)) add_package_info("Repo Url", "repository") add_package_info("Github Release", "githubRelease") # Publish info ts = publish_dict.get("date", None) if not ts: ts = package_dict.get("publishDate", None) # backward compatibility for deprecated key if ts: add_info("Publish Date", str(datetime.fromtimestamp(ts, tz=timezone.utc).astimezone())) add_info("Build Number", publish_dict.get("buildNumber", None)) add_info("Kit Version", publish_dict.get("kitVersion", None)) add_package_info("Target", "target") # Test info test = ext_info.get("test", None) if isinstance(test, (list, tuple)): for t in test: add_info("Test Waiver", t.get("waiver", None)) class OverviewPage(PageBase): """ Build a class with same interface and add it to ExtInfoWidget.pages below to have it show up as a tab """ def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): def content_label(text): ui.Label(text, style_type_name_override="ExtensionDescription.Content") readme_str = get_ext_text_content("readme", ext_info, ext_item) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.ZStack(): ui.Rectangle(style_type_name_override="ExtensionDescription.ContentBackground") with ui.HStack(): ui.Spacer(width=10) with ui.VStack(height=0): ui.Spacer(height=10) # All the meta info about the package (version, date, authors) build_package_info(ext_info) ui.Spacer(height=15) # Readme MarkdownText(readme_str) # Preview ? if ext_item.preview_image_path: ui.Image( ext_item.preview_image_path, alignment=ui.Alignment.H_CENTER, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=700, height=700, ) else: content_label("Preview: 'package/preview_image' is not specified.") def destroy(self): pass @staticmethod def get_tab_name(): return "OVERVIEW" class ChangelogPage(PageBase): def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): changelog_str = get_ext_text_content("changelog", ext_info, ext_item) if not changelog_str: changelog_str = "[no changelog]" # word_wrap is important here because changelog can # be Markdown, and if word_wrap is defalut, Label # ignores everything after double hash. word_wrap fixes it. with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.ZStack(): ui.Rectangle(style_type_name_override="ExtensionDescription.ContentBackground") with ui.HStack(): ui.Spacer(width=10) with ui.VStack(height=0): ui.Spacer(height=10) MarkdownText(changelog_str) def destroy(self): pass @staticmethod def get_tab_name(): return "CHANGELOG" class DependenciesPage(PageBase): def __init__(self): self._ext_graph = None def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): # Graph available if extension is enabled: if ext_info.get("state", {}).get("enabled", False): self._ext_graph = ExtsGraphWidget(ext_info.get("package").get("id")) else: with ui.VStack(height=0): manager = omni.kit.app.get_app().get_extension_manager() # Enable result result, exts, err = manager.solve_extensions([ext_item.id], add_enabled=True, return_only_disabled=True) if not result: ui.Label( "Enabling this extension will fail with the following error:", style_type_name_override="ExtensionDescription.Header", ) ui.Label(err, style_type_name_override="ExtensionDescription.ContentError") else: ui.Label( "Enabling this extension will enable the following extensions in order:", style_type_name_override="ExtensionDescription.Header", ) ui.Label( "".join(f"\n - {ext['id']}" for ext in exts), style_type_name_override="ExtensionDescription.Content", ) ui.Spacer(height=30) # Dependencies ui.Label("Dependencies (in config):", style_type_name_override="ExtensionDescription.Header") ui.Spacer(height=4) for k, v in ext_info.get("dependencies", {}).items(): label_text = f"{k}" tag = v.get("tag", None) if tag: label_text += f"-{tag}" version = v.get("version", "*.*.*") if version: label_text += f" | v{version}" optional = v.get("optional", False) if optional: label_text += "(optional)" ui.Label(label_text, style_type_name_override="ExtensionDescription.Content") def destroy(self): pass @staticmethod def get_tab_name(): return "DEPENDENCIES" class PackagesPage(PageBase): def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): manager = omni.kit.app.get_app().get_extension_manager() package_info = ext_info.get("package") packages = manager.fetch_extension_packages(package_info.get("id")) with ui.VStack(height=0): ui.Label( "All available packages for version {} :".format(package_info["version"]), style_type_name_override="ExtensionDescription.Title", ) for p in packages: package_id = p["package_id"] with ui.CollapsableFrame(package_id, collapsed=True): with ui.HStack(): ui.Spacer(width=20) with ui.VStack(): build_package_info(manager.get_registry_extension_dict(package_id)) def destroy(self): pass @staticmethod def get_tab_name(): return "PACKAGES" class ExtTestPage(PageBase): def __init__(self): self.tab = ExtTestTab() def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): self.tab.build(ext_info) def destroy(self): self.tab.destroy() @staticmethod def get_tab_name(): return "TESTS" class ExtInfoWidget: pages = [OverviewPage, ChangelogPage, DependenciesPage, PackagesPage, ExtTestPage] current_page = 0 def __init__(self): # Widgets for tabs self.__tabs = [] self.__pages = [] # Put into frame to enable rebuilding of UI self._frame = ui.Frame() self._ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_change_sub = self._ext_manager.get_change_event_stream().create_subscription_to_pop( lambda *_: self._refresh_once_next_frame(), name="ExtInfoWidget" ) self._ext_graph = None self._version_menu = None self._selected_version = None self._selected_package_id = None # Refresh when new ext data fetched fetcher = get_ext_data_fetcher() def on_data_fetched(package_id): if self._selected_package_id == package_id: self._refresh_once_next_frame() fetcher.on_data_fetched_fn = on_data_fetched self.select_ext(None) self.page_tabs = [] self.update_tabs() self.set_show_graph_fn(None) def update_tabs(self): self.page_tabs = [] for page in self.pages: self.page_tabs.append(page()) def set_visible(self, visible): self._frame.visible = visible def select_ext(self, ext_summary): """Select extension to display info about. Can be None""" self._ext_summary = ext_summary self._selected_version = None self._selected_package_id = None self._refresh_once_next_frame() def _refresh(self): # Fetch all extensions for currently selected extension summary extensions = ( self._ext_manager.fetch_extension_versions(self._ext_summary.fullname) if self._ext_summary is not None else [] ) def _draw_empty_page(): with self._frame: ui.Label("Select an extension") if len(extensions) == 0: _draw_empty_page() return # If user hasn't yet changed the version to display summary advices which should be shown by default: if self._selected_version is None: self._selected_version = self._ext_summary.default_ext["version"] # Now actual extension is selected (including version). Get all the info for it selected_index = next( (i for i, v in enumerate(extensions) if v["version"][:4] == self._selected_version[:4]), None ) # If selected version is not available, select latest. That can happen if latest published is incompatible with # current target. In summaries it will show later version than the one you can select by default. if self._selected_version is not None and selected_index is None: selected_index = 0 self._selected_version = extensions[selected_index]["version"] if selected_index is None: _draw_empty_page() return selected_ext = extensions[selected_index] is_version_latest = selected_index == 0 ext_id = selected_ext["id"] package_id = selected_ext["package_id"] self._selected_package_id = package_id # If this extension is enabled or other version of this extension is enabled: any_version_enabled = any(ext["enabled"] for ext in extensions) ext_item, ext_info = build_ext_info(ext_id, package_id) # -> Tuple[ExtensionCommonInfo, dict]: # Get ext info either from local or remote index if not ext_info: _draw_empty_page() return # Gather more info by solving dependencies. When other version of this extension is already enabled solving is # known to fail because of conflict. It will always display a red icon then. # When we actually toggle it we will first turn off that version. So for that case do not solve extensions. # An alternative solution might be to manually build a list of all enabled extensions, but exclude current one. if not any_version_enabled: ext_item.solve_extensions() if not ext_item.is_local: fetcher = get_ext_data_fetcher() fetcher.fetch(ext_item) ext_path = ext_info.get("path", "") package_dict = ext_info.get("package", {}) docs_dict = ext_info.get("documentation", {}) if ext_item.is_local: # For local extensions add version to ext_id to make it more concrete (for later enabling etc.) name = package_dict.get("name") version = package_dict.get("version", None) ext_id = name + "-" + version if version else name name = package_dict.get("name", "") enabled = ext_item.enabled category = get_categories().get(ext_item.category) ################################################################################################################ # Build version selector menu def select_version(version): self._selected_version = version self._refresh_once_next_frame() self._version_menu = ui.Menu("Version") with self._version_menu: ui.MenuItem("Version(s)", enabled=False) ui.Separator() for i, e in enumerate(extensions): version = e["version"] version_str = version_to_str(version[:4]) color = 0xFF76B900 if selected_index == i else 0xFFC0C0C0 ui.MenuItem( version_str, checked=selected_index == i, checkable=True, style={"color": color, "margin": 0}, triggered_fn=lambda v=version: select_version(v), ) # Publish / Unpublish buttons if get_options().publishing: ui.Separator() ui.MenuItem("Publishing", enabled=False) ui.Separator() if ext_item.is_local: ui.MenuItem( "PUBLISH", triggered_fn=lambda ext_id=ext_id: self._ext_manager.publish_extension(ext_id) ) else: ui.MenuItem( "UNPUBLISH", triggered_fn=lambda ext_id=ext_id: self._ext_manager.unpublish_extension(ext_id) ) # Uninstall can_be_uninstalled = not ext_item.enabled and ext_item.location_tag == "INSTALLED" if can_be_uninstalled: ui.Separator() ui.MenuItem( "UNINSTALL", triggered_fn=lambda ext_id=ext_id: self._ext_manager.uninstall_extension(ext_id) ) ################################################################################################################ ################################################################################################################ def draw_icon_block(): # Icon with ui.HStack(width=ICON_ZONE_WIDTH): ui.Spacer() with ui.VStack(width=EXT_ICON_SIZE_LARGE[0]): ui.Spacer() ui.Image(ext_item.icon_path, height=EXT_ICON_SIZE_LARGE[1], style={"color": 0xFFFFFFFF}) ui.Spacer() ui.Spacer() ################################################################################################################ def draw_top_row_block(): with ui.HStack(): # Big button if not ext_item.is_local: if ext_info.get("state", {}).get("isPulled", False): ui.Button( "INSTALLING...", style_type_name_override="ExtensionDescription.DownloadingButton", width=100, height=30, ) else: def on_click(item=ext_item): asyncio.ensure_future(pull_extension_async(item, self._refresh_once_next_frame)) ui.Button( "INSTALL", style_type_name_override="ExtensionDescription.InstallButton", width=100, height=30, clicked_fn=on_click, ) else: can_update = not is_version_latest is_autoload_enabled = ext_controller.is_autoload_enabled(ext_item.id) if not ext_item.enabled and ext_item.is_toggle_blocked and is_autoload_enabled: def on_click(): omni.kit.app.get_app().restart() ui.Button( "RESTART APP", style_type_name_override="ExtensionDescription.RestartButton", clicked_fn=on_click, width=100, height=30, ) elif can_update: def on_click(ext_id=ext_id, switch_off_on=(enabled and not ext_item.is_toggle_blocked)): latest_ext = extensions[0] latest_ext_id = latest_ext["id"] latest_ext_version = latest_ext["version"] # If autoload for that one is enabled, move it to latest: if ext_controller.is_autoload_enabled(ext_id): ext_controller.toggle_autoload(ext_id, False) if check_can_be_toggled(latest_ext_id, for_autoload=True): ext_controller.toggle_autoload(latest_ext_id, True) # If extension is enabled, switch off to latest: if switch_off_on: toggle_extension(ext_id, False) toggle_extension(latest_ext_id, True) # Finally switch UI to show newest version select_version(latest_ext_version) ui.Button( "UPDATE", style_type_name_override="ExtensionDescription.UpdateButton", clicked_fn=on_click, width=100, height=30, ) else: ui.Button( "UP TO DATE", style_type_name_override="ExtensionDescription.UpToDateButton", width=100, height=30, ) # Version selector with ui.VStack(width=0): ui.Spacer() ui.Button(name="options", width=40, height=22, clicked_fn=self._version_menu.show) ui.Spacer() # Toggle ui.Spacer(width=15) ExtensionToggle(ext_item, with_label=True, show_install_button=False) # Autoload toggle with ui.HStack(): ui.Spacer(width=20) def toggle_autoload(value, ext_id=ext_id): if check_can_be_toggled(ext_id, for_autoload=True): ext_controller.toggle_autoload(ext_id, value) self._refresh_once_next_frame() SimpleCheckBox( ext_controller.is_autoload_enabled(ext_id), toggle_autoload, "AUTOLOAD", enabled=True ) ui.Spacer(width=20) def add_icon_button(name, on_click, tooltip=None): with ui.VStack(width=0): ui.Spacer() # cannot get style tooltip override to work, so force it here b = ui.Button( name=name, style_type_name_override="IconButton", width=23, height=18, clicked_fn=on_click, style={"Label": {"color": 0xFF444444}}, ) if tooltip: b.set_tooltip_fn(lambda *_: ui.Label(tooltip)) ui.Spacer() return b def add_open_button(url, name, prefer_vscode=False, tooltip=None): def on_click(url=url): open_in_vscode_if_enabled(url, prefer_vscode) b = add_icon_button(name, on_click) if not tooltip: tooltip = url b.set_tooltip_fn(lambda *_: ui.Label(tooltip)) # Doc button add_doc_link_button(ext_item, package_dict, docs_dict) ui.Spacer(width=8) if ext_item.is_local: # Extension "open folder" button ext_folder = os.path.dirname(ext_path) if os.path.isfile(ext_path) else ext_path add_open_button(ext_folder, name="OpenFolder") ui.Spacer(width=8) # Extension "open folder" button if is_vscode_installed(): add_open_button(ext_folder, name="OpenInVSCode", prefer_vscode=True, tooltip="Open in VSCode") ui.Spacer(width=8) # Extension "open config" button add_open_button(ext_info.get("configPath", ""), name="OpenConfig", prefer_vscode=True) ui.Spacer(width=8) # Extension export button def on_export(ext_id=ext_id): export_ext(ext_id) add_icon_button("Export", on_export, tooltip=f"Export {ext_info['package']['packageId']}") ################################################################################################################ def draw_extension_name_block(): with ui.HStack(): # Extension id ui.Label( ext_item.title, height=0, width=0, style_type_name_override="ExtensionDescription.Label", tooltip=ext_id, ) ui.Spacer() # Remove that separate rect block with ext_id? # with ui.ZStack(height=0, width=0): # ui.Rectangle(style_type_name_override="ExtensionDescription.Rectangle", name="Name") # ui.Label(ext_id, style_type_name_override="ExtensionDescription.Id", name="Name") ################################################################################################################ def draw_extension_description_block(): with ui.HStack(): ui.Label( clip_text(ext_item.description), height=0, width=50, style_type_name_override="ExtensionDescription.Label", ) ################################################################################################################ def draw_extension_version_block(): with ui.HStack(): if ext_item.version: ui.Label( "v" + ext_item.version, style_type_name_override="ExtensionDescription.Label", width=0, name="Version", ) def add_separator(): ui.Spacer(width=10) ui.Line(alignment=ui.Alignment.LEFT, style_type_name_override="ExtensionDescription.Label", width=0) ui.Spacer(width=10) add_separator() # Repository/Local text = f"Registry: {ext_item.provider_name}" if ext_item.provider_name else "Local" ui.Label(text, style_type_name_override="ExtensionDescription.Label", width=0) ui.Spacer() ################################################################################################################ def draw_category_block(): # Categoty Info and Icon with ui.HStack(width=CATEGORY_ZONE_WIDTH): ui.Spacer() with ui.VStack(width=CATEGORY_ICON_SIZE[0]): ui.Spacer() ui.Image(category["image"], width=CATEGORY_ICON_SIZE[0], height=CATEGORY_ICON_SIZE[1]) ui.Spacer(height=10) ui.Label(category["name"], alignment=ui.Alignment.CENTER) ui.Spacer() ui.Spacer() def draw_ext_source_block(): with ui.HStack(height=0): with ui.ZStack(height=32, width=0): ui.Image(style_type_name_override="ExtensionDescription.CommunityImage", width=148, height=32) with ui.HStack(width=0): ui.Spacer(width=52) name = ext_item.author_group.get_ui_name() ui.Label(name, style_type_name_override="ExtensionDescription.CommunityLabel") ui.Spacer(width=2) if ext_item.is_untrusted: with ui.ZStack(height=30): with ui.VStack(): ui.Spacer(height=2) ui.Rectangle(style_type_name_override="ExtensionDescription.UnverifiedRectangle") ui.Label( "UNVERIFIED", alignment=ui.Alignment.RIGHT_CENTER, style_type_name_override="ExtensionDescription.UnverifiedLabel", ) def draw_content_block(): def set_page(index): for i in self.__tabs: i.selected = False for i in self.__pages: i.visible = False self.__tabs[index].selected = True self.__pages[index].visible = True ExtInfoWidget.current_page = index ui.Spacer(height=10) with ui.HStack(height=20): tab_buttons = [] for index, page in enumerate(self.page_tabs): tab_btn = ui.Button( page.get_tab_name(), width=0, style_type_name_override="ExtensionDescription.Tab", clicked_fn=lambda i=index: set_page(i), ) tab_buttons.append(tab_btn) if index < len(self.page_tabs) - 1: ui.Line( style_type_name_override="ExtensionDescription.TabLine", alignment=ui.Alignment.H_CENTER, height=20, width=40, ) ui.Spacer() self.__tabs[:] = tab_buttons ui.Spacer(height=8) with ui.ZStack(): pages = [] for page_tab in self.page_tabs: page = ui.Frame(build_fn=lambda i=ext_info, e=ext_item, page_tab=page_tab: page_tab.build_tab(i, e)) pages.append(page) self.__pages[:] = pages set_page(ExtInfoWidget.current_page) # Default page ################################################################################################################ ################################################################################################################ # Build Actual UI Layout of all blocks with self._frame: with ui.ZStack(): ui.Rectangle(style_type_name_override="ExtensionDescription.Background") with ui.VStack(spacing=4): # Top Margin ui.Spacer(height=15) with ui.HStack(height=0, spacing=5): draw_icon_block() with ui.VStack(): draw_top_row_block() ui.Spacer(height=10) draw_extension_name_block() draw_extension_description_block() ui.Spacer(height=10) draw_extension_version_block() draw_category_block() # ui.Spacer(height=4) if ext_item.author_group != ExtAuthorGroup.NVIDIA: draw_ext_source_block() with ui.HStack(): ui.Spacer(width=10) # Content page with ui.VStack(): # Separator line ui.Line( height=0, alignment=ui.Alignment.BOTTOM, style_type_name_override="ExtensionDescription.TabLineFull", ) draw_content_block() ui.Spacer(width=10) ui.Spacer(height=5) def _refresh_once_next_frame(self): async def _delayed_refresh(weak_widget): await omni.kit.app.get_app().next_update_async() w = weak_widget() if w: w._refresh_task = None w._refresh() with contextlib.suppress(Exception): self._refresh_task.cancel() self._refresh_task = asyncio.ensure_future(_delayed_refresh(weakref.ref(self))) def set_show_graph_fn(self, fn: Callable): self._show_graph_fn = fn def _show_graph(self, ext_id): if self._show_graph_fn: self._show_graph_fn(ext_id) def destroy(self): self._ext_change_sub = None if self._ext_graph: self._ext_graph.destroy() self._ext_graph = None for page in self.page_tabs: page.destroy() # We want to None the instances also self._version_menu = None self.__tabs = [] self.__pages = []
34,417
Python
36.988962
120
0.498097
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_export_import.py
import asyncio import os import carb import carb.tokens import omni.kit.app from .common import get_omni_documents_path from .utils import get_setting # Store last user choosen folder for convenience between sessions RECENT_EXPORT_PATH_KEY = "/persistent/exts/omni.kit.window.extensions/recentExportPath" def _print_and_log(message): carb.log_info(message) print(message) async def _ask_user_for_path(is_export: bool, apply_button_label="Choose", title=None): app = omni.kit.app.get_app() manager = app.get_extension_manager() if not manager.is_extension_enabled("omni.kit.window.filepicker"): manager.set_extension_enabled("omni.kit.window.filepicker", True) await app.next_update_async() await app.next_update_async() from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.window.filepicker import FilePickerDialog done = False choosen_path = None def on_click_cancel(f, d): nonlocal done done = True if is_export: def on_click_open(f, d): nonlocal done, choosen_path choosen_path = d done = True filepicker = FilePickerDialog( title or "Choose Folder", allow_multi_selection=False, apply_button_label=apply_button_label, click_apply_handler=on_click_open, click_cancel_handler=on_click_cancel, enable_filename_input=False, ) else: def on_click_open(f, d): nonlocal done, choosen_path choosen_path = os.path.join(d, f) done = True def on_filter_zip_files(item: FileBrowserItem) -> bool: if not item or item.is_folder: return True return os.path.splitext(item.path)[1] == ".zip" filepicker = FilePickerDialog( title or "Choose Extension Zip Archive", allow_multi_selection=False, apply_button_label="Import", click_apply_handler=on_click_open, click_cancel_handler=on_click_cancel, item_filter_options=[("*.zip", ".zip Archives (*.zip)")], item_filter_fn=on_filter_zip_files, ) recent_path = get_setting(RECENT_EXPORT_PATH_KEY, None) if not recent_path: recent_path = get_omni_documents_path() filepicker.show(path=recent_path) while not done: await app.next_update_async() filepicker.hide() filepicker.destroy() if choosen_path: recent_path = os.path.dirname(choosen_path) if os.path.isfile(choosen_path) else choosen_path carb.settings.get_settings().set(RECENT_EXPORT_PATH_KEY, recent_path) return choosen_path async def _export(ext_id: str): output = await _ask_user_for_path(is_export=True, apply_button_label="Export") if output: app = omni.kit.app.get_app() manager = app.get_extension_manager() archive_path = manager.pack_extension(ext_id, output) app.print_and_log(f"Extension: '{ext_id}' was exported to: '{archive_path}'") async def _import(): archive_path = await _ask_user_for_path(is_export=False, apply_button_label="Import") # Registry Local Cache Folder registry_cache = get_setting("/app/extensions/registryCacheFull", None) if not registry_cache: carb.log_error("Can't import extension, registry cache path is not set.") return if archive_path: omni.ext.unpack_extension(archive_path, registry_cache) omni.kit.app.get_app().print_and_log(f"Extension: '{archive_path}' was imported to: '{registry_cache}'") def export_ext(ext_id: str): asyncio.ensure_future(_export(ext_id)) def import_ext(): asyncio.ensure_future(_import())
3,771
Python
29.176
112
0.641474
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_graph_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. # import os from collections import defaultdict from typing import List, Tuple import carb import omni.kit.app import omni.ui as ui from omni.kit.widget.graph import GraphNodeDescription, GraphPortDescription from omni.kit.widget.graph.abstract_graph_node_delegate import AbstractGraphNodeDelegate from omni.kit.widget.graph.graph_model import GraphModel from omni.kit.widget.graph.graph_view import GraphView from .utils import ext_id_to_fullname # pylint: disable=property-with-parameters # Colors & Style BACKGROUND_COLOR = 0xFF34302A BORDER_DEFAULT = 0xFF232323 CONNECTION = 0xFF80C280 NODE_BACKGROUND = 0xFF141414 PLUGINS_COLOR = 0xFFFFE3C4 LIBRARIES_COLOR = 0xAA44EBE7 MODULES_COLOR = 0xFFAAE3C4 GRAPH_STYLE = { "Graph": {"background_color": BACKGROUND_COLOR}, "Graph.Connection": {"color": CONNECTION, "background_color": CONNECTION, "border_width": 2.0}, # Node "Graph.Node.Background": {"background_color": NODE_BACKGROUND}, "Graph.Node.Border": {"background_color": BORDER_DEFAULT}, # Header "Graph.Node.Header.Label": {"color": 0xFFEEEEEE, "margin_height": 5.0, "font_size": 14.0}, } # Constants MARGIN_WIDTH = 7.5 MARGIN_TOP = 20.0 MARGIN_BOTTOM = 25.0 BORDER_THICKNESS = 3.0 HEADER_HEIGHT = 25.0 MIN_WIDTH = 180.0 CONNECTION_CURVE = 60 class GraphNodeDelegate(AbstractGraphNodeDelegate): """ The delegate with the Omniverse design. """ def __init__(self, scale_factor=1.0): self._manager = omni.kit.app.get_app_interface().get_extension_manager() self._scale_factor = scale_factor def __scale(self, value): """Return the value multiplied by global scale multiplier""" return value * self._scale_factor def set_scale_factor(self, scale_factor): """Replace scale factor""" self._scale_factor = scale_factor def node_background(self, model, node_desc: GraphNodeDescription): """Called to create widgets of the node background""" # Computed values left_right_offset = MARGIN_WIDTH - BORDER_THICKNESS * 0.5 # Draw a rectangle and a top line with ui.HStack(): # Left offset ui.Spacer(width=self.__scale(left_right_offset)) with ui.VStack(): ui.Spacer(height=self.__scale(MARGIN_TOP)) # The node body with ui.ZStack(): # This trick makes min width ui.Spacer(width=self.__scale(MIN_WIDTH)) # Build outer rectangle ui.Rectangle(style_type_name_override="Graph.Node.Border") # Build inner rectangle with ui.VStack(): ui.Spacer(height=self.__scale(HEADER_HEIGHT)) with ui.HStack(): ui.Spacer(width=self.__scale(BORDER_THICKNESS)) ui.Rectangle(style_type_name_override="Graph.Node.Background") ui.Spacer(width=self.__scale(BORDER_THICKNESS)) ui.Spacer(height=self.__scale(BORDER_THICKNESS)) ui.Spacer(height=self.__scale(MARGIN_BOTTOM)) # Right offset ui.Spacer(width=self.__scale(left_right_offset)) def node_header_input(self, model, node_desc: GraphNodeDescription): """Called to create the left part of the header that will be used as input when the node is collapsed""" with ui.ZStack(width=self.__scale(8)): if node_desc.connected_target: # Circle that shows that the port is a target for the connection ui.Circle( radius=self.__scale(4), size_policy=ui.CircleSizePolicy.FIXED, style_type_name_override="Graph.Connection", alignment=ui.Alignment.RIGHT_CENTER, ) def node_header_output(self, model, node_desc: GraphNodeDescription): """Called to create the right part of the header that will be used as output when the node is collapsed""" with ui.ZStack(width=self.__scale(8)): if node_desc.connected_source: # Circle that shows that the port is a source for the connection ui.Circle( radius=self.__scale(4), size_policy=ui.CircleSizePolicy.FIXED, style_type_name_override="Graph.Connection", alignment=ui.Alignment.LEFT_CENTER, ) def node_header(self, model, node_desc: GraphNodeDescription): """Called to create widgets of the top of the node""" item = model[node_desc.node].item def build_list(files, title, color): if len(files) > 0: style = {"CollapsableFrame": {"color": color, "background_color": NODE_BACKGROUND}} with ui.CollapsableFrame(title, collapsed=False, style=style): with ui.VStack(height=0): for p in files: ui.Label(" - " + os.path.basename(p), height=self.__scale(20)).set_tooltip(p) # Draw the node name and a bit of space with ui.VStack(height=0): ui.Spacer(height=self.__scale(18)) with ui.HStack(height=0): ui.Spacer(width=self.__scale(18)) title = item.id ui.Label(title, style_type_name_override="Graph.Node.Header.Label") build_list(item.plugins, "carb plugins", PLUGINS_COLOR) build_list(item.libraries, "shared libraries", LIBRARIES_COLOR) build_list(item.modules, "python modules", MODULES_COLOR) ui.Spacer(height=self.__scale(55)) def node_footer(self, model, node_desc: GraphNodeDescription): pass def port_input(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription): pass def port_output(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription): pass def port(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription): pass def connection(self, model, source, target): """Called to create the connection between ports""" # If the connection is reversed, we need to mirror tangents connection_direction_is_same_as_flow = source.level >= target.level reversed_tangent = -1.0 if connection_direction_is_same_as_flow else 1.0 ui.FreeBezierCurve( target.widget, source.widget, start_tangent_width=ui.Percent(CONNECTION_CURVE * reversed_tangent), end_tangent_width=ui.Percent(-CONNECTION_CURVE * reversed_tangent), style_type_name_override="Graph.Connection", ) class ExtGraphItem: def __init__(self, manager, ext_id): info = manager.get_extension_dict(ext_id) # Extension dependencies: self.deps = info.get("state/dependencies", []) self.port_deps = [d + "/out" for d in self.deps] # Extension useful info (id, version, plugins, modules etc) state_dict = info.get("state", {}) native_dict = state_dict.get("native", {}) self.id = ext_id self.plugins = native_dict.get("plugins", []) self.libraries = native_dict.get("libraries", []) self.modules = state_dict.get("python", {}).get("modules", []) def __lt__(self, other): return self.id < other.id class Model(GraphModel): def __init__(self, ext_id: str = None): super().__init__() # build graph out of enabled extensions manager = omni.kit.app.get_app_interface().get_extension_manager() exts = manager.get_extensions() enabled_exts = [e["id"] for e in exts if e["enabled"]] self._nodes = {ext_id: ExtGraphItem(manager, ext_id) for ext_id in enabled_exts} # If ext_id was passed filter out extension that are not reachable from this one. To show only its graph: self._root_ext_id = ext_id if self._root_ext_id: self._filter_out_unreachable_nodes(ext_id) def _filter_out_unreachable_nodes(self, ext_id): visited = set() q = [] root = self._nodes.get(ext_id, None) if not root: carb.log_error(f"Failure to filter dep graph, can't find ext node: {ext_id}") return q.append(root) visited.add(root) while len(q) > 0: node = q.pop() for d in node.deps: child = self._nodes[d] if child not in visited: visited.add(child) q.append(child) self._nodes = {ext_id: item for ext_id, item in self._nodes.items() if item in visited} @property def expansion_state(self, item=None): return self.ExpansionState.CLOSED @property def nodes(self, item=None): return {e.id for e in self._nodes.values()} @property def name(self, item=None): return self._nodes[item].id @property def item(self, item=None): return self._nodes[item] @property def ports(self, item=None): return [item + "/in", item + "/out"] @property def inputs(self, item): if item.endswith("/in"): item = self._nodes.get(item[:-3], None) return item.port_deps if item else [] return None @property def outputs(self, item): outputs = [] if item.endswith("/out") else None return outputs def copy_as_graphviz(self): output = "" output += """ digraph Extensions { graph [outputMode=nodesfirst rankdir=LR] node [shape=box style=filled] """ for _, node in self._nodes.items(): label = node.id + "\\n-------------------\\n" def gen(files, title): if len(files) == 0: return "" return f"{title}:\\l" + "".join([f" * {os.path.basename(f)}\\l" for f in files]) label += gen(node.plugins, "plugins") label += gen(node.libraries, "libraries") label += gen(node.modules, "modules") output += f'\t\t"{node.id}" [label="{label}"]\n' for d in node.deps: output += f'\t\t"{d}" -> "{node.id}"\n' output += "}\n" print(output) omni.kit.clipboard.copy(output) class ExtsListView: def __init__(self, model, ext_id): self._model = model self._ext_id = ext_id # gather reverse dependencies from both local extensions and registry extensions registry_exts = [] unique_registry_exts = set() manager = omni.kit.app.get_app_interface().get_extension_manager() for ext in manager.get_extensions(): ext_name = ext["name"] registry_exts.append(ext) unique_registry_exts.add(ext_name) for ext in manager.get_registry_extensions(): ext_id = ext["id"] ext_name = ext["name"] if ext_name not in unique_registry_exts: # grab latest version of each extension versions = manager.fetch_extension_versions(ext_name) if len(versions) > 0 and versions[0]["id"] == ext_id: registry_exts.append(ext) unique_registry_exts.add(ext_name) self._reverse_dep = self._get_reverse_dependencies(manager, registry_exts) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.ZStack(): ui.Rectangle(style_type_name_override="ExtensionDescription.ContentBackground") with ui.HStack(): ui.Spacer(width=10) with ui.VStack(height=0): ui.Spacer(height=10) direct = self._model._nodes[self._ext_id].deps if self._ext_id else () ui.Label(f"- Direct Dependencies ({len(direct)}):", height=20) for ext in sorted(direct): ui.Label(ext) ui.Spacer(height=10) indirect = [ node for node in self._model._nodes.values() if node.id not in direct and node.id != self._ext_id ] ui.Label(f"- All Indirect Dependencies ({len(indirect)}):", height=20) for node in sorted(indirect): ui.Label(node.id) ui.Spacer(width=10) with ui.VStack(height=10): ui.Spacer(height=10) direct = self._reverse_dep[0] ui.Label(f"- Direct Reverse Dependencies ({len(direct)}):", height=20) for item in sorted(direct): ui.Label(item) ui.Spacer(height=10) indirect = [ ext for ext in self._reverse_dep[1] if ext not in direct and ext != ext_id_to_fullname(self._ext_id) ] ui.Label(f"- All Indirect Reverse Dependencies ({len(indirect)}):", height=20) for item in sorted(indirect): ui.Label(item) def _get_reverse_dependencies(self, manager, exts) -> Tuple[List, List]: dependents = defaultdict(set) unique_exts_first_order = set() unique_exts = set() max_depth = 40 for ext in exts: ext_id = ext["id"] ext_name = ext["name"] info = manager.get_extension_dict(ext_id) if not info: info = manager.get_registry_extension_dict(ext_id) if info: deps = info.get("dependencies", []) for dep_name in deps: dependents[dep_name].add(ext_name) def recurse(ext_name: str, cur_depth: int): if cur_depth < max_depth: if cur_depth == 1: unique_exts_first_order.add(ext_name) unique_exts.add(ext_name) for dep_name in dependents[ext_name]: recurse(dep_name, cur_depth + 1) if self._ext_id: info = manager.get_extension_dict(self._ext_id) ext_name = info.get("package/name", "") recurse(ext_name, 0) # returns a tuple, 1st order deps only and all reverse deps return list(unique_exts_first_order), list(unique_exts) class ExtsGraphWidget: """Extensions graph window""" def __init__(self, ext_id): self._ext_id = ext_id self._view_index = 0 with ui.ZStack(): self._delegate = GraphNodeDelegate() self._model = Model(self._ext_id) # TODO(anov): remove pan_x, pan_y hardcoded after graph auto align fixed. self._graph_frame = ui.Frame() raster_nodes = carb.settings.get_settings().get("/exts/omni.kit.window.extensions/raster_nodes") with self._graph_frame: self._graph_view = GraphView( delegate=self._delegate, model=self._model, style=GRAPH_STYLE, zoom=0.5, pan_x=1000, pan_y=400, raster_nodes=raster_nodes, ) self._list_frame = ui.Frame() with self._list_frame: self._list_view = ExtsListView(self._model, self._ext_id) self._list_frame.visible = False with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() with ui.VStack(width=200, height=0, content_clipping=True): ui.Button( "Toggle View", width=200, height=20, mouse_pressed_fn=lambda *_: self._toggle_view(), ) ui.Button( "Copy as Graphviz .dot", width=200, height=20, mouse_pressed_fn=lambda *_: self._model.copy_as_graphviz(), ) ui.Spacer(width=10) ui.Spacer(height=10) def _toggle_view(self): self._view_index = (self._view_index + 1) % 2 self._list_frame.visible = self._view_index == 1 self._graph_frame.visible = self._view_index == 0 def destroy(self): self._delegate = None self._model = None self._list_frame = None self._list_view = None self._graph_frame = None self._graph_view = None class ExtsGraphWindow: """Extensions graph window""" def __init__(self): self._frame = ui.Frame() self._frame.visible = False self._graph_widget = None self.select_ext(None) manager = omni.kit.app.get_app_interface().get_extension_manager() change_stream = manager.get_change_event_stream() self._change_script_sub = change_stream.create_subscription_to_pop( lambda _: self._refresh(), name="ExtsGraphWindow watch for exts" ) def destroy(self): self._frame = None if self._graph_widget: self._graph_widget.destroy() self._change_script_sub = None def _refresh(self): self.set_visible(self._frame.visible) def select_ext(self, ext_id): self._ext_id = ext_id def set_visible(self, visible: bool): if self._frame.visible == visible: if visible: # recreate if already shown self.set_visible(False) else: # if not shown already -> do nothing. return if not visible: self._frame.visible = False else: self._build() self._frame.visible = True def _build(self): with self._frame: if self._graph_widget: self._graph_widget.destroy() self._graph_widget = ExtsGraphWidget(self._ext_id)
19,076
Python
35.89942
114
0.551478
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/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. # # pylint: disable=attribute-defined-outside-init, protected-access import asyncio import contextlib import weakref from typing import Callable import omni.ext import omni.kit.app import omni.kit.ui import omni.ui as ui from . import common, ext_controller, ext_info_widget from .exts_list_widget import ExtsListWidget from .utils import get_setting from .window import ExtsWindow MENU_PATH = "Window/Extensions" _ext_instance = None def show_window(value: bool): """Show/Hide Extensions window""" if _ext_instance: _ext_instance.show_window(value) def get_instance() -> "weakref.ReferenceType[ExtsWindowExtension]": return weakref.ref(_ext_instance) class ExtsWindowExtension(omni.ext.IExt): """The entry point exts 2.0 window""" def on_startup(self, ext_id): global _ext_instance _ext_instance = self app = omni.kit.app.get_app() common.EXT_ROOT = app.get_extension_manager().get_extension_path(ext_id) self._window = None # # Add to menu - will fail if the editor is not loaded self._menu = None # Throwing is ok, but leaves self._menu undefined with contextlib.suppress(Exception): self._menu = omni.kit.ui.get_editor_menu().add_item( MENU_PATH, lambda _, v: self.show_window(v), toggle=True, value=False, priority=100 ) ui.Workspace.set_show_window_fn( "Extensions", lambda value: self.show_window(value), # pylint: disable=unnecessary-lambda ) # Start enabling autoloadable extensions: asyncio.ensure_future(ext_controller.autoload_extensions()) # Auto show window, for convenience show = get_setting("/exts/omni.kit.window.extensions/showWindow", False) if self._menu: omni.kit.ui.get_editor_menu().set_value(MENU_PATH, show) if show: self.show_window(True) # Some events trigger rebuild of a whole window bus = app.get_message_bus_event_stream() self._subs = [] def on_rebuild(_): if self._window: self.show_window(False) self.show_window(True) self._subs.append(bus.create_subscription_to_pop_by_type(common.COMMUNITY_TAB_TOGGLE_EVENT, on_rebuild)) def on_shutdown(self): global _ext_instance _ext_instance = None self.show_window(False) self._menu = None self._subs = None def show_window(self, value): if value: def on_visibility_changed(visible): omni.kit.ui.get_editor_menu().set_value(MENU_PATH, visible) self._window = ExtsWindow(on_visibility_changed if self._menu else None) else: if self._window: self._window.destroy() self._window = None # -------------------------------------------------------------------------------------------------------------- # API to add a new tab to the extension info pane @classmethod def refresh_extension_info_widget(cls): if _ext_instance._window and _ext_instance._window._ext_info_widget: _ext_instance._window._ext_info_widget.update_tabs() _ext_instance._window._ext_info_widget._refresh() @classmethod def add_tab_to_info_widget(cls, tab: ext_info_widget.PageBase): ext_info_widget.ExtInfoWidget.pages.append(tab) cls.refresh_extension_info_widget() @classmethod def remove_tab_from_info_widget(cls, tab: ext_info_widget.PageBase): if tab in ext_info_widget.ExtInfoWidget.pages: ext_info_widget.ExtInfoWidget.pages.remove(tab) ext_info_widget.ExtInfoWidget.current_page = 0 cls.refresh_extension_info_widget() # -------------------------------------------------------------------------------------------------------------- # API to add a searchable keyword @classmethod def refresh_search_items(cls): if _ext_instance._window and _ext_instance._window._exts_list_widget: _ext_instance._window._exts_list_widget.rebuild_filter_menu() _ext_instance._window._exts_list_widget._model.refresh_all() @classmethod def add_searchable_keyword(cls, keyword: str, description: str, filter_on_keyword: Callable, clear_cache: Callable): ExtsListWidget.searches[keyword] = (description, filter_on_keyword, clear_cache) cls.refresh_search_items() @classmethod def remove_searchable_keyword(cls, keyword_to_remove: str): if keyword_to_remove in ExtsListWidget.searches: del ExtsListWidget.searches[keyword_to_remove] cls.refresh_search_items()
5,156
Python
34.565517
120
0.63014
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/__init__.py
# flake8: noqa from .ext_commands import ToggleExtension from .ext_components import SimpleCheckBox from .extension import ExtsWindowExtension, get_instance
157
Python
30.599994
56
0.840764
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_controller.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. # from functools import lru_cache import carb import carb.settings import omni.kit.app from .utils import ext_id_to_fullname, set_default_and_get_setting DEFERRED_LOAD_SETTING_KEY = "/exts/omni.kit.window.extensions/deferredLoadExts" AUTOLOAD_SETTING_KEY = "/persistent/app/exts/enabled" FEATURED_EXT_SETTING_KEY = "/exts/omni.kit.window.extensions/featuredExts" WAIT_FRAMES_SETTING_KEY = "/exts/omni.kit.window.extensions/waitFramesBetweenEnable" _autoload_exts = None _startup_exts = set() _startup_ext_ids = set() def _get_autoload_exts(): global _autoload_exts if _autoload_exts is None: _autoload_exts = set(set_default_and_get_setting(AUTOLOAD_SETTING_KEY, [])) return _autoload_exts @lru_cache() def _get_featured_exts(): return set(set_default_and_get_setting(FEATURED_EXT_SETTING_KEY, [])) def _save(): exts = _get_autoload_exts() carb.settings.get_settings().set(AUTOLOAD_SETTING_KEY, list(exts)) def toggle_autoload(ext_id: str, toggle: bool): exts = _get_autoload_exts() if toggle: # Disable all other versions ext_manager = omni.kit.app.get_app().get_extension_manager() extensions = ext_manager.fetch_extension_versions(ext_id_to_fullname(ext_id)) for e in extensions: exts.discard(e["id"]) exts.add(ext_id) else: exts.discard(ext_id) _save() def is_autoload_enabled(ext_id: str) -> bool: exts = _get_autoload_exts() return ext_id in exts def is_startup_ext(ext_name: str) -> bool: return ext_name in _startup_exts def is_startup_ext_id(ext_id: str) -> bool: return ext_id in _startup_ext_ids def is_featured_ext(ext_name: str) -> bool: return ext_name in _get_featured_exts() def are_featured_exts_enabled() -> bool: return len(_get_featured_exts()) > 0 async def autoload_extensions(): # Delay for one update until everything else of a core app is loaded await omni.kit.app.get_app().next_update_async() ext_manager = omni.kit.app.get_app().get_extension_manager() wait_frames = set_default_and_get_setting(WAIT_FRAMES_SETTING_KEY, 1) # Enable all deferered extension, one by one. Wait for next frame inbetween each. for ext_id in set_default_and_get_setting(DEFERRED_LOAD_SETTING_KEY, []): ext_manager.set_extension_enabled_immediate(ext_id, True) for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() # Build list of startup extensions (those that were started by this point) _autoload_exts = _get_autoload_exts() for ext_info in ext_manager.get_extensions(): if ext_info["enabled"] and ext_info["id"] not in _autoload_exts: _startup_exts.add(ext_info["name"]) _startup_ext_ids.add(ext_info["id"])
3,228
Python
31.29
85
0.696097
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/utils.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. # # pylint: disable=protected-access, access-member-before-definition import asyncio import contextlib import glob import os import platform import shutil import subprocess from functools import lru_cache from typing import Callable, Tuple import carb import carb.dictionary import carb.settings import omni.kit.commands def call_once_with_delay(fn: Callable, delay: float): """Call function once after `delay` seconds. If this function called again before `delay` is passed the timer gets reset.""" async def _delayed_refresh(): await asyncio.sleep(delay) fn() with contextlib.suppress(Exception): fn._delay_call_task.cancel() fn._delay_call_task = asyncio.ensure_future(_delayed_refresh()) @lru_cache() def is_windows(): return platform.system().lower() == "windows" def run_process(args): print(f"running process: {args}") kwargs = {"close_fds": False} if is_windows(): kwargs["creationflags"] = subprocess.CREATE_NEW_CONSOLE | subprocess.CREATE_NEW_PROCESS_GROUP subprocess.Popen(args, **kwargs) # pylint: disable=consider-using-with def version_to_str(version: Tuple[int, int, int, str, str]) -> str: """Generate string `0.0.0-tag+tag`""" delimiters = ("", ".", ".", "-", "+") return "".join(f"{d}{v}" for d, v in zip(delimiters, version) if str(v) and v is not None) def ext_id_to_fullname(ext_id: str) -> str: return omni.ext.get_extension_name(ext_id) def ext_id_to_name_version(ext_id: str) -> Tuple[str, str]: """Convert 'omni.foo-tag-1.2.3' to 'omni.foo-tag' and '1.2.3'""" a, b, *rest = ext_id.split("-") if b: if not b[0:1].isdigit(): return f"{a}-{b}", "-".join(rest) return a, "-".join([b] + rest) return a, "" def get_ext_info_dict(ext_manager, ext_info) -> Tuple[carb.dictionary.Item, bool]: ext_dict = ext_manager.get_extension_dict(ext_info["id"]) if ext_dict is not None: return (ext_dict, True) return (ext_manager.get_registry_extension_dict(ext_info["package_id"]), False) def get_setting(path, default=None): setting = carb.settings.get_settings().get(path) return setting if setting is not None else default def set_default_and_get_setting(path, default=None): settings = carb.settings.get_settings() settings.set_default(path, default) return settings.get(path) def clip_text(s, max_count=80): return s[:max_count] + ("..." if len(s) > max_count else "") def open_file_using_os_default(path: str): if platform.system() == "Darwin": # macOS subprocess.call(("open", path)) elif platform.system() == "Windows": # Windows os.startfile(path) # noqa: PLE1101 else: # linux variants subprocess.call(("xdg-open", path)) def open_url(url): import webbrowser webbrowser.open(url) def open_using_os_default(path: str): if os.path.isfile(path): open_file_using_os_default(path) else: # open dir import webbrowser webbrowser.open(path) def open_in_vscode(path: str): subprocess.call(["code", path], shell=is_windows()) @lru_cache() def is_vscode_installed(): try: cmd = ["code", "--version"] return subprocess.call(cmd, shell=is_windows(), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) == 0 except FileNotFoundError: return False def _search_path_entry_up(path, entry, max_steps_up=3): for _ in range(0, max_steps_up + 1): if os.path.exists(os.path.join(path, entry)): return os.path.normpath(path) new_path = os.path.normpath(os.path.join(path, "..")) if new_path == path: break path = new_path return None def open_in_vscode_if_enabled(path: str, prefer_vscode: bool = True): if prefer_vscode and is_vscode_installed(): # Search for .vscode folder few folders up to open project instead of just extension # 5 steps is enough for '_build/window/release/exts/omni.foo' for instance if os.path.isdir(path): path = _search_path_entry_up(path, ".vscode", max_steps_up=5) or path open_in_vscode(path) else: open_using_os_default(path) def copy_text(text): omni.kit.clipboard.copy(text) def cleanup_folder(path): try: for p in glob.glob(f"{path}/*"): if os.path.isdir(p): if omni.ext.is_link(p): omni.ext.destroy_link(p) else: shutil.rmtree(p) else: os.remove(p) except Exception as exc: # pylint: disable=broad-except carb.log_warn(f"Unable to clean up files: {path}: {exc}") @lru_cache() def get_extpath_git_ext(): try: import omni.kit.extpath.git as git_ext return git_ext except ImportError: return None async def _load_popup_dialog_ext(): app = omni.kit.app.get_app() manager = app.get_extension_manager() if not manager.is_extension_enabled("omni.kit.window.popup_dialog"): manager.set_extension_enabled("omni.kit.window.popup_dialog", True) await app.next_update_async() await app.next_update_async() async def show_ok_popup(title, message, **dialog_kwargs): await _load_popup_dialog_ext() from omni.kit.window.popup_dialog import MessageDialog app = omni.kit.app.get_app() done = False def on_click(d): nonlocal done done = True dialog_kwargs.setdefault("disable_cancel_button", True) dialog = MessageDialog(title=title, message=message, ok_handler=on_click, **dialog_kwargs) dialog.show() while not done: await app.next_update_async() dialog.destroy() async def show_user_input_popup(title, label, default): await _load_popup_dialog_ext() from omni.kit.window.popup_dialog import InputDialog app = omni.kit.app.get_app() value = None def on_click(dialog: InputDialog): nonlocal value value = dialog.get_value() dialog = InputDialog( message=title, pre_label=label, post_label="", default_value=default, ok_handler=on_click, ok_label="Ok", ) dialog.show() while not value: await app.next_update_async() dialog.destroy() return value
6,773
Python
26.425101
113
0.641223
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_components.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 asyncio import sys from typing import Callable, Dict import omni.kit.app import omni.ui as ui from .common import ExtensionCommonInfo, ExtSource, build_doc_urls, pull_extension_async, toggle_extension from .styles import get_style from .utils import get_setting, open_url, run_process class ExtensionToggle: def __init__(self, item: ExtensionCommonInfo, with_label=False, show_install_button=True, refresh_cb=None): with ui.HStack(width=0, style=get_style(self)): if item.is_app: def on_click(is_local=item.is_local, ext_id=item.id): manager = omni.kit.app.get_app().get_extension_manager() if not is_local: manager.pull_extension(ext_id) args = [sys.argv[0]] ext_info = manager.get_extension_dict(ext_id) if ext_info.get("isKitFile", False): args.append(ext_info["path"]) else: args.extend(["--enable", ext_id]) # Pass all exts folders for folder in get_setting("/app/exts/folders", default=[]): args.extend(["--ext-folder", folder]) run_process(args) with ui.VStack(): ui.Spacer() ui.Button("LAUNCH", name="LaunchButton", width=60, height=20, clicked_fn=on_click) ui.Spacer() elif not item.is_local: if not show_install_button: return with ui.VStack(): ui.Spacer() if item.is_pulled: ui.Button("INSTALLING...", name="DownloadingButton", width=60, height=20) else: def on_click(item=item): asyncio.ensure_future(pull_extension_async(item)) ui.Button("INSTALL", name="InstallButton", width=60, height=20, clicked_fn=on_click) ui.Spacer() else: if item.failed: with ui.VStack(): ui.Spacer() # OM-90861: Add tooltip for extension depdency solve failure tooltip = "Failed to solve extension dependency." if item.solver_error: tooltip += f"\nError: {item.solver_error}" ui.Image(name="Failed", width=26, height=26, tooltip=tooltip) ui.Spacer() with ui.VStack(): ui.Spacer() name = "clickable" tb = ui.ToolButton(image_width=39, image_height=18, height=0, name=name) tb.model.as_bool = item.enabled def toggle(model, ext_id=item.id, fullname=item.fullname): enable = model.get_value_as_bool() # If we about to enable, toggle other versions if enabled if enable: manager = omni.kit.app.get_app().get_extension_manager() extensions = manager.fetch_extension_versions(fullname) for e in extensions: if e["enabled"] and e["id"] != ext_id: toggle_extension(e["id"], False) if not toggle_extension(ext_id, enable=enable): model.as_bool = not enable if item.is_toggle_blocked: tb.name = "nonclickable" # TODO(anov): how to make ToolButton disabled? def block_change(model, enabled=item.enabled): model.as_bool = enabled tb.model.add_value_changed_fn(block_change) else: tb.model.add_value_changed_fn(toggle) ui.Spacer() if with_label: ui.Spacer(width=8) if item.enabled: ui.Label("ENABLED", name="EnabledLabel") else: ui.Label("DISABLED", name="DisabledLabel") class SimpleCheckBox: def __init__(self, checked: bool, on_checked_fn: Callable, text: str = None, model=None, enabled=True): with ui.HStack(width=0, style=get_style(self)): with ui.VStack(width=0): ui.Spacer() if enabled: tb = ui.ToolButton(image_width=39, image_height=18, height=0, model=model) tb.model.as_bool = checked tb.model.add_value_changed_fn(lambda model: on_checked_fn(model.get_value_as_bool())) else: name = "disabled_checked" if checked else "disabled_unchecked" ui.Image(width=39, height=18, name=name) ui.Spacer() if text: ui.Label(text) class SearchWidget: """String field with a label overlay to type search string into.""" def __init__(self, on_search_fn: Callable[[str], None]): def clear_text(widget): widget.model.set_value("") widget.focus_keyboard() def field_changed(field_string): self._clear_button.visible = len(field_string) > 0 on_search_fn(field_string) self.clear_filters() with ui.ZStack(height=0, style=get_style(self)): # Search filed with ui.HStack(): field_widget = ui.StringField(style_type_name_override="SearchField") self._search = field_widget.model ui.Rectangle(width=20, style={"background_color": 0xFF212121, "border_radius": 0.0}) with ui.HStack(): ui.Spacer() self._clear_button = ui.Button( "", name="ClearSearch", width=16, alignment=ui.Alignment.CENTER, clicked_fn=lambda w=field_widget: clear_text(w), visible=False, ) # The label on the top of the search field with ui.HStack(): ui.Spacer(width=5) with ui.VStack(width=0): ui.Spacer() self._search_icon = ui.Image(name="SearchIcon", width=12, height=13) ui.Spacer() self._search_label = ui.Label("Search", style={"margin_width": 4}, name="Search") # The filtering logic self._begin_filter_sub = self._search.subscribe_begin_edit_fn(lambda _: self._toggle_visible(False)) self._edit_filter_sub = self._search.subscribe_value_changed_fn(lambda m: field_changed(m.as_string)) self._end_filter_sub = self._search.subscribe_end_edit_fn(lambda m: self._toggle_visible(not m.as_string)) def _toggle_visible(self, visible): self._search_label.visible = visible self._search_icon.visible = visible def set_text(self, text): self._search.as_string = text self._toggle_visible(False) def get_text(self): return self._search.as_string def get_filters(self): return self._filters def toggle_filter(self, filter_to_toggle): if filter_to_toggle in self._filters: self._filters.remove(filter_to_toggle) else: self._filters.append(filter_to_toggle) def clear_filters(self): self._filters = [] def destroy(self): self._begin_filter_sub = None self._edit_filter_sub = None self._end_filter_sub = None class ExtSourceSelector: def __init__(self, on_selected_fn): self._on_selected_fn = None self._buttons = {} with ui.HStack(height=20): for index, source in enumerate(ExtSource): ui.Spacer() tab_btn = ui.Button( source.get_ui_name(), width=0, style_type_name_override="ExtensionDescription.Tab", clicked_fn=lambda s=source: self.set_tab(s), ) self._buttons[source] = tab_btn if index < len(ExtSource) - 1: ui.Spacer() ui.Line( style_type_name_override="ExtensionDescription.TabLine", alignment=ui.Alignment.H_CENTER, height=20, width=40, ) ui.Spacer() self.set_tab(ExtSource.NVIDIA) self._on_selected_fn = on_selected_fn def set_badge_number(self, source, number): self._buttons[source].text = source.get_ui_name() + f" ({number})" def set_tab(self, source): for b in self._buttons.values(): b.selected = False self._buttons[source].selected = True if self._on_selected_fn: self._on_selected_fn(source) def add_icon_button(name, on_click): with ui.VStack(width=0): ui.Spacer() b = ui.Button(name=name, style_type_name_override="IconButton", width=23, height=18, clicked_fn=on_click) ui.Spacer() return b def add_doc_link_button(ext_item: ExtensionCommonInfo, package_dict: Dict, docs_dict: Dict): # Create a button, but hide. button = None with ui.VStack(width=0): ui.Spacer() button = ui.Button( name="OpenDoc", style_type_name_override="IconButton", width=23, height=18, style={"Label": {"color": 0xFF444444}}, ) ui.Spacer() button.visible = False def check_url_sync(url): import urllib try: return urllib.request.urlopen(url).getcode() == 200 except urllib.error.HTTPError: return False async def check_urls(doc_urls): for doc_url in doc_urls: # run sync code on other thread not to block if await asyncio.get_event_loop().run_in_executor(None, check_url_sync, doc_url): button.visible = True def on_click(url=doc_url): open_url(url) button.set_clicked_fn(on_click) button.set_tooltip_fn(lambda url=doc_url: ui.Label(url)) break # Async check for URLs and if valid show the button doc_urls = build_doc_urls(ext_item) if doc_urls: asyncio.ensure_future(check_urls(doc_urls))
11,164
Python
35.848185
114
0.523647
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_data_fetcher.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 asyncio import json import logging import os from functools import lru_cache from typing import Callable, List import omni.kit.app from .common import ExtensionCommonInfo, get_registry_url logger = logging.getLogger(__name__) class ExtDataFetcher: """Fetches json files near extension archives from the registry and caches them""" def __init__(self): # Notify when anything new fetched self.on_data_fetched_fn: Callable = None # Cached data self._data = {} def get_ext_data(self, package_id) -> dict: return self._data.get(package_id, None) def fetch(self, ext_item: ExtensionCommonInfo): if self.get_ext_data(ext_item.package_id): return json_data_urls = self._build_json_data_urls(ext_item) if json_data_urls: async def read_data(): for json_data_url in json_data_urls: result, _, content = await omni.client.read_file_async(json_data_url) if result == omni.client.Result.OK: try: content = memoryview(content).tobytes().decode("utf-8") self._data[ext_item.package_id] = json.loads(content) if self.on_data_fetched_fn: self.on_data_fetched_fn(ext_item.package_id) # noqa break except Exception as e: # noqa logger.error("Error reading extra registry data from: %s. Error: %s", json_data_url, e) asyncio.ensure_future(read_data()) def _build_json_data_urls(self, ext_item: ExtensionCommonInfo) -> List[str]: ext_manager = omni.kit.app.get_app().get_extension_manager() ext_remote_info = ext_manager.get_registry_extension_dict(ext_item.package_id) registry_url = get_registry_url(ext_item.provider_name) if not registry_url: return None # Same as archive path, but extension is `.json`: archive_path = ext_remote_info.get("package", {}).get("archivePath", None) if archive_path: # build url relative to the registry url archive_path = archive_path.replace("\\", "/") archive_path = omni.client.combine_urls(registry_url + "/index.zip", archive_path) archive_path = omni.client.normalize_url(archive_path) archive_path = os.path.splitext(archive_path)[0] + ".json" if omni.client.break_url(archive_path).host == omni.client.break_url(registry_url).host: return [archive_path] # that means archive path is on different host (like packman). Do the best guess using registry url. # Old format is one big folder, new format is a subfolder for each extension data_filename = os.path.basename(archive_path) return [ "{}/archives/{}".format(registry_url, data_filename), "{}/archives/{}/{}".format(registry_url, ext_item.fullname, data_filename), ] return None @lru_cache() def get_ext_data_fetcher(): return ExtDataFetcher()
3,635
Python
39.4
115
0.616506
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/markdown_renderer.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 .styles import get_style class MarkdownText: def __init__(self, content): with ui.VStack(height=0, style=get_style(self)): def consume_heading(s): heading = 0 while s.startswith("#"): s = s[1:] heading += 1 return heading, s.lstrip() for line in content.splitlines(): line = line.lstrip() heading, line = consume_heading(line) style_name = "text" if heading > 0: style_name = f"H{heading}" ui.Label(line, name=style_name, height=0, word_wrap=True)
1,138
Python
32.499999
76
0.603691
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_list_widget.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. # # pylint: disable=attribute-defined-outside-init, protected-access, # pylint: disable=access-member-before-definition, unnecessary-lambda-assignment import asyncio import contextlib import fnmatch from collections import OrderedDict, defaultdict from enum import IntFlag from functools import lru_cache from typing import Callable, List, Optional import carb import carb.events import carb.settings import omni.kit.app import omni.kit.commands import omni.ui as ui from omni.kit.widget.filter import FilterButton from omni.kit.widget.options_menu import OptionItem from omni.ui import color as cl from .common import ( EXTENSION_PULL_STARTED_EVENT, REGISTRIES_CHANGED_EVENT, ExtAuthorGroup, ExtensionCommonInfo, ExtSource, get_categories, get_open_example_links, is_community_tab_enabled, ) from .ext_components import ExtensionToggle, ExtSourceSelector, SearchWidget from .ext_controller import are_featured_exts_enabled from .ext_export_import import import_ext from .ext_template import create_new_extension_template from .styles import ( EXT_ICON_SIZE, EXT_ITEM_TITLE_BAR_H, EXT_LIST_ITEM_H, EXT_LIST_ITEM_ICON_ZONE_W, EXT_LIST_ITEMS_MARGIN_H, ) from .utils import get_ext_info_dict, get_extpath_git_ext ext_manager = None # Sync only once for now @lru_cache() def _sync_registry(): ext_manager.refresh_registry() class ExtGroupItem(ui.AbstractItem): def __init__(self, name): super().__init__() self.name = name self.total_count = 0 self.items = [] self.ext_source = ExtSource.NVIDIA def contains(self, ext_summary): return True def is_expanded_by_default(self): return True class ExtFeatureGroupItem(ExtGroupItem): def contains(self, ext_summary): return ext_summary.feature class ExtToggleableGroupItem(ExtGroupItem): def contains(self, ext_summary): return ext_summary.toggleable class ExtNonToggleableGroupItem(ExtGroupItem): def contains(self, ext_summary): return not ext_summary.toggleable def is_expanded_by_default(self): return False class ExtAuthorGroupItem(ExtGroupItem): def __init__(self, name, author_group: ExtAuthorGroup): super().__init__(name) self.author_group = author_group self.ext_source = ExtSource.THIRD_PARTY def contains(self, ext_summary): return ext_summary.author_group == self.author_group def is_expanded_by_default(self): return True class ExtSummaryItem(ui.AbstractItem): """An abstract item that represents an extension summary""" def refresh(self, ext_summary): self.fullname = ext_summary["fullname"] self.flags = ext_summary["flags"] self.enabled_ext = ext_summary["enabled_version"] self.latest_ext = ext_summary["latest_version"] self.default_ext = self.latest_ext self.enabled = bool(self.flags & omni.ext.EXTENSION_SUMMARY_FLAG_ANY_ENABLED) if self.enabled: self.default_ext = self.enabled_ext self.id = self.default_ext["id"] is_latest = self.enabled_ext["id"] == self.latest_ext["id"] self.can_update = self.enabled and not is_latest # Query more info ext_info, is_local = get_ext_info_dict(ext_manager, self.default_ext) # Take latest version (in terms of semver) and grab publish date from it if any, for sorting invert it. latest_info = ext_info if is_latest else get_ext_info_dict(ext_manager, self.latest_ext)[0] publish_date = latest_info.get("package", {}).get("publish", {}).get("date", 0) self.publish_date_rev = -publish_date # Move all attributes from ExtensionCommonInfo class to this class self.__dict__.update(ExtensionCommonInfo(self.id, ext_info, is_local).__dict__) class ExtSummariesModel(ui.AbstractItemModel): """Extension summary model that watches the changes in ext manager""" class SortDirection(IntFlag): NONE = 0 Ascending = 1 Descending = 2 def __init__(self, flat=None): super().__init__() global ext_manager app = omni.kit.app.get_app() ext_manager = app.get_extension_manager() self._ext_summaries = {} # Order matters here, because contains() matches first group self._groups = [ ExtAuthorGroupItem("User", ExtAuthorGroup.USER), ExtAuthorGroupItem("Partner", ExtAuthorGroup.PARTNER), ExtAuthorGroupItem("Community - Verified", ExtAuthorGroup.COMMUNITY_VERIFIED), ExtAuthorGroupItem("Community - Unverified", ExtAuthorGroup.COMMUNITY_UNVERIFIED), ExtFeatureGroupItem("Feature"), ExtToggleableGroupItem("General"), ExtNonToggleableGroupItem("Non-Toggleable"), ] # Attribute in ExtSummaryItem to sort by. For each attribute store order of sort in a dict (can be toggled) self._sort_attr = "name" self._sort_direction = ExtSummariesModel.SortDirection.Ascending # exscribe for ext manager changes and generic event def on_change(*_): self._resync_exts() self._subs = [] self._subs.append( ext_manager.get_change_event_stream().create_subscription_to_pop( on_change, name="ExtSummariesModel watch for exts" ) ) bus = app.get_message_bus_event_stream() self._subs.append(bus.create_subscription_to_pop_by_type(REGISTRIES_CHANGED_EVENT, on_change)) self._subs.append(bus.create_subscription_to_pop_by_type(EXTENSION_PULL_STARTED_EVENT, on_change)) # Current name filter self._filter_name_text = [] # Current category filter self._filter_category = "" # Current ext source self._filter_ext_source = ExtSource.NVIDIA # Hacky link back to tree view to be able to update expanded state self.tree_view = None # on refresh callback self.on_refresh_cb = None # Builds a list self._resync_exts() def resync_registry(self): ext_manager.refresh_registry() def refresh_all(self): self._resync_exts() def _resync_exts(self): get_extpath_git_ext.cache_clear() for (_, _, clear_cache) in ExtsListWidget.searches.values(): if clear_cache is not None: clear_cache() _sync_registry() ext_summaries = ext_manager.fetch_extension_summaries() # groups for g in self._groups: g.total_count = 0 self._ext_summaries = {} for ext_s in ext_summaries: item = ExtSummaryItem() item.refresh(ext_s) # assign group item.group = next(x for x in self._groups if x.contains(item)) item.group.total_count += 1 self._item_changed(item) self._ext_summaries[ext_s["fullname"]] = item self._item_changed(None) # Update expanded state after tree was built and rendered async def _delayed_expand(): await omni.kit.app.get_app().next_update_async() if self.tree_view: for g in self._groups: self.tree_view.set_expanded(g, g.is_expanded_by_default(), False) if self.tree_view: asyncio.ensure_future(_delayed_expand()) self._sorted_summaries = list(self._ext_summaries.values()) self._make_sure_sorted() def _refresh_item_group_lists(self): # Filtering logic here: matching_fns = [] # Split text in words and look for @keywords. Add matching functions and remove from the list. # To remove from list while iterating use backward iteration trick. parts = self._filter_name_text.copy() for i in range(len(parts) - 1, -1, -1): w = parts[i] if w.startswith("@"): # Predefined keywords or use default ones fn = ExtsListWidget.searches.get(w, [None, None, None])[1] if fn is None: fn = lambda item, w=w: w[1:] in item.keywords matching_fns.append(fn) del parts[i] # Whatever left just use as wildcard search: if len(parts) > 0: for part in parts: filter_str = f"*{part.lower()}*" matching_fns.append( lambda item, filter_str=filter_str: fnmatch.fnmatch(item.name.lower(), filter_str) or fnmatch.fnmatch(item.fullname.lower(), filter_str) ) # If category filter enabled, add matching function for it if len(self._filter_category) != 0: matching_fns.append(lambda item: self._filter_category == item.category) else: hidden_categories = [c for c, v in get_categories().items() if v.get("hidden", False)] matching_fns.append(lambda item: item.category not in hidden_categories) # Show item only if it matches all matching functions for group in self._groups: group.items = [v for v in self._sorted_summaries if v.group == group and all(f(v) for f in matching_fns)] self._item_changed(group) # callback if self.on_refresh_cb: self.on_refresh_cb() def get_item_children(self, item): """Reimplemented from AbstractItemModel""" if item is None: self._refresh_item_group_lists() return [g for g in self._groups if g.total_count and g.ext_source == self._filter_ext_source] if isinstance(item, ExtGroupItem): return item.items return [] def get_item_value_model_count(self, item): """Reimplemented from AbstractItemModel""" return 1 def get_item_value_model(self, item, column_id): """Reimplemented from AbstractItemModel""" return def filter_by_text(self, filter_name_text, filters): """Specify the filter string that is used to reduce the model""" new_list = filters + [filter_name_text] if self._filter_name_text == new_list and not new_list: return self._filter_name_text = new_list # Avoid refreshing on every key typed, as it can be slow. Add delay: self._refresh_once_with_delay(delay=0.3) def select_category(self, filter_category): # Special case for "All" => "" if self._filter_category == filter_category: return self._filter_category = filter_category self._refresh_once_with_delay(delay=0.1) def select_ext_source(self, ext_source): if self._filter_ext_source == ext_source: return False self._filter_ext_source = ext_source self._resync_exts() return True def _refresh_once_with_delay(self, delay: float): """Call refresh once after `delay` seconds. If called again before `delay` is passed the timer gets reset.""" async def _delayed_refresh(): await asyncio.sleep(delay) self._item_changed(None) with contextlib.suppress(Exception): self._refresh_task.cancel() self._refresh_task = asyncio.ensure_future(_delayed_refresh()) def sort_by_attr(self, attr: str): """Sort by item attribute.""" if attr is None: return if self._sort_attr != attr: self._sort_attr = attr self._make_sure_sorted() def sort_direction(self, direction: SortDirection): """Sort by direction.""" if direction is None: return self._sort_direction = direction self._make_sure_sorted() def _make_sure_sorted(self): # Sort order setting is global reverse = self._sort_direction == ExtSummariesModel.SortDirection.Descending # Attribute value getter key_fn = lambda x: getattr(x, self._sort_attr) cmp_fn = (lambda x, y: x >= y) if reverse else (lambda x, y: x <= y) # Check that it is already sorted to avoid list rebuild is_sorted_fn = lambda l: all(cmp_fn(key_fn(l[i]), key_fn(l[i + 1])) for i in range(len(l) - 1)) if not is_sorted_fn(self._sorted_summaries): self._sorted_summaries = sorted(self._sorted_summaries, key=key_fn, reverse=reverse) self._item_changed(None) def destroy(self): self._ext_summaries = {} self._sorted_summaries = [] self._subs = None self.tree_view = None self.on_refresh_cb = None class ExtsDelegate(ui.AbstractItemDelegate): def build_branch(self, model, item, column_id, level, expanded): """ui.AbstractItemDelegate API: Create a branch widget that opens or closes subtree""" return def build_widget(self, model, item, column_id, level, expanded): """ui.AbstractItemDelegate API: Create a widget per column""" if isinstance(item, ExtGroupItem): with ui.ZStack(): with ui.VStack(): ui.Spacer(height=1) ui.Rectangle(height=30, name="ExtensionListGroup") with ui.HStack(): image_name = "expanded" if expanded else "" ui.Image( style_type_name_override="ExtensionList.Group.Icon", name=image_name, width=31, height=31, alignment=ui.Alignment.LEFT_CENTER, ) ui.Label( "{} ({}/{})".format(item.name, len(item.items), item.total_count), style_type_name_override="ExtensionList.Group.Label", ) return h = EXT_LIST_ITEM_H - EXT_ITEM_TITLE_BAR_H with ui.VStack(height=EXT_LIST_ITEM_H + EXT_LIST_ITEMS_MARGIN_H): with ui.ZStack(): with ui.VStack(height=0): ui.Rectangle(height=EXT_LIST_ITEM_H, style_type_name_override="ExtensionList.Background") ui.Rectangle(height=EXT_LIST_ITEMS_MARGIN_H, style_type_name_override="ExtensionList.Separator") with ui.VStack(): # Top row with ui.HStack(height=EXT_ITEM_TITLE_BAR_H): # Title ui.Label( item.title, style_type_name_override="ExtensionList.Label", name="Title", elided_text=True ) # Toggle ExtensionToggle(item, show_install_button=not item.is_untrusted) ui.Spacer(width=5) with ui.HStack(): with ui.HStack(width=EXT_LIST_ITEM_ICON_ZONE_W): ui.Spacer() with ui.VStack(width=EXT_ICON_SIZE[0]): ui.Spacer() ui.Image(item.icon_path, height=EXT_ICON_SIZE[1], style={"color": 0xFFFFFFFF}) ui.Spacer() ui.Spacer() with ui.ZStack(): ui.Rectangle(height=h, style_type_name_override="ExtensionList.Foreground") with ui.VStack(): ui.Spacer(height=5) # Category name category = get_categories().get(item.category) ui.Label( category["name"], height=0, style_type_name_override="ExtensionList.Label", name="Category", ) # Extension id ui.Label( item.fullname, height=0, style_type_name_override="ExtensionList.Label", name="Id", elided_text=True, ) # Version if item.version and item.version[0:3] != (0, 0, 0): ui.Label( "v" + item.version, style_type_name_override="ExtensionList.Label", name="Version", alignment=ui.Alignment.BOTTOM, ) # Update available? # if item.can_update: with ui.VStack(): ui.Spacer(height=10) with ui.HStack(): ui.Spacer() if item.can_update: ui.Image( name="UpdateAvailable", width=28, height=31, alignment=ui.Alignment.RIGHT_CENTER, ) ui.Spacer(width=10) if item.can_update: ui.Label( "UPDATE AVAILABLE", alignment=ui.Alignment.RIGHT_CENTER, name="UpdateAvailable" ) elif item.author_group != ExtAuthorGroup.NVIDIA: with ui.HStack(): ui.Spacer() with ui.VStack(width=148, height=0): ui.Spacer() with ui.ZStack(): ui.Image( name="Community", width=148, height=32, alignment=ui.Alignment.RIGHT_BOTTOM, ) name = item.author_group.get_ui_name() ui.Label(name, alignment=ui.Alignment.RIGHT_CENTER, name="Community") elif item.location_tag: ui.Label(item.location_tag, alignment=ui.Alignment.RIGHT_CENTER, name="LocationTag") ui.Spacer() def build_header(self, column_id): pass class ExtsListWidget: # Search configuration information as SearchKey:(SearchUiName, FilterBySearchKey, ClearSearchCache) searches = OrderedDict( { "@startup": ("Startup", lambda item: item.is_startup, None), "@featured": ("Featured", lambda item: item.is_featured or item.ext_source == ExtSource.THIRD_PARTY, None), "@bundled": ("Bundled", lambda item: bool(item.flags & omni.ext.EXTENSION_SUMMARY_FLAG_BUILTIN), None), "@user": ("User", lambda item: item.author_group == ExtAuthorGroup.USER, None), "@app": ("App", lambda item: item.is_app, None), "@enabled": ("Enabled", lambda item: bool(item.flags & omni.ext.EXTENSION_SUMMARY_FLAG_ANY_ENABLED), None), "@update": ("Update Available", lambda item: item.can_update, None), "@installed": ( "Installed", lambda item: bool(item.flags & omni.ext.EXTENSION_SUMMARY_FLAG_INSTALLED), None, ), "@remote": ("Remote", lambda item: not bool(item.flags & omni.ext.EXTENSION_SUMMARY_FLAG_BUILTIN), None), } ) # remove "Featured" when not in use if not are_featured_exts_enabled(): del searches["@featured"] def __init__(self): # Extensions List Data Model self._model = ExtSummariesModel() self._model.on_refresh_cb = self._on_ext_list_refresh menu_style = { "padding": 2, "Menu.Item.CheckMark": {"color": cl.shade(cl("#34C7FF"))}, "Titlebar.Background": {"background_color": cl.shade(cl("#1F2123"))}, "Titlebar.Title": {"color": cl.shade(cl("#848484"))}, "Titlebar.Reset": {"background_color": 0}, "Titlebar.Reset.Label": {"color": cl.shade(cl("#2E86A9"))}, "Titlebar.Reset.Label:hovered": {"color": cl.shade(cl("#34C7FF"))}, } # Delegate to build list rows. self._delegate = ExtsDelegate() self.set_show_graph_fn(None) self.set_show_properties_fn(None) # Filter button self._filter_button: Optional[FilterButton] = None # Sort menu. One day it will be a hamburger. One can dream. self._sortby_menu = ui.Menu("Sort By", style=menu_style, menu_compatibility=False, tearable=False) self.rebuild_sortby_menu() self._options_menu = ui.Menu("Options", style=menu_style, menu_compatibility=False, tearable=False) self.rebuild_options_menu() # Extension creation menu self._create_menu = ui.Menu("Create", style=menu_style, menu_compatibility=False, tearable=False) self.rebuild_create_menu() def _menu_header(self, title, clicked_fn): with ui.ZStack(height=0): ui.Rectangle(style_type_name_override="Titlebar.Background") with ui.VStack(): ui.Spacer(height=3) with ui.HStack(): ui.Spacer(width=10) ui.Label(title, style_type_name_override="Titlebar.Title") ui.Spacer() ui.Button( "Reset all" if clicked_fn else " ", style_type_name_override="Titlebar.Reset", clicked_fn=clicked_fn, ) ui.Spacer(width=10) ui.Spacer(height=2) def rebuild_filter_menu(self): if self._filter_button: option_items = self._build_filter_items() self._filter_button.model.rebuild_items(option_items) def rebuild_sortby_menu(self): def reset_sort(): asyncio.ensure_future(update_sort("name", ExtSummariesModel.SortDirection.Ascending)) async def update_sort(sb: str, sd: ExtSummariesModel.SortDirection): if sb: await omni.kit.app.get_app().next_update_async() self._model.sort_by_attr(sb) if sd is not ExtSummariesModel.SortDirection.NONE: await omni.kit.app.get_app().next_update_async() self._model.sort_direction(sd) sort_by = self._model._sort_attr sort_direction = self._model._sort_direction # change button color self._sortby_button.name = ( "sortby" if sort_by == "name" and sort_direction == ExtSummariesModel.SortDirection.Ascending else "sortby_on" ) self._sortby_menu.clear() with self._sortby_menu: self._menu_header("Sort", reset_sort) ui.MenuItem( "Name", triggered_fn=lambda: asyncio.ensure_future( update_sort("name", ExtSummariesModel.SortDirection.NONE) ), checkable=True, checked=sort_by == "name", ) ui.MenuItem( "Enabled", triggered_fn=lambda: asyncio.ensure_future( update_sort("enabled", ExtSummariesModel.SortDirection.NONE) ), checkable=True, checked=sort_by == "enabled", ) ui.MenuItem( "Publish Date", triggered_fn=lambda: asyncio.ensure_future( update_sort("publish_date_rev", ExtSummariesModel.SortDirection.NONE) ), checkable=True, checked=sort_by == "publish_date_rev", ) ui.Separator() ui.MenuItem( "Ascending", triggered_fn=lambda: asyncio.ensure_future( update_sort(None, ExtSummariesModel.SortDirection.Ascending) ), checkable=True, checked=sort_direction == ExtSummariesModel.SortDirection.Ascending, ) ui.MenuItem( "Descending", triggered_fn=lambda: asyncio.ensure_future( update_sort(None, ExtSummariesModel.SortDirection.Descending) ), checkable=True, checked=sort_direction == ExtSummariesModel.SortDirection.Descending, ) asyncio.ensure_future(update_sort(None, ExtSummariesModel.SortDirection.NONE)) def rebuild_options_menu(self): self._options_menu.clear() with self._options_menu: self._menu_header("Options", None) ui.MenuItem("Settings", triggered_fn=self._show_properties) ui.MenuItem("Refresh", triggered_fn=self._model.refresh_all) ui.MenuItem("Resync Registry", triggered_fn=self._resync_registry) ui.MenuItem("Show Extension Graph", triggered_fn=self._show_graph) ui.MenuItem("Import Extension", triggered_fn=import_ext) def rebuild_create_menu(self): def open_url(url): import webbrowser webbrowser.open(url) self._create_menu.clear() with self._create_menu: self._menu_header("Create Extension", None) ui.MenuItem("New Extension Template Project", triggered_fn=create_new_extension_template) for name, url in get_open_example_links(): ui.MenuItem(name, triggered_fn=lambda u=url: open_url(u)) def _on_key_pressed(self, key, mod, pressed): """Allow up/down arrow to be used to select prev/next extension""" def _select_next(treeview: ui.TreeView, model: ui.AbstractItemModel, after=True): full_list = model.get_item_children(None) selection = treeview.selection if not selection: treeview.selection = [full_list[0]] else: index = full_list.index(selection[0]) index += 1 if after else -1 if index < 0 or index >= len(full_list): return treeview.selection = [full_list[index]] if not pressed: return if mod == 0 and key == int(carb.input.KeyboardInput.DOWN): _select_next(self.tree_view, self._model, after=True) elif mod == 0 and key == int(carb.input.KeyboardInput.UP): _select_next(self.tree_view, self._model, after=False) def _on_selection_changed(self, selection): item = selection[0] if len(selection) > 0 else None if item and isinstance(item, ExtGroupItem): self.tree_view.set_expanded(item, not self.tree_view.is_expanded(item), False) self.tree_view.clear_selection() else: self._ext_selected_fn(item) def _on_ext_list_refresh(self): cnt = defaultdict(int) for group in self._model._groups: cnt[group.ext_source] += len(group.items) for source, value in cnt.items(): self._ext_source_selector.set_badge_number(source, value) async def __update_filter(self, search_key: str) -> None: if search_key: self._search.toggle_filter(search_key) await omni.kit.app.get_app().next_update_async() self._filter_by_text(self._search.get_text(), self._search.get_filters()) def _build_filter_items(self) -> List[OptionItem]: option_items = [] filters = self._search.get_filters() for search_key, (search_description, _, _) in self.searches.items(): option_item = OptionItem( search_description, on_value_changed_fn=lambda m, sk=search_key: asyncio.ensure_future(self.__update_filter(sk)), ) option_item.model.set_value(search_key in filters) option_items.append(option_item) return option_items def _build_filter_button(self): option_items = self._build_filter_items() self._filter_button = FilterButton(option_items) def build(self): with ui.VStack(spacing=3): with ui.HStack(height=0): # Create button ui.Button(name="create", width=22, height=22, clicked_fn=self._create_menu.show) # Search field with ui.HStack(width=ui.Fraction(2)): self._search = SearchWidget( on_search_fn=lambda t: self._filter_by_text(t, self._search.get_filters()) ) if are_featured_exts_enabled(): self._search.toggle_filter("@featured") ui.Spacer(width=10) # Category selector category_list = [("All", "")] + [(v["name"], c) for c, v in get_categories().items()] self._category_combo = ui.ComboBox(0, *[c[0] for c in category_list], style={"padding": 4}) self._category_combo.model.add_item_changed_fn( lambda model, item: self._select_category(category_list[model.get_item_value_model(item).as_int][1]) ) ui.Spacer(width=5) # Filter button self._build_filter_button() # Sort-By button self._sortby_button = ui.Button(name="sortby", width=24, height=24, clicked_fn=self._sortby_menu.show) # Properies ui.Button(name="options", width=24, height=24, clicked_fn=self._options_menu.show) # Source selector (community tab) self._ext_source_selector = None if is_community_tab_enabled(): self._ext_source_selector = ExtSourceSelector(self._select_ext_source) frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ) with frame: with ui.ZStack(): self.tree_view = ui.TreeView( self._model, header_visible=False, delegate=self._delegate, column_widths=[ui.Fraction(1)], root_visible=False, keep_expanded=False, ) self._model.tree_view = self.tree_view self.tree_view.set_selection_changed_fn(self._on_selection_changed) # make that public self.clear_selection = self.tree_view.clear_selection frame.set_key_pressed_fn(self._on_key_pressed) def set_show_graph_fn(self, fn: Callable): self._show_graph_fn = fn def set_ext_selected_fn(self, fn: Callable): self._ext_selected_fn = fn def _resync_registry(self): self._model.resync_registry() def _show_graph(self): if self._show_graph_fn: self._show_graph_fn() def set_show_properties_fn(self, fn: Callable): self._show_properties_fn = fn def _show_properties(self): if self._show_properties_fn: self._show_properties_fn() def _filter_by_text(self, filter_text: str, filters: list): """Set the search filter string to the models and widgets""" self._model.filter_by_text(filter_text, filters) def _select_category(self, category: str): """Set the category to show""" self._model.select_category(category) def _select_ext_source(self, ext_source): self._model.select_ext_source(ext_source) def destroy(self): self._delegate = None if self._filter_button: self._filter_button.destroy() self._filter_button = None self._sortby_menu = None self._options_menu = None self._search.destroy() self._search = None self._category_combo = None self._model.destroy() self._model = None
33,624
Python
38.235706
120
0.545444
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_commands.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.kit.app import omni.kit.commands class ToggleExtension(omni.kit.commands.Command): """ Toggle extension **Command**. Enables/disables an extension. Args: ext_id(str): Extension id. enable(bool): Enable or disable. """ def __init__(self, ext_id: str, enable: bool): self._ext_id = ext_id self._enable = enable self._ext_manager = omni.kit.app.get_app().get_extension_manager() def do(self): manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate(self._ext_id, self._enable) omni.kit.app.send_telemetry_event( "omni.kit.window.extensions@enable_ext", data1=self._ext_id, value1=float(self._enable) )
1,199
Python
35.363635
99
0.694746
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_template.py
# pylint: disable=protected-access import asyncio import glob import os import re import sys from datetime import datetime from itertools import chain from pathlib import Path from string import Template import carb.tokens import omni.ext import omni.kit.app from . import ext_controller from .ext_export_import import _ask_user_for_path from .utils import open_in_vscode_if_enabled, show_ok_popup, show_user_input_popup def substitute_tokens_in_file(path, tokens): try: with open(path, "r", encoding="utf-8") as f: content = Template(f.read()).safe_substitute(tokens) except UnicodeDecodeError: # Non-text file, ignore return with open(path, "w", encoding="utf-8") as f: f.write(content) def is_subpath(path, root): return root in path.parents def _copy_template(src, dst, ext_id, python_module_path): import shutil from distutils.dir_util import copy_tree # noqa: PLW0612, PLW4901 from os.path import join copy_tree(join(src, "tools"), join(dst, "tools")) copy_tree(join(src, "vscode"), join(dst, ".vscode")) shutil.copy(join(src, "README.md"), join(dst, "README.md")) shutil.copy(join(src, "gitignore"), join(dst, ".gitignore")) shutil.copy(join(src, "link_app.bat"), join(dst, "link_app.bat")) shutil.copy(join(src, "link_app.sh"), join(dst, "link_app.sh")) copy_tree(join(src, "exts", "[ext_id]", "[python_module]"), join(dst, "exts", ext_id, python_module_path)) copy_tree(join(src, "exts", "[ext_id]", "config"), join(dst, "exts", ext_id, "config")) copy_tree(join(src, "exts", "[ext_id]", "docs"), join(dst, "exts", ext_id, "docs")) copy_tree(join(src, "exts", "[ext_id]", "data"), join(dst, "exts", ext_id, "data")) async def _create_new_extension_template(): export_path = await _ask_user_for_path( is_export=True, apply_button_label="Select", title="Choose a location for your extension project" ) if not export_path: return project_folder = await show_user_input_popup( "Name the extension project. This is the root folder of the repository.", "Project Name: ", "kit-exts-project" ) export_path = os.path.join(export_path, project_folder) # Create folder os.makedirs(export_path, exist_ok=True) if len(os.listdir(export_path)) > 0: await show_ok_popup("Error", f"Folder already exist: {export_path}") return template_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.window.extensions}/ext_template") if sys.platform == "win32": kit_exec = "kit.exe" python_exe = "python.exe" else: kit_exec = "kit" python_exe = "bin/python3" ext_id = await show_user_input_popup("Choose Extension Name:", "ext_id: ", "company.hello.world") ext_name = "".join([token.capitalize() for token in ext_id.split(".")]) ext_title = " ".join(ext_id.split(".")) ext_id_pattern = r"^[a-zA-Z0-9._]+$" if not re.match(ext_id_pattern, ext_id): await show_ok_popup("Error", f"Invalid extension name: {ext_id}. Supported chars: {ext_id_pattern}") return python_module = ext_id python_module_path = ext_id.replace(".", "/") # copy template folder _copy_template(template_path, export_path, ext_id, python_module_path) # Find app root def _look_for_app_root(path): path = Path(path) for p in chain([path], path.parents): for kit_subpath in ["", "kit"]: if p.joinpath(kit_subpath, kit_exec).is_file(): return str(p), str(kit_subpath) return None, None app_path = carb.tokens.get_tokens_interface().resolve("${app}") app_root_path, kit_subpath = _look_for_app_root(app_path) if not app_root_path: await show_ok_popup("Error", f"Can't find app root in {app_root_path}") return # build vscode exts search paths: ext_relative_paths = [] app = omni.kit.app.get_app() manager = app.get_extension_manager() for folder in manager.get_folders(): path_type = folder["type"] if path_type == omni.ext.ExtensionPathType.COLLECTION: path = Path(folder["path"]) if is_subpath(path, Path(app_root_path)): for p in glob.glob(f"{path}/*"): if os.path.isdir(p): s = ' "${{workspaceFolder}}/app/{}",'.format( Path(p).relative_to(app_root_path).as_posix() ) ext_relative_paths.append(s) export_exts_path = f"{export_path}/exts" export_app_path = f"{export_path}/app" # substitute all tokens tokens = { "ext_id": ext_id, "ext_name": ext_name, "ext_title": ext_title, "kit_subpath": kit_subpath + "/" if kit_subpath else "", "python_exe": python_exe, "python_module": python_module, "ext_search_paths": "\n".join(ext_relative_paths), "export_path": export_path, "export_exts_path": export_exts_path, "export_app_path": export_app_path, "author": os.environ.get("USERNAME", "please fill in author information"), "today": datetime.today().strftime("%Y-%m-%d"), } for folder, _, files in os.walk(export_path): for filename in files: substitute_tokens_in_file(os.path.join(folder, filename), tokens) # create link omni.ext.create_link(export_app_path, app_root_path) # try open in vscode: open_in_vscode_if_enabled(export_path, prefer_vscode=True) # add new search path (remove + add will trigger fs search for sure) manager.remove_path(export_exts_path) manager.add_path(export_exts_path, omni.ext.ExtensionPathType.COLLECTION_USER) await app.next_update_async() # Enable that one ext and make it autoload manager.set_extension_enabled(ext_id, True) ext_controller.toggle_autoload(f"{ext_id}-1.0.0", True) # Focus on it from .extension import get_instance instance = get_instance()() instance._window._ext_info_widget._refresh_once_next_frame() instance._window._exts_list_widget._search.set_text(ext_id) def create_new_extension_template(): asyncio.ensure_future(_create_new_extension_template())
6,299
Python
35
118
0.622003
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_properties_registries.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 carb.dictionary import carb.settings import omni.kit.app import omni.ui as ui from .common import REGISTRIES_CHANGED_EVENT, USER_REGISTRIES_SETTING, get_registries from .ext_components import SimpleCheckBox from .styles import get_style from .utils import copy_text, get_setting DEFAUT_PUBLISH_SETTING = "app/extensions/registryPublishDefault" EMPTY_REGISTRY_NAME = "[enter_name]" REGISTRIES_COLUMNS = ["name", "url", "default", "user"] class RegistryItem(ui.AbstractItem): def __init__(self, name, url, is_user=True, is_default=False, add_dummy=False): super().__init__() self.name_model = ui.SimpleStringModel(name) self.url_model = ui.SimpleStringModel(url) self.default_model = ui.SimpleBoolModel(is_default) self.is_user = is_user self.add_dummy = add_dummy class RegistriesModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._children = [] self._load() self._add_dummy = RegistryItem("", "", add_dummy=True) self._default_changing = False def destroy(self): self._children = [] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: return [] return self._children + [self._add_dummy] def get_item_value_model_count(self, item): """The number of columns""" return 4 def get_item_value_model(self, item, column_id): if column_id == 0: return item.name_model if column_id == 1: return item.url_model return None def _load(self): self._children = [] default_registry = get_setting(DEFAUT_PUBLISH_SETTING, "") # Registries ui.Label("Registries:") for name, url, is_user in get_registries(): self._children.append(RegistryItem(name, url, is_user, is_default=(name == default_registry))) self._item_changed(None) def add_empty(self): self._children.append(RegistryItem(EMPTY_REGISTRY_NAME, "", is_user=True)) self._item_changed(None) def remove_item(self, item): self._children.remove(item) self._item_changed(None) self.save() def save(self): registries = [] for child in self._children: if child.is_user: name = child.name_model.as_string url = child.url_model.as_string if name and url: # Auto fill name? if name == EMPTY_REGISTRY_NAME: name = "/".join(url.split("/")[-2:]) # Take last 2 child.name_model.as_string = name registries.append({"name": name, "url": url}) settings_dict = carb.settings.get_settings().get_settings_dictionary("") settings_dict[USER_REGISTRIES_SETTING[1:]] = registries # Notify registry omni.kit.app.get_app().get_message_bus_event_stream().push(REGISTRIES_CHANGED_EVENT) def set_default(self, item, value): # to avoid recursion if self._default_changing: return self._default_changing = True for c in self._children: c.default_model.as_bool = False item.default_model.as_bool = value carb.settings.get_settings().set(DEFAUT_PUBLISH_SETTING, item.name_model.as_string if value else "") self._default_changing = False class EditableDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._subscription = None self._context_menu = ui.Menu("Context menu") def destroy(self): self._subscription = None self._context_menu = None def _show_copy_context_menu(self, x, y, button, modifier, text): if button != 1: return self._context_menu.clear() with self._context_menu: ui.MenuItem("Copy", triggered_fn=lambda: copy_text(text)) self._context_menu.show() def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" with ui.HStack(width=20): value_model = model.get_item_value_model(item, column_id) if column_id in (0, 1): stack = ui.ZStack(height=20) with stack: label = ui.Label(value_model.as_string, width=500, name=("config" if item.is_user else "builtin")) field = ui.StringField(value_model, visible=False) # Start editing when double clicked stack.set_mouse_double_clicked_fn( lambda x, y, b, _, f=field, l=label, m=model, i=item: self.on_double_click(b, f, l, m, i) ) # Right click is copy menu stack.set_mouse_pressed_fn( lambda x, y, b, m, t=value_model.as_string: self._show_copy_context_menu(x, y, b, m, t) ) elif column_id == 2: if not item.add_dummy: with ui.HStack(): ui.Spacer(width=10) SimpleCheckBox( item.default_model.as_bool, lambda value, item=item: model.set_default(item, value), model=item.default_model, text="", ) ui.Spacer(width=20) else: if item.is_user: def on_click(): if item.add_dummy: model.add_empty() else: model.remove_item(item) with ui.HStack(): ui.Spacer(width=10) ui.Button( name=("add" if item.add_dummy else "remove"), style_type_name_override="ItemButton", width=20, height=20, clicked_fn=on_click, ) ui.Spacer() def on_double_click(self, button, field, label, model, item): """Called when the user double-clicked the item in TreeView""" if button != 0: return if item.add_dummy: return if not item.is_user: copy_text(field.model.as_string) return # Make Field visible when double clicked field.visible = True field.focus_keyboard() # When editing is finished (enter pressed of mouse clicked outside of the viewport) self._subscription = field.model.subscribe_end_edit_fn( lambda m, f=field, l=label, md=model: self.on_end_edit(m.as_string, f, l, md) ) def on_end_edit(self, text, field, label, model): """Called when the user is editing the item and pressed Enter or clicked outside of the item""" field.visible = False label.text = text self._subscription = None if text: model.save() def build_header(self, column_id): with ui.HStack(): ui.Spacer(width=10) ui.Label(REGISTRIES_COLUMNS[column_id], name="header") class ExtsRegistriesWidget: def __init__(self): self._model = RegistriesModel() self._delegate = EditableDelegate() with ui.VStack(style=get_style(self)): ui.Spacer(height=20) with ui.ScrollingFrame( height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style_type_name_override="TreeView", ): tree_view = ui.TreeView( self._model, delegate=self._delegate, root_visible=False, header_visible=True, ) tree_view.column_widths = [ui.Fraction(1), ui.Fraction(4), ui.Pixel(60), ui.Pixel(40)] ui.Spacer(height=10) def destroy(self): self._model.destroy() self._model = None self._delegate.destroy() self._delegate = None
8,863
Python
35.03252
118
0.55207
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_status_bar.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. # from datetime import datetime import omni.ext import omni.kit.app import omni.ui as ui from omni.ui import color as cl NEUTRAL = cl("#FFFFFF") SUCCESS = cl("#3794ff") FAILURE = cl("#CC0000") class ExtStatusBar: def __init__(self): self._label = ui.Label("", height=8) app = omni.kit.app.get_app() bus = app.get_message_bus_event_stream() self._subs = [] self._set_status("") def sub(e, message, color): self._subs.append(bus.create_subscription_to_pop_by_type(e, lambda e: self._set_status(message, color, e))) sub(omni.ext.EVENT_REGISTRY_REFRESH_BEGIN, "Syncing Registry...", NEUTRAL) sub( omni.ext.EVENT_REGISTRY_REFRESH_END_SUCCESS, "Registry Synced: " + datetime.now().strftime("%H:%M:%S"), SUCCESS, ) sub(omni.ext.EVENT_REGISTRY_REFRESH_END_FAILURE, "Registry Sync Failed.", FAILURE) sub(omni.ext.EVENT_EXTENSION_PULL_BEGIN, "Installing: {}...", NEUTRAL) sub(omni.ext.EVENT_EXTENSION_PULL_END_SUCCESS, "Installed successfully: {}", SUCCESS) sub(omni.ext.EVENT_EXTENSION_PULL_END_FAILURE, "Install failed: {}", FAILURE) def _set_status(self, status, color=NEUTRAL, evt=None): if evt and evt.payload["packageId"]: status = status.format(evt.payload["packageId"]) self._status = status self._status_color = color self._refresh_ui() def _refresh_ui(self): self._label.style = {"font_size": 14, "color": self._status_color} self._label.text = self._status
2,023
Python
35.799999
119
0.655956
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_properties_widget.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 carb.dictionary import carb.settings import carb.tokens import omni.kit.app import omni.ui as ui from .common import COMMUNITY_TAB_TOGGLE_EVENT, SettingBoolValue, get_options from .exts_list_widget import ExtSummaryItem from .exts_properties_paths import ExtsPathsWidget from .exts_properties_registries import ExtsRegistriesWidget from .styles import get_style from .utils import cleanup_folder, copy_text, ext_id_to_name_version, get_setting, version_to_str class ExtsPropertiesWidget: def __init__(self): self._ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_change_sub = self._ext_manager.get_change_event_stream().create_subscription_to_pop( lambda *_: self._refresh(), name="ExtPropertiesWidget" ) self._registries_widget = None self._paths_widget = None self._frame = ui.Frame() def destroy(self): self._clean_widgets() self._ext_change_sub = None self._frame = None def set_visible(self, visible): self._frame.visible = visible self._refresh() def _clean_widgets(self): if self._registries_widget: self._registries_widget.destroy() self._registries_widget = None if self._paths_widget: self._paths_widget.destroy() self._paths_widget = None def _refresh(self): if not self._frame.visible: return self._clean_widgets() # Build UI with self._frame: with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.ZStack(style=get_style(self)): ui.Rectangle(style_type_name_override="Properies.Background") with ui.HStack(): ui.Spacer(width=20) with ui.VStack(spacing=4, height=0): def add_open_button(text, url): def open_url(url_=url): # Import it here instead of on the file root because it has long import time. import webbrowser webbrowser.open(url_) ui.Button(text, width=0, clicked_fn=open_url, tooltip=url) ui.Spacer(height=10) # Extension Search Paths with ui.CollapsableFrame("Extension Search Paths", collapsed=False): self._paths_widget = ExtsPathsWidget() # Registries with ui.CollapsableFrame("Extension Registries", collapsed=False): self._registries_widget = ExtsRegistriesWidget() with ui.CollapsableFrame("Extension System Cache", collapsed=True): with ui.VStack(): ui.Spacer(height=10) cache_path = get_setting("/exts/omni.kit.registry.nucleus/cachePath", None) if cache_path: cache_path = carb.tokens.get_tokens_interface().resolve(cache_path) with ui.HStack(): add_open_button("Open", cache_path) def clean(p_=cache_path): cleanup_folder(p_) ui.Button( "Clean", width=0, clicked_fn=clean, tooltip="Remove all downloaded extensions", ) ui.Label(f"Path: {cache_path}") ui.Spacer(height=10) with ui.CollapsableFrame("Options", collapsed=True): with ui.VStack(): ui.Spacer(height=10) def add_option(option: SettingBoolValue, name: str, evt: int = None): # Publishing enabled with ui.HStack(width=60): cb = ui.CheckBox() def on_change(model): option.set_bool(model.get_value_as_bool()) if evt: omni.kit.app.get_app().get_message_bus_event_stream().push(evt) cb.model.set_value(option.get()) cb.model.add_value_changed_fn(on_change) ui.Label(name) options = get_options() add_option(options.publishing, "Publishing Enabled") if options.community_tab is not None: ui.Spacer(height=10) add_option( options.community_tab, "Show Community Extensions", COMMUNITY_TAB_TOGGLE_EVENT, ) ui.Spacer(height=10) # Export all exts data with ui.CollapsableFrame("Miscellaneous", collapsed=True): with ui.VStack(): ui.Spacer(height=10) ext_summaries = self._ext_manager.fetch_extension_summaries() total_cnt = len(ext_summaries) builtin_cnt = sum( bool(e["flags"] & omni.ext.EXTENSION_SUMMARY_FLAG_BUILTIN) for e in ext_summaries ) installed_cnt = sum( bool(e["flags"] & omni.ext.EXTENSION_SUMMARY_FLAG_INSTALLED) for e in ext_summaries ) ui.Label(f"Total Extensions: {total_cnt}", height=20) ui.Label(f"Bultin Extensions: {builtin_cnt}", height=20) ui.Label(f"Installed Extensions: {installed_cnt}", height=20) registry_count = len(self._ext_manager.get_registry_extensions()) ui.Label(f"Registry Packages: {registry_count}", height=20) ui.Spacer(height=10) ui.Button( "Copy all exts as CSV", width=100, height=30, clicked_fn=lambda: self.export_all_exts(ext_summaries), ) # Export all exts data ui.Button( "Copy enabled exts as .kit file (top level)", width=100, height=30, clicked_fn=lambda: self.export_enabled_exts_as_kit_file(only_top_level=True), ) # Export all exts data ui.Button( "Copy enabled exts as .kit file (all)", width=100, height=30, clicked_fn=lambda: self.export_enabled_exts_as_kit_file(only_top_level=False), ) ui.Spacer() ui.Spacer(width=20) def export_all_exts(self, ext_summaries): """Export all exts in CSV format with some of config params. print and copy result.""" ext_sum_dict = {} for ext_s in ext_summaries: item = ExtSummaryItem() item.refresh(ext_s) ext_sum_dict[ext_s["fullname"]] = item fields_to_export = [ "package/name", "package/version", "can_update,latest_version", # special case "state/enabled", "isKitFile", "package/category", "package/title", "package/description", "package/authors", "package/repository", "package/keywords", "package/readme", "package/changelog", "package/preview_image", "package/icon", "core/reloadable", ] # Header output = ",".join(["id"] + fields_to_export) + "\n" # Per ext row data for ext in self._ext_manager.get_extensions(): d = self._ext_manager.get_extension_dict(ext["id"]) row = ext["id"] + "," for f in fields_to_export: if f.startswith("can_update"): # special case, do both rows at once item = ext_sum_dict.get(ext["name"], None) if item: latest_version = version_to_str(item.latest_ext["version"][:4]) row += f'"{item.can_update}",' row += f'"{latest_version}",' else: row += ",," else: row += f'"{str(d.get(f, ""))}",' row = row.replace("\n", r"\n") output += row + "\n" print(output) copy_text(output) def export_enabled_exts_as_kit_file(self, only_top_level=True): """Export all topmost exts in .kit format. print and copy result.""" excludes = {"omni.kit.registry.nucleus", "omni.kit.profile_python"} all_deps = set() all_exts = set() for ext in self._ext_manager.get_extensions(): if ext["enabled"]: ext_id = ext["id"] info = self._ext_manager.get_extension_dict(ext_id) deps = info.get("state/dependencies", []) all_exts.add(ext_id) all_deps.update(deps) output = "[dependencies]\n" exported_exts = (all_exts - all_deps) if only_top_level else all_exts for e in exported_exts: if "-" not in e: print(f"skipping ext 1.0: {e}") continue name, version = ext_id_to_name_version(e) if name in excludes: continue output += '"{0}" = {{ version = "{1}", exact = true }}\n'.format(name, version) print(output) copy_text(output)
12,066
Python
42.88
118
0.436184
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/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. # from typing import Callable import omni.ui as ui from .ext_info_widget import ExtInfoWidget from .ext_status_bar import ExtStatusBar from .exts_graph_window import ExtsGraphWindow from .exts_list_widget import ExtsListWidget from .exts_properties_widget import ExtsPropertiesWidget from .styles import get_style class PageSwitcher: def __init__(self): self._main_pages = {} self._selected_page = None def add_page(self, name, widget): widget.set_visible(False) self._main_pages[name] = widget def select_page(self, name, force=False): if self._selected_page == name and not force: return # Set previous inviisible selected_page = self._main_pages.get(self._selected_page, None) if selected_page: selected_page.set_visible(False) # Set new and make visible self._selected_page = name selected_page = self._main_pages.get(self._selected_page, None) if selected_page: selected_page.set_visible(True) def destroy(self): self._main_pages = {} PAGE_GRAPH = "graph" PAGE_INFO = "info" PAGE_PROPERTIES = "properties" class ExtsWindow: """Extensions window""" def __init__(self, on_visibility_changed_fn: Callable): self._window = ui.Window("Extensions", width=1300, height=800, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self._window.set_visibility_changed_fn(on_visibility_changed_fn) # Tree view style self._exts_list_widget = ExtsListWidget() self._page_switcher = PageSwitcher() # Build UI with self._window.frame: with ui.HStack(style=get_style(self)): with ui.ZStack(width=0): # Draggable splitter with ui.Placer(offset_x=392, draggable=True, drag_axis=ui.Axis.X): ui.Rectangle(width=10, name="Splitter") with ui.HStack(): with ui.VStack(): # Extensions List Widget (on the left) self._exts_list_widget.build() # Status bar self._status_bar = ExtStatusBar() ui.Spacer(width=10) with ui.ScrollingFrame(vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.HStack(): # Selected Extension info self._ext_info_widget = ExtInfoWidget() self._page_switcher.add_page(PAGE_INFO, self._ext_info_widget) # Graph self._exts_graph = ExtsGraphWindow() self._page_switcher.add_page(PAGE_GRAPH, self._exts_graph) # Properties self._exts_properties = ExtsPropertiesWidget() self._page_switcher.add_page(PAGE_PROPERTIES, self._exts_properties) # Setup show graph callback self._exts_list_widget.set_show_graph_fn(lambda: self._show_graph(None)) self._exts_list_widget.set_show_properties_fn(self._show_properties) self._exts_list_widget.set_ext_selected_fn(self._select_ext) self._ext_info_widget.set_show_graph_fn(self._show_graph) self._select_ext(None) def _show_graph(self, ext_id: str): self._exts_list_widget.clear_selection() self._exts_graph.select_ext(ext_id) self._page_switcher.select_page(PAGE_GRAPH, force=True) def _show_properties(self): self._exts_list_widget.clear_selection() self._page_switcher.select_page(PAGE_PROPERTIES) def _select_ext(self, ext_summary): self._page_switcher.select_page(PAGE_INFO) self._ext_info_widget.select_ext(ext_summary) def destroy(self): """ Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ self._exts_graph.destroy() self._exts_graph = None self._ext_info_widget.destroy() self._ext_info_widget = None self._exts_list_widget.destroy() self._exts_list_widget = None self._exts_properties.destroy() self._exts_properties = None self._page_switcher.destroy() self._page_switcher = None self._window = None
4,868
Python
37.039062
106
0.609901
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/tests/test_properties_paths.py
import os import tempfile import omni.kit.app import omni.kit.test import omni.kit.window.extensions # pylint: disable=protected-access class TestPaths(omni.kit.test.AsyncTestCase): async def test_add_remove_user_path(self): manager = omni.kit.app.get_app().get_extension_manager() def get_paths(): return {p["path"] for p in manager.get_folders()} async def wait(): await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() def get_model(): omni.kit.window.extensions.get_instance()() return instance._window._exts_properties._paths_widget._model instance = omni.kit.window.extensions.get_instance()() instance.show_window(True) instance._window._show_properties() await wait() paths_before = get_paths() with tempfile.TemporaryDirectory() as tmp_dir: p0 = f"{tmp_dir}/0" p1 = f"{tmp_dir}/1" # Add new path using model get_model().add_empty() last = get_model()._children[-1] last.path_model.as_string = p0 get_model().save() # Ext manager creates it automatically self.assertTrue(os.path.exists(p0)) self.assertEqual(len(get_paths()) - len(paths_before), 1) # Add new path using model get_model().add_empty() last = get_model()._children[-1] last.path_model.as_string = p1 get_model().save() await wait() # Ext manager creates it automatically self.assertTrue(os.path.exists(p1)) self.assertEqual(len(get_paths()) - len(paths_before), 2) # Remove! get_model().remove_item(get_model()._children[-1]) await wait() self.assertEqual(len(get_paths()) - len(paths_before), 1) # Remove! get_model().remove_item(get_model()._children[-1]) await wait() self.assertEqual(get_paths(), paths_before)
2,114
Python
30.567164
73
0.566225
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/tests/__init__.py
# flake8: noqa from .test_properties_paths import * from .test_properties_registries import *
94
Python
22.749994
41
0.776596
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/tests/test_properties_registries.py
import carb.settings import omni.kit.app import omni.kit.test import omni.kit.window.extensions # pylint: disable=protected-access class TestRegistries(omni.kit.test.AsyncTestCase): async def test_add_remove_registry_UNRELIABLE(self): # noqa manager = omni.kit.app.get_app().get_extension_manager() settings = carb.settings.get_settings() def get_default(): return settings.get("/app/extensions/registryPublishDefault") def get_providers(): return {p["name"] for p in manager.get_registry_providers()} instance = omni.kit.window.extensions.get_instance()() instance.show_window(True) instance._window._show_properties() await omni.kit.app.get_app().next_update_async() def get_model(): widget = instance._window._exts_properties._registries_widget return widget._model model = get_model() model.set_default(model._children[0], True) providers_before = get_providers() default_before = get_default() self.assertEqual(model._children[0].name_model.as_string, default_before) # Add new registry using model model.add_empty() last = model._children[-1] last.url_model.as_string = "omniverse://kit-extensions.ov.nvidia.com/exts/kit/debug" # name is set automatically model.save() model = None # Wait to propagate and check await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() self.assertEqual(get_providers() - providers_before, {"kit/debug"}) # Make it default now get_model().set_default(get_model()._children[-1], True) await omni.kit.app.get_app().next_update_async() self.assertEqual(get_default(), "kit/debug") # Remove! get_model().remove_item(get_model()._children[-1]) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() self.assertEqual(get_providers(), providers_before) # get back default: get_model()._children[0].default_model.as_bool = True await omni.kit.app.get_app().next_update_async() self.assertEqual(get_default(), default_before)
2,310
Python
35.109374
92
0.635065
omniverse-code/kit/exts/omni.kit.window.extensions/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.1.1] - 2022-11-17 ### Updated - Switched out pyperclip for linux-friendly copy & paste ## [1.1.0] - 2022-05-06 ### Added - Added support for truncated words in extension search window ## [1.0.2] - 2020-12-07 ### Changed - Fix path_is_parent exception with different drive paths ## [1.0.1] - 2020-07-09 ### Changed - Don't produce symlink for icons in the extension folder ## [1.0.0] - 2020-07-08 ### Added - The initial release with minimal support of loading/unloading extensions and access to the external extension registry.
633
Markdown
25.416666
121
0.704581
omniverse-code/kit/exts/omni.kit.window.extensions/docs/index.rst
omni.kit.window.extensions ########################### Extensions Window
75
reStructuredText
11.666665
27
0.52
omniverse-code/kit/exts/omni.kit.test_helpers_gfx/omni/kit/test_helpers_gfx/__init__.py
from .compare_utils import *
28
Python
27.999972
28
0.785714
omniverse-code/kit/exts/omni.kit.test_helpers_gfx/omni/kit/test_helpers_gfx/compare_utils.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## """The utilities for image comparison""" import pathlib import sys import traceback import math from enum import Enum import numpy as np import carb import carb.tokens import omni.appwindow from omni.kit.test.teamcity import teamcity_publish_image_artifact class CompareError(Exception): pass class ComparisonMetric(Enum): MAX_DIFFERENCE = 0 # the maximum differrence between pixels. 0 is no difference. In the range [0-255]. PIXEL_COUNT = 1 # the total number of pixels that is not the same for two images MEAN_ERROR_SQUARED = 2 # Mean root square difference between pixels of two images PEAK_SIGNAL_TO_NOISE_RATIO = 3 def computeMSE(difference): components = len(difference.getpixel((0, 0))) errors = np.asarray(difference) / 255 return sum(np.mean(np.square(errors), axis = (0, 1))) / components def compare(image1: pathlib.Path, image2: pathlib.Path, image_diffmap: pathlib.Path, metric: ComparisonMetric = ComparisonMetric.MAX_DIFFERENCE): """ Compares two images and return a value that indicates the maximum differrence between pixels. 0 is no difference in the range [0-255]. It uses Pillow for image read. Args: image1, image2: images to compare image_diffmap: the difference map image will be saved if there is any difference between given images """ if not image1.exists(): raise CompareError(f"File image1 {image1} does not exist") if not image2.exists(): raise CompareError(f"File image2 {image2} does not exist") if "PIL" not in sys.modules.keys(): # Checking if we have Pillow imported try: from PIL import Image except ImportError: # Install Pillow if it's not installed import omni.kit.pipapi omni.kit.pipapi.install("Pillow", module="PIL") from PIL import Image from PIL import ImageChops original = Image.open(str(image1)) contrast = Image.open(str(image2)) if original.size != contrast.size: raise CompareError( f"[omni.ui.test] Can't compare different resolutions\n\n" f"{image1} {original.size[0]}x{original.size[1]}\n" f"{image2} {contrast.size[0]}x{contrast.size[1]}\n\n" f"It's possible that your monitor DPI is not 100%.\n\n" ) difference = ImageChops.difference(original, contrast) metric_value = 0.0 try: if metric is ComparisonMetric.MAX_DIFFERENCE: metric_value = sum([sum(i) for i in difference.convert("RGB").getextrema()]) if metric is ComparisonMetric.PIXEL_COUNT: metric_value = sum([sum( difference.getpixel((j, i))) > 0 for i in range(difference.height) for j in range(difference.width)]) if metric is ComparisonMetric.MEAN_ERROR_SQUARED: metric_value = computeMSE(difference) if metric is ComparisonMetric.PEAK_SIGNAL_TO_NOISE_RATIO: metric_value = computeMSE(difference) if metric_value < sys.float_info.epsilon: metric_value = math.inf metric_value = 10 * math.log10(1 / metric_value) except(): raise CompareError(f"[omni.ui.test] Can't compute metric {metric} \n\n") if metric_value > 0: # Images are different # Multiply image by 255 difference = difference.convert("RGB").point(lambda i: min(i * 255, 255)) difference.save(str(image_diffmap)) return metric_value def capture(image_name: str, output_img_dir: str, app_window: omni.appwindow.IAppWindow = None, use_log: bool = True): """ Captures frame. Args: image_name: the image name of the image and golden image. output_img_dir: the directory path that the capture will be saved to. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. """ image1 = pathlib.Path(output_img_dir).joinpath(image_name) if use_log: carb.log_info(f"[tests.compare] Capturing {image1}") import omni.renderer_capture capture_interface = omni.renderer_capture.acquire_renderer_capture_interface() capture_interface.capture_next_frame_swapchain(str(image1), app_window) def finalize_capture_and_compare(image_name: str, threshold: float, output_img_dir: str, golden_img_dir: str, app_window: omni.appwindow.IAppWindow = None, metric: ComparisonMetric = ComparisonMetric.MAX_DIFFERENCE): """ Finalizes capture and compares it with the golden image. Args: image_name: the image name of the image and golden image. threshold: the max threshold to collect TC artifacts. output_img_dir: the directory path that the capture will be saved to. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. app_window: IAppWindow instance for which the capture will happen, use None to capture default app window. Returns: A value that indicates the maximum difference between pixels. 0 is no difference in the range [0-255]. """ image1 = pathlib.Path(output_img_dir).joinpath(image_name) image2 = pathlib.Path(golden_img_dir).joinpath(image_name) image_diffmap = pathlib.Path(output_img_dir).joinpath(f"{pathlib.Path(image_name).stem}.diffmap.png") import omni.renderer_capture capture_interface = omni.renderer_capture.acquire_renderer_capture_interface() capture_interface.wait_async_capture(app_window) carb.log_info(f"[tests.compare] Comparing {image1} to {image2}") try: diff = compare(image1, image2, image_diffmap, metric) if diff >= threshold: teamcity_publish_image_artifact(image2, "golden", "Reference") teamcity_publish_image_artifact(image1, "results", "Generated") teamcity_publish_image_artifact(image_diffmap, "results", "Diff") return diff except CompareError as e: carb.log_error(f"[tests.compare] Failed to compare images for {image_name}. Error: {e}") exc = traceback.format_exc() carb.log_error(f"[tests.compare] Traceback:\n{exc}") async def capture_and_compare(image_name: str, threshold, output_img_dir: str, golden_img_dir: str, app_window: omni.appwindow.IAppWindow = None, use_log: bool = True, metric: ComparisonMetric = ComparisonMetric.MAX_DIFFERENCE): """ Captures frame and compares it with the golden image. Args: image_name: the image name of the image and golden image. threshold: the max threshold to collect TC artifacts. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. Returns: A value that indicates the maximum difference between pixels. 0 is no difference in the range [0-255]. """ capture(image_name, output_img_dir, app_window, use_log=use_log) await omni.kit.app.get_app().next_update_async() return finalize_capture_and_compare(image_name, threshold, output_img_dir, golden_img_dir, app_window, metric)
7,732
Python
38.454081
119
0.66865
omniverse-code/kit/exts/omni.kit.test_helpers_gfx/docs/index.rst
omni.kit.test_helpers_gfx ########################### Testing system helpers for graphics. Module that provides helpers that simplify writing tests, e.g. capture and compare screenshots, create windows, etc. .. automodule:: omni.kit.test_helpers_gfx :platform: Windows-x86_64, Linux-x86_64 :members: :show-inheritance: :undoc-members: :imported-members: :noindex: enum
397
reStructuredText
23.874999
116
0.675063
omniverse-code/kit/exts/omni.kit.window.usd_paths/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.4" category = "Core" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "USD Paths" description="Lists paths in USD file and allows editing" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "usd", "paths"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.commands" = {} "omni.usd" = {} "omni.ui" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.window.usd_paths" # That will make tests auto-discoverable by test_runner: [[python.module]] name = "omni.kit.window.usd_paths.tests" [[test]] stdoutFailPatterns.exclude = [ "*extension object is still alive*", # Ignore any leaks for startup tests to not block pipeline ]
1,096
TOML
25.756097
99
0.718978
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/scripts/__init__.py
from .usd_paths import *
25
Python
11.999994
24
0.72
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/scripts/usd_paths.py
import re import os import asyncio import carb import omni.ext import omni.kit.ui import omni.ui as ui from pxr import Usd, UsdGeom, UsdShade, UsdUtils, Ar, Sdf _extension_instance = None _extension_path = None class UsdPathsExtension(omni.ext.IExt): def __init__(self): self.USD_PATHS_TOOL_MENU = "Window/USD Paths" self._use_regex = False self._regex_button = None self._regex_button_style = { "Button.Label":{"font_size": 12.0}, "Button":{"margin": 2, "padding": 2}, "Button:checked":{"background_color": 0xFF114411}, "Button:hovered":{"background_color": 0xFF444444}, "Button:pressed":{"background_color": 0xFF111111}, } self._action_button_style = { "Button.Label:disabled":{"color": 0xFF666666}, "Button:disabled": {"background_color": 0xFF222222} } super().__init__() def on_startup(self, ext_id): global _extension_instance _extension_instance = self global _extension_path _extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id) self._unique_paths = {} self._window = None editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item(self.USD_PATHS_TOOL_MENU, self._show_ui, True, 10) editor_menu.set_value(self.USD_PATHS_TOOL_MENU, False) def on_shutdown(self): global _extension_instance global _template_list _extension_instance = None _template_list = None def _clean_up_paths_ui(self): if hasattr(self, "_scrollable") and self._scrollable is not None: self._window.layout.remove_child(self._scrollable) self._scrollable = None def _list_all_paths(self, path): if path not in self._scrollable_pending: self._scrollable_pending.append(path) return path def _modify_path(self, path): if path in self._unique_paths: return self._unique_paths[path].model.get_value_as_string() def _apply_path_edits(self, btn_widget=None): stage = omni.usd.get_context().get_stage() if not stage: carb.log_error("stage not found") return (all_layers, all_assets, unresolved_paths) = UsdUtils.ComputeAllDependencies(stage.GetRootLayer().identifier) if not all_layers: all_layers = stage.GetLayerStack() for layer in all_layers: UsdUtils.ModifyAssetPaths(layer, self._modify_path) self._traverse() self._btn_apply.enabled = False def _replace(self, btn_widget=None): if not self._unique_paths: self._traverse() for path in self._unique_paths: mdl_path = self._unique_paths[path].model.get_value_as_string() if self._use_regex: mdl_path = re.sub( self._txt_search.model.get_value_as_string(), self._txt_replace.model.get_value_as_string(), mdl_path, ) else: mdl_path = mdl_path.replace( self._txt_search.model.get_value_as_string(), self._txt_replace.model.get_value_as_string() ) self._unique_paths[path].model.set_value(mdl_path) self._btn_apply.enabled = True self._btn_replace.enabled = False def _toggle_block(self, is_enabled): self._txt_search.enabled = is_enabled self._txt_replace.enabled = is_enabled self._btn_replace.enabled = is_enabled if is_enabled: return self._btn_apply.enabled = False async def _wait_frame_finished(self, finish_fn): await omni.kit.app.get_app_interface().next_update_async() finish_fn() async def _preload_materials_from_stage(self, on_complete_fn): shaders = [] stage = omni.usd.get_context().get_stage() if not stage: carb.log_error("stage not found") return for p in stage.Traverse(): if p.IsA(UsdShade.Material): if not p.GetMetadata("ignore_material_updates"): material = UsdShade.Material(p) shader = material.ComputeSurfaceSource("mdl")[0] shaders.append(shader.GetPath().pathString) old_paths = omni.usd.get_context().get_selection().get_selected_prim_paths() omni.usd.get_context().get_selection().set_selected_prim_paths(shaders, True) await omni.kit.app.get_app_interface().next_update_async() await omni.kit.app.get_app_interface().next_update_async() def reload_old_paths(): omni.usd.get_context().get_selection().set_selected_prim_paths(old_paths, True) on_complete_fn() asyncio.ensure_future(self._wait_frame_finished(finish_fn=reload_old_paths)) def _traverse(self, btn_widget=None): self._unique_paths = {} self._scrollable.clear() self._scrollable_pending = [] self._toggle_block(False) def on_preload_complete(): with self._scrollable: with ui.VStack(spacing=2, height=0): self._scrollable_pending.sort() for path in self._scrollable_pending: text_box = ui.StringField(skip_draw_when_clipped=True) text_box.model.set_value(path) self._unique_paths[path] = text_box self._scrollable_pending = None if len(self._unique_paths) > 0: self._toggle_block(True) asyncio.ensure_future(self.get_asset_paths(on_preload_complete, self._list_all_paths)) def _build_ui(self): with self._window.frame: with ui.VStack(spacing=4): with ui.VStack(spacing=2, height=0): ui.Spacer(height=4) with ui.HStack(spacing=10, height=0): ui.Label("Search", width=60, alignment=ui.Alignment.RIGHT_CENTER) with ui.ZStack(height=0): self._txt_search = ui.StringField() with ui.HStack(): ui.Spacer(height=0) def toggle_regex(button): self._use_regex = not self._use_regex button.checked = self._use_regex def on_mouse_hover(hover_state): self._txt_search.enabled = not hover_state self._regex_button = ui.Button(width=0, text="Regex", style=self._regex_button_style) self._regex_button.set_clicked_fn(lambda b=self._regex_button: toggle_regex(b)) self._regex_button.set_mouse_hovered_fn(on_mouse_hover) ui.Spacer(width=10) ui.Spacer() with ui.HStack(spacing=10, height=0): ui.Label("Replace", width=60, alignment=ui.Alignment.RIGHT_CENTER) self._txt_replace = ui.StringField(height=0) ui.Spacer(width=10) ui.Spacer() with ui.HStack(spacing=10): ui.Spacer(width=56) ui.Button( width=0, style=self._action_button_style, clicked_fn=self._traverse, text=" Reload paths ") ui.Spacer() self._btn_replace = ui.Button( width=0, style=self._action_button_style, clicked_fn=self._replace, text=" Preview ", enabled=False) self._btn_apply = ui.Button( width=0, style=self._action_button_style, clicked_fn=self._apply_path_edits, text=" Apply ", enabled=False ) ui.Spacer() ui.Spacer(width=100) def on_text_changed(model): if self._btn_apply.enabled: self._btn_apply.enabled = False if not self._btn_replace.enabled: self._btn_replace.enabled = True self._txt_search.model.add_value_changed_fn(on_text_changed) self._txt_replace.model.add_value_changed_fn(on_text_changed) ui.Spacer(width=14) self._scrollable = ui.ScrollingFrame( text="ScrollingFrame", vertical_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON ) def _show_ui(self, menu, value): if self._window is None: window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._window = ui.Window( "USD Paths", width=400, height=400, flags=window_flags, dockPreference=omni.ui.DockPreference.LEFT_BOTTOM, ) self._window.set_visibility_changed_fn(self._on_visibility_changed) self._window.deferred_dock_in("Console", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) self._window.dock_order = 99 self._build_ui() if self._window: if value: self._window.visible = True else: self._window.visible = False def _on_visibility_changed(self, visible): omni.kit.ui.get_editor_menu().set_value(self.USD_PATHS_TOOL_MENU, visible) async def get_asset_paths(self, on_complete_fn, get_path_fn): stage = omni.usd.get_context().get_stage() if not stage: carb.log_error("stage not found") return def on_preload_complete(): (all_layers, all_assets, unresolved_paths) = UsdUtils.ComputeAllDependencies( stage.GetRootLayer().identifier ) if not all_layers: all_layers = stage.GetLayerStack() # all_layers doesn't include session layer, use that too session_layer = stage.GetSessionLayer() if not session_layer in all_layers: all_layers.append(session_layer) for layer in all_layers: UsdUtils.ModifyAssetPaths(layer, get_path_fn) on_complete_fn() await self._preload_materials_from_stage(on_preload_complete) def get_extension(): return Extension() def get_instance(): return _extension_instance def get_extension_path(sub_directory): global _extension_path path = _extension_path if sub_directory: path = os.path.normpath(os.path.join(path, sub_directory)) return path
11,339
Python
37.835616
117
0.529676
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/tests/create_prims.py
import os import carb 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") sunflower_hdr = omni.kit.window.usd_paths.get_extension_path("data/sunflowers.hdr") lenna_dds = omni.kit.window.usd_paths.get_extension_path("textures/lenna.dds") lenna_gif = omni.kit.window.usd_paths.get_extension_path("textures/lenna.gif") lenna_jpg = omni.kit.window.usd_paths.get_extension_path("textures/lenna.jpg") lenna_png = omni.kit.window.usd_paths.get_extension_path("textures/lenna.png") lenna_tga = omni.kit.window.usd_paths.get_extension_path("textures/lenna.tga") # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path=omni.usd.get_stage_next_free_path(stage, "{}/Looks".format(rootname), False), 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) # add additional files to shader omni.usd.create_material_input( ground_mat_prim, "diffuse_texture", Sdf.AssetPath(lenna_dds), Sdf.ValueTypeNames.Asset ) omni.usd.create_material_input(ground_mat_prim, "ao_texture", Sdf.AssetPath(lenna_gif), Sdf.ValueTypeNames.Asset) omni.usd.create_material_input( ground_mat_prim, "normalmap_texture", Sdf.AssetPath(lenna_jpg), Sdf.ValueTypeNames.Asset ) omni.usd.create_material_input( ground_mat_prim, "reflectionroughness_texture", Sdf.AssetPath(lenna_png), Sdf.ValueTypeNames.Asset ) omni.usd.create_material_input( ground_mat_prim, "metallic_texture", Sdf.AssetPath(lenna_tga), Sdf.ValueTypeNames.Asset ) # create GroundCube ground_cube_path = omni.usd.get_stage_next_free_path(stage, "{}/GroundCube".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=ground_cube_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) ground_cube_prim = stage.GetPrimAtPath(ground_cube_path) # set transform ground_cube_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, -50, 0)) ground_cube_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(2000, 1, 2000)) ground_cube_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:scale"] ) # set doNotCastShadows primvars_api = UsdGeom.PrimvarsAPI(ground_cube_prim) primvars_api.CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set misc omni.kit.commands.execute( "BindMaterial", prim_path=ground_cube_path, material_path=mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create DistantLight distant_light_path = omni.usd.get_stage_next_free_path(stage, "{}/DistantLight".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=distant_light_path, prim_type="DistantLight", select_new_prim=False, # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 attributes={UsdLux.Tokens.inputsAngle: 1.0, UsdLux.Tokens.inputsColor: Gf.Vec3f(1, 1, 1), UsdLux.Tokens.inputsIntensity: 2000} if hasattr(UsdLux.Tokens, 'inputsIntensity') else \ {UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.color: Gf.Vec3f(1, 1, 1), UsdLux.Tokens.intensity: 2000}, ) distant_light_prim = stage.GetPrimAtPath(distant_light_path) # set transform distant_light_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(1, 1.0000004, 1.0000004) ) distant_light_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(242.08, 327.06, 0) ) distant_light_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) distant_light_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create DomeLight dome_light_path = omni.usd.get_stage_next_free_path(stage, "{}/DomeLight".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=dome_light_path, prim_type="DomeLight", select_new_prim=False, # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 attributes={ UsdLux.Tokens.inputsIntensity: 1000, UsdLux.Tokens.inputsSpecular: 1, UsdLux.Tokens.inputsTextureFile: sunflower_hdr, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong, UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited, } if hasattr(UsdLux.Tokens, 'inputsIntensity') else \ { UsdLux.Tokens.intensity: 1000, UsdLux.Tokens.specular: 1, UsdLux.Tokens.textureFile: sunflower_hdr, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong, UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited, }, ) dome_light_prim = stage.GetPrimAtPath(dome_light_path) # set misc # https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4 if hasattr(UsdLux.Tokens, 'inputsShapingFocusTint'): dome_light_prim.GetAttribute(UsdLux.Tokens.inputsShapingFocusTint).Set(Gf.Vec3f(0, 0, 0)) dome_light_prim.GetAttribute(UsdLux.Tokens.inputsShapingFocus).Set(0) else: dome_light_prim.GetAttribute(UsdLux.Tokens.shapingFocusTint).Set(Gf.Vec3f(0, 0, 0)) dome_light_prim.GetAttribute(UsdLux.Tokens.shapingFocus).Set(0)
7,497
Python
47.374193
186
0.696012
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/tests/__init__.py
from .test_usd_paths import * from .create_prims import *
58
Python
18.66666
29
0.741379
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/tests/test_usd_paths.py
import os import unittest import carb import omni.kit.test class TestUsdPaths(omni.kit.test.AsyncTestCase): 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.window.usd_paths.tests.create_test_stage() async def tearDown(self): pass async def test_paths(self): found_paths = [] def get_all_paths(path): if path not in found_paths: found_paths.append(os.path.basename(path).lower()) return path def on_preload_complete(): paths = sorted( [ path for path in found_paths if path.endswith(".hdr") or path.endswith(".mdl") or path.find("lenna.") != -1 ] ) self.assertListEqual( paths, ["canary_wharf_4k.hdr", "lenna.dds", "lenna.gif", "lenna.jpg", "lenna.png", "lenna.tga", "omnipbr.mdl"], ) await omni.kit.window.usd_paths.get_instance().get_asset_paths(on_preload_complete, get_all_paths)
1,173
Python
29.894736
120
0.553282
omniverse-code/kit/exts/omni.kit.window.usd_paths/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.4] - 2022-02-11 ### Changes - reorganize UI ## [1.0.3] - 2020-12-01 ### Changes - fixed issues with apply button not enabled ## [1.0.2] - 2020-08-14 ### Changes - fixed issues with editor/stage not avaliable fixed issue with symlinks ## [1.0.1] - 2020-08-04 ### Changes - being created in source directory fixed issues with material paths not ## [1.0.0] - 2020-07-24 ### Changes - being listed converted to extension 2.0 added tests
542
Markdown
19.884615
80
0.680812
omniverse-code/kit/exts/omni.kit.window.usd_paths/docs/index.rst
omni.kit.window.usd_paths ########################### USD Paths Window .. toctree:: :maxdepth: 1 CHANGELOG
121
reStructuredText
7.133333
27
0.495868
omniverse-code/kit/exts/omni.kit.tagging/omni/tagging_client/__init__.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. from idl.connection.transport.ws import WebSocketClient from omni.discovery import DiscoverySearch from ._generated.client import * import asyncio class TaggingClientHelper: default_fb: str = "localhost:3020" def __init__(self, nucleus_server: str, tagging_fallback: str = default_fb, subscription_fallback: str = default_fb, suggestions_fallback: str = default_fb, discovery_timeout: float = 10): self.server = nucleus_server self.tagging_fallback = tagging_fallback self.subscription_fallback = subscription_fallback self.suggestions_fallback = suggestions_fallback self.transports = {} self.interfaces = {} self.timeout = discovery_timeout async def __aenter__(self): return self async def __aexit__(self, *args, **kwargs): await self.close() async def close(self): try: for i in self.interfaces.values(): await i.transport.close() for t in self.transports.values(): await t.close() except BaseException as e: print(e) async def get_tagging_service(self) -> TaggingService: return await self._get_service(TaggingService, self.tagging_fallback) async def get_tag_subscription_service(self) -> TagSubscription: return await self._get_service(TagSubscription, self.subscription_fallback) async def get_tag_suggestions_service(self) -> TagSuggestions: return await self._get_service(TagSuggestions, self.suggestions_fallback) async def _get_transport(self, fallback): if fallback in self.transports: return self.transports[fallback] else: print(f'discovery failed, trying fallback connection to {fallback}') transport = WebSocketClient(uri=f'ws://{fallback}') await transport.prepare() self.transports[fallback] = transport return transport async def _find_service(self, interface): async with DiscoverySearch(self.server) as search: return await search.find(interface, meta={"deployment": "external"}) async def _get_service(self, interface, fallback): if interface in self.interfaces: return self.interfaces[interface] else: instance = await self._create_interface(interface, fallback) self.interfaces[interface] = instance return instance async def _create_interface(self, interface, fallback): try: return await asyncio.wait_for(self._find_service(interface), timeout=self.timeout) except Exception: transport = await self._get_transport(fallback) return interface(transport) if transport else None
3,275
Python
38.469879
94
0.661374
omniverse-code/kit/exts/omni.kit.tagging/omni/discovery/__init__.py
import asyncio import logging import os import ssl import urllib.parse from typing import Callable, Optional, Awaitable, List, Dict from idl.connection.marshallers import Marshaller from idl.connection.transport import Client, TransportSettings, TransportError from idl.connection.transport.http import HttpClient from idl.connection.transport.http_file import HttpFileClient from idl.connection.transport.omni import OmniClientTransport from idl.connection.transport.ws import WebSocketClient from idl.data.serializers import Serializer from idl.data.serializers.json import JSONSerializer from idl.types import Record from omni.discovery.client import ( DiscoveryRegistration as DiscoveryRegistrationClient, DiscoverySearch as DiscoverySearchClient ) from omni.discovery.data import ( Manifest, HealthStatus, Meta, HealthCheck, DiscoverInterfaceQuery, ServiceInterface, SupportedTransport, ) logger = logging.getLogger("omni.discovery") sentinel = object() Stop = bool DISCOVERY_ENDPOINT = "/omni/discovery" class DiscoveryManifest(Record): token: str interfaces: list transport: TransportSettings meta: Optional[Meta] class DiscoveryRegistration: def __init__(self, uri: str, ssl_context: ssl.SSLContext = None, *, conn_timeout: float = 5.0): self.uri = uri self.ssl_context = ssl_context self.conn_timeout = conn_timeout async def register(self, manifest: DiscoveryManifest, on_check: Callable[[HealthCheck], Awaitable[Optional[Stop]]] = None, retry_timeout: float = 5.0): registered_manifest = Manifest( token=manifest.token, transport=manifest.transport, meta=manifest.meta, interfaces={ interface.__interface_name__: ServiceInterface( origin=interface.__interface_origin__, name=interface.__interface_name__, capabilities=getattr(interface, "__interface_capabilities__", None) ) for interface in manifest.interfaces } ) info = "\n".join([ f" Discovery URI: {self.uri}", f" Transport settings: {registered_manifest.transport}", f" Meta: {registered_manifest.meta}" ]) logger.info(f"Registering the service in the discovery with these parameters:\n{info}") running = True while running: try: registering = True ws = await connect(self.uri, self.ssl_context, timeout=self.conn_timeout) if ws is None: raise ConnectionError(f"Failed to connect to the discovery service {self.uri}") async with DiscoveryRegistrationClient(ws) as discovery: async for health_check in discovery.register(registered_manifest): if on_check: stop = await on_check(health_check) if stop: break if health_check.status == HealthStatus.OK: if registering: if manifest.meta: logger.info(f"Registered in {self.uri} with {manifest.meta} meta.") else: logger.info(f"Registered in {self.uri}.") registering = False else: logger.error( f"Can't register the service: {health_check.message or health_check.status}.\n" f"Info:\n{info}" ) if registering: running = False break except asyncio.CancelledError: return except Exception as exc: logger.exception( f"An error has occurred while registering the service in the discovery.\n" f"Info:\n{info}", exc_info=exc ) try: loop = asyncio.get_event_loop() except RuntimeError: break else: if loop.is_closed(): break await asyncio.sleep(retry_timeout) class DiscoverySearch: def __init__(self, uri: str, ssl_context: ssl.SSLContext = None): self._uri = uri self._ssl_context = ssl_context self._ws: Optional[WebSocketClient] = None self._closing: Optional[asyncio.Task] = None async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_val, exc_tb): await self.close() async def find( self, interface, meta: Meta = None, supported_transport: Optional[List[SupportedTransport]] = sentinel, capabilities: Dict[str, int] = None, *, timeout: float = 5.0 ): if supported_transport is sentinel: supported_transport = list(Client.get_supported()) ws = await self._connect(timeout) discovery = DiscoverySearchClient(ws) origin = interface.__interface_origin__ interface_name = interface.__interface_name__ if capabilities is None: capabilities = getattr(interface, "__interface_capabilities__", None) try: response = await discovery.find(DiscoverInterfaceQuery( service_interface=ServiceInterface( origin=origin, name=interface_name, capabilities=capabilities ), supported_transport=supported_transport, meta=meta )) except TransportError as exc: raise ConnectionError(f"Failed to communicate with the discovery service {self._uri}.") from exc if not response.found: raise ConnectionError( f"Interface {interface_name!r} from {origin!r} has not been found." ) transport = Client.create(response.transport) try: await transport.prepare() except Exception as exc: msg = "\n".join([ f"An error has occurred when tried to establish a connection to {interface.__name__}.", f"Info: ", f" Discovery URI: {self._uri}", f" Interface: {interface_name}", f" Meta: {meta}", f" Response: {response}", ]) raise ConnectionError(msg) from exc return interface(transport) async def close(self): if self._closing: self._closing.cancel() if self._ws: await self._ws.close() async def _connect(self, timeout: float = 5.0): if self._ws is not None: return self._ws ws = await connect(self._uri, self._ssl_context, timeout=timeout) if ws is None: raise ConnectionError(f"Failed to connect to the discovery service {self._uri}.") loop = asyncio.get_event_loop() if self._closing: self._closing.cancel() self._ws = ws self._closing = loop.create_task(self._wait_closed()) return self._ws async def _wait_closed(self): if self._ws is not None: await self._ws.closed.wait() self._ws = None async def connect(uri: str, ssl_context: ssl.SSLContext, *, timeout: float = 5.0) -> Optional[WebSocketClient]: loop = asyncio.get_event_loop() url = parse_url(uri) hostname = url.hostname # Path-based routing is not used on Workstation setup: # https://nvidia-omniverse.atlassian.net/browse/OM-32965 force_pbr = int(os.getenv("OMNI_DISCOVERY_FORCE_PBR", "0")) if hostname in ("localhost", "127.0.0.1", "::1") and not force_pbr: ws_port_based_client_task = loop.create_task(create_port_based_client(uri, ssl_context=ssl_context)) done, pending = await asyncio.wait({ws_port_based_client_task}, timeout=timeout) if ws_port_based_client_task in done: return ws_port_based_client_task.result() else: ws_port_based_client_task.cancel() else: wss_path_based_client_task = loop.create_task( create_path_based_client(uri, scheme="wss", ssl_context=ssl_context) ) ws_path_based_client_task = loop.create_task( create_path_based_client(uri, scheme="ws", ssl_context=ssl_context) ) ws_port_based_client_task = loop.create_task( create_port_based_client(uri, ssl_context=ssl_context) ) tasks = [ wss_path_based_client_task, ws_path_based_client_task, ws_port_based_client_task, ] done = [] try: ws_timeout = loop.create_task(asyncio.sleep(timeout)) done, pending = await asyncio.wait( {wss_path_based_client_task, ws_timeout}, return_when=asyncio.FIRST_COMPLETED, ) if wss_path_based_client_task in done: ws = wss_path_based_client_task.result() if ws: return ws done, pending = await asyncio.wait( {ws_path_based_client_task, ws_timeout}, return_when=asyncio.FIRST_COMPLETED ) if ws_path_based_client_task in done: ws = ws_path_based_client_task.result() if ws: return ws done, pending = await asyncio.wait( {ws_port_based_client_task, ws_timeout}, return_when=asyncio.FIRST_COMPLETED ) if ws_port_based_client_task in done: ws = ws_port_based_client_task.result() if ws: return ws finally: for task in tasks: if task not in done: if task.done(): ws: WebSocketClient = task.result() if ws: try: await ws.close() except: pass else: task.cancel() async def create_path_based_client(uri: str, scheme: str = "wss", ssl_context: ssl.SSLContext = None) -> Optional[WebSocketClient]: url = parse_url(uri, default_scheme=scheme) path = url.path.rstrip("/") + DISCOVERY_ENDPOINT hostname = url.hostname port = url.port scheme = url.scheme if port: uri = f"{scheme}://{hostname}:{port}{path}" else: uri = f"{scheme}://{hostname}{path}" try: ws = WebSocketClient(uri=uri, ssl_context=ssl_context) await ws.prepare() return ws except Exception as exc: msg = f"Failed to connect to the discovery service using path-based routing ({uri})." logger.debug(msg, exc_info=exc) return None async def create_port_based_client(uri: str, ssl_context: ssl.SSLContext = None) -> Optional[WebSocketClient]: url = parse_url(uri, default_scheme="ws") hostname = url.hostname port = url.port scheme = url.scheme if not port: port = "3333" uri = f"{scheme}://{hostname}:{port}" try: ws = WebSocketClient(uri=uri, ssl_context=ssl_context) await ws.prepare() return ws except Exception as exc: msg = f"Failed to connect to the discovery service using port-based routing ({uri})." logger.debug(msg, exc_info=exc) return None def parse_url(value: str, default_scheme: str = "ws") -> urllib.parse.ParseResult: url = urllib.parse.urlparse(value) if not url.scheme: url = urllib.parse.urlparse(f"{default_scheme}://{value}") return url Serializer.register(JSONSerializer) Marshaller.register(Marshaller) Client.register(HttpClient) Client.register(HttpFileClient) Client.register(WebSocketClient) Client.register(OmniClientTransport)
12,344
Python
35.308823
131
0.559786
omniverse-code/kit/exts/omni.kit.tagging/omni/discovery/data.py
from typing import List, Optional, Dict, AsyncIterator from idl.types import Enum, Record, Literal Capabilities = Dict[str, int] DiscoverySearchServerRemoteCapabilities = Capabilities DiscoverySearchServerLocalCapabilities = {'find': 2, 'find_all': 2} DiscoverySearchServerCapabilities = DiscoverySearchServerRemoteCapabilities DiscoverySearchClientRemoteCapabilities = Capabilities DiscoverySearchClientLocalCapabilities = {'find': 2, 'find_all': 2} DiscoverySearchClientCapabilities = DiscoverySearchClientLocalCapabilities DiscoverySearchFindAllServerRemoteVersion = int DiscoverySearchFindAllServerLocalVersion = 2 DiscoverySearchFindAllServerVersion = DiscoverySearchFindAllServerRemoteVersion DiscoverySearchFindAllClientRemoteVersion = int DiscoverySearchFindAllClientLocalVersion = 2 DiscoverySearchFindServerRemoteVersion = int DiscoverySearchFindServerLocalVersion = 2 DiscoverySearchFindServerVersion = DiscoverySearchFindServerRemoteVersion DiscoverySearchFindClientRemoteVersion = int DiscoverySearchFindClientLocalVersion = 2 DiscoveryRegistrationServerRemoteCapabilities = Capabilities DiscoveryRegistrationServerLocalCapabilities = {'register': 2, 'register_unsafe': 2, 'unregister_unsafe': 2} DiscoveryRegistrationServerCapabilities = DiscoveryRegistrationServerRemoteCapabilities DiscoveryRegistrationClientRemoteCapabilities = Capabilities DiscoveryRegistrationClientLocalCapabilities = {'register': 2, 'register_unsafe': 2, 'unregister_unsafe': 2} DiscoveryRegistrationClientCapabilities = DiscoveryRegistrationClientLocalCapabilities DiscoveryRegistrationUnregisterUnsafeServerRemoteVersion = int DiscoveryRegistrationUnregisterUnsafeServerLocalVersion = 2 DiscoveryRegistrationUnregisterUnsafeServerVersion = DiscoveryRegistrationUnregisterUnsafeServerRemoteVersion DiscoveryRegistrationUnregisterUnsafeClientRemoteVersion = int DiscoveryRegistrationUnregisterUnsafeClientLocalVersion = 2 DiscoveryRegistrationRegisterUnsafeServerRemoteVersion = int DiscoveryRegistrationRegisterUnsafeServerLocalVersion = 2 DiscoveryRegistrationRegisterUnsafeServerVersion = DiscoveryRegistrationRegisterUnsafeServerRemoteVersion DiscoveryRegistrationRegisterUnsafeClientRemoteVersion = int DiscoveryRegistrationRegisterUnsafeClientLocalVersion = 2 DiscoveryRegistrationRegisterServerRemoteVersion = int DiscoveryRegistrationRegisterServerLocalVersion = 2 DiscoveryRegistrationRegisterServerVersion = DiscoveryRegistrationRegisterServerRemoteVersion DiscoveryRegistrationRegisterClientRemoteVersion = int DiscoveryRegistrationRegisterClientLocalVersion = 2 Meta = Dict[str, str] class HealthStatus(metaclass=Enum): OK = "OK" Closed = "CLOSED" Denied = "DENIED" AlreadyExists = "ALREADY_EXISTS" InvalidSettings = "INVALID_SETTINGS" InvalidCapabilities = "INVALID_CAPABILITIES" class ServiceInterface(Record): origin: str name: str capabilities: Optional[Capabilities] class TransportSettings(Record): name: str params: str meta: Meta ServiceInterfaceMap = Dict[str, ServiceInterface] class SupportedTransport(Record): name: str meta: Optional[Meta] class SearchResult(Record): found: bool version: Optional[int] service_interface: Optional[ServiceInterface] transport: Optional[TransportSettings] meta: Optional[Meta] DiscoverySearchFindAllClientVersion = DiscoverySearchFindAllClientLocalVersion DiscoverySearchFindClientVersion = DiscoverySearchFindClientLocalVersion class DiscoverInterfaceQuery(Record): service_interface: ServiceInterface supported_transport: Optional[List[SupportedTransport]] meta: Optional[Meta] class HealthCheck(Record): status: HealthStatus time: str version: Optional[int] message: Optional[str] meta: Optional[Meta] DiscoveryRegistrationUnregisterUnsafeClientVersion = DiscoveryRegistrationUnregisterUnsafeClientLocalVersion class Manifest(Record): interfaces: ServiceInterfaceMap transport: TransportSettings token: str meta: Optional[Meta] DiscoveryRegistrationRegisterUnsafeClientVersion = DiscoveryRegistrationRegisterUnsafeClientLocalVersion DiscoveryRegistrationRegisterClientVersion = DiscoveryRegistrationRegisterClientLocalVersion
4,228
Python
35.456896
109
0.854778
omniverse-code/kit/exts/omni.kit.tagging/omni/discovery/client.py
from typing import AsyncIterator, Dict, List, Optional from idl.connection.transport import Client from idl.types import Literal, Record from .data import * class DiscoverySearch: def __init__(self, transport: Client): self.transport = transport async def __aenter__(self) -> 'DiscoverySearch': await self.transport.prepare() return self async def __aexit__(self, exc_type, exc_val, exc_tb): await self.transport.close() async def find(self, query: DiscoverInterfaceQuery) -> SearchResult: """ Finds an entry for specified origin and interface. A query can specify the required capabilities, connection settings and other metadata. """ _request = {} _request["query"] = query _request["version"] = DiscoverySearchFindClientVersion _response = await self.transport.call("DiscoverySearch", "find", _request, request_type=DiscoverySearchFindArgs, return_type=SearchResult) return _response async def find_all(self, ) -> AsyncIterator[SearchResult]: """ Retrieves all registered interfaces for this discovery service. """ _request = {} _request["version"] = DiscoverySearchFindAllClientVersion agen = self.transport.call_many("DiscoverySearch", "find_all", _request, request_type=DiscoverySearchFindAllArgs, return_type=SearchResult) try: async for _response in agen: yield _response finally: await agen.aclose() __interface_name__ = "DiscoverySearch" __interface_origin__ = "Discovery.idl.ts" __interface_capabilities__ = DiscoverySearchClientLocalCapabilities class DiscoveryRegistration: def __init__(self, transport: Client): self.transport = transport async def __aenter__(self) -> 'DiscoveryRegistration': await self.transport.prepare() return self async def __aexit__(self, exc_type, exc_val, exc_tb): await self.transport.close() async def register(self, manifest: Manifest) -> AsyncIterator[HealthCheck]: """ Registers a new service with specified connection settings and interfaces. The discovery keeps a subscription to ensure that registered service is still available. The service is removed from discovery as soon as it stops receiving health checks from the subscription. You can use `register_unsafe` to register a service without a subscription and health checks. """ _request = {} _request["manifest"] = manifest _request["version"] = DiscoveryRegistrationRegisterClientVersion agen = self.transport.call_many("DiscoveryRegistration", "register", _request, request_type=DiscoveryRegistrationRegisterArgs, return_type=HealthCheck) try: async for _response in agen: yield _response finally: await agen.aclose() async def register_unsafe(self, manifest: Manifest) -> HealthCheck: """ Registers a new service without a health checking. It's a service responsibility to call `unregister_unsafe` when the provided functions become not available. """ _request = {} _request["manifest"] = manifest _request["version"] = DiscoveryRegistrationRegisterUnsafeClientVersion _response = await self.transport.call("DiscoveryRegistration", "register_unsafe", _request, request_type=DiscoveryRegistrationRegisterUnsafeArgs, return_type=HealthCheck) return _response async def unregister_unsafe(self, manifest: Manifest) -> HealthCheck: """ Removes the service registered with `register_unsafe` from the discovery. """ _request = {} _request["manifest"] = manifest _request["version"] = DiscoveryRegistrationUnregisterUnsafeClientVersion _response = await self.transport.call("DiscoveryRegistration", "unregister_unsafe", _request, request_type=DiscoveryRegistrationUnregisterUnsafeArgs, return_type=HealthCheck) return _response __interface_name__ = "DiscoveryRegistration" __interface_origin__ = "Discovery.idl.ts" __interface_capabilities__ = DiscoveryRegistrationClientLocalCapabilities class DiscoverySearchFindArgs(Record): query: DiscoverInterfaceQuery version: Optional[Literal(DiscoverySearchFindClientVersion)] = DiscoverySearchFindClientVersion class DiscoverySearchFindAllArgs(Record): version: Optional[Literal(DiscoverySearchFindAllClientVersion)] = DiscoverySearchFindAllClientVersion class DiscoveryRegistrationRegisterArgs(Record): manifest: Manifest version: Optional[Literal(DiscoveryRegistrationRegisterClientVersion)] = DiscoveryRegistrationRegisterClientVersion class DiscoveryRegistrationRegisterUnsafeArgs(Record): manifest: Manifest version: Optional[Literal(DiscoveryRegistrationRegisterUnsafeClientVersion)] = DiscoveryRegistrationRegisterUnsafeClientVersion class DiscoveryRegistrationUnregisterUnsafeArgs(Record): manifest: Manifest version: Optional[Literal(DiscoveryRegistrationUnregisterUnsafeClientVersion)] = DiscoveryRegistrationUnregisterUnsafeClientVersion
5,323
Python
38.731343
182
0.698854
omniverse-code/kit/exts/omni.kit.tagging/omni/kit/tagging/__init__.py
from .scripts.taggingservice import *
38
Python
18.499991
37
0.815789
omniverse-code/kit/exts/omni.kit.tagging/omni/kit/tagging/scripts/taggingservice.py
import carb import carb.events import asyncio import omni.client import omni.kit.tagging from idl.connection.transport import TransportError # rename this to omni.tagging.client after omni.tagging is deprecated import omni.tagging_client as tagging_client class TaggingClientContextAsync: """Create a tag client context.""" def __init__(self, ov_server, **kwargs): self.ov_server = ov_server async def init_client(self): """Create tagging client.""" self._helper = tagging_client.TaggingClientHelper(self.ov_server) # connect to the tagging service self.service = await self._helper.get_tagging_service() # check that tagging server is responding res = await self.service.generate_client_id() # get the ID of the client (this will likely be deprecated) self.client_id = res.client_id async def close_client(self, client_msg: str = None, *args, **kwargs): """Close tagging client.""" await self._helper.__aexit__(*args, **kwargs) # log the given message on success if client_msg is not None: tag_utils_logger.debug(client_msg) class OmniKitTaggingDelegate: """Delegate that handles when async tagging events are finished. """ def updated_tags_for_url(self, url: str): pass def finished_getting_tags(self, urls: str): pass class OmniKitTagging(omni.ext.IExt): """The Tagging plugin. This plugin holds tagging client contexts.""" static_instance = None def on_startup(self): OmniKitTagging.static_instance = self self._connections = {} self._auth_tokens = {} self._path_results = {} self._tagging_clients = {} self._conn_subscription = omni.client.register_connection_status_callback(self._server_status_changed) self._delegate = None self._initializing = False def on_shutdown(self): for client in self._tagging_clients: asyncio.ensure_future(self._tagging_clients[client].close_client()) self._tagging_clients = None self._conn_subscription = None self._auth_subscription = None self._delegate = None OmniKitTagging.static_instance = None def set_delegate(self, delegate: OmniKitTaggingDelegate): self._delegate = delegate def _server_status_changed(self, url, status): def _server_info_callback(result, server_info): nonlocal url broken_url = omni.client.break_url(url) if result == omni.client.Result.OK: self._auth_tokens[broken_url.host] = server_info.auth_token else: carb.log_error(f"Server info error: {str(result)}") broken_url = omni.client.break_url(url) if status == omni.client.ConnectionStatus.CONNECTED: self._connections[broken_url.host] = True omni.client.get_server_info_with_callback(url, _server_info_callback) else: self._connections[broken_url.host] = False async def _verify_connection(self, host): if host is None: return False if host not in self._connections: carb.log_warn(f"Unable to get tags. Not connected to host: {host}") return False if host not in self._auth_tokens: carb.log_error(f"Error getting auth token for host: {host}") return False if host not in self._tagging_clients: self._initializing = True self._tagging_clients[host] = TaggingClientContextAsync(ov_server=host) await self._tagging_clients[host].init_client() self._initializing = False if self._tagging_clients[host].service is None: carb.log_error(f"Error creating tagging client service on {host}") return False return True def tags_action(self, url, new_tag, action="add", old_tag=None): if action.lower() == "add": modify_type = tagging_client.TagModifyType.Add elif action.lower() == "set": modify_type = tagging_client.TagModifyType.Set elif action.lower() == "reset": modify_type = tagging_client.TagModifyType.Reset elif action.lower() == "remove": modify_type = tagging_client.TagModifyType.Remove elif action.lower() == "update": modify_type = tagging_client.TagModifyType.Remove asyncio.ensure_future(self.tags_action_async(url, old_tag, modify_type)) modify_type = tagging_client.TagModifyType.Add else: carb.log_error(f"provided action is currently not supported: ({action})") asyncio.ensure_future(self.tags_action_async(url, new_tag, modify_type)) async def tags_action_async(self, url, tag, modify_type): broken_url = omni.client.break_url(url) host = broken_url.host if not await self._verify_connection(host): return tag_dict = self.validate_tag(tag) if tag_dict: # 5 second timout for service initialization. timeout = 5.0 while self._initializing and timeout > 0: await asyncio.sleep(0.5) timeout -= 0.5 constructed_tag = tagging_client.Tag( name=tag_dict["key"], tag_namespace=tag_dict["full_namespace"], value=tag_dict["value"] ) try: # get the tags results = await self._tagging_clients[host].service.modify_tags( auth_token=self._auth_tokens[host], client_id=self._tagging_clients[host].client_id, paths=[broken_url.path], tags=[constructed_tag], modify_type=modify_type, ) except AttributeError: # service is still being initialized carb.log_warn("Timeout waiting for tagging service initialization") return except TransportError as msg: # lost connection to tagging service carb.log_warn(f"TransportError: {msg}") self._tagging_clients = {} return if self._delegate: self._delegate.updated_tags_for_url(url) def get_tags(self, urls, callback): asyncio.ensure_future(self.get_tags_async(urls, callback)) async def get_tags_async(self, urls, callback=None): paths = {} for url in urls: broken_url = omni.client.break_url(url) host = broken_url.host if not await self._verify_connection(host): return # 5 second timout for service initialization. timeout = 5.0 while self._initializing and timeout > 0: await asyncio.sleep(0.5) timeout -= 0.5 if host not in paths: paths[host] = [broken_url.path] else: paths[host].append(broken_url.path) for host in paths: try: # get the tags results = await self._tagging_clients[host].service.get_tags( auth_token=self._auth_tokens[host], paths=paths[host] ) except AttributeError as msg: # service is still being initialized carb.log_warn(f"Timeout waiting for tagging service initialization: {msg}") return except TransportError as msg: # lost connection to tagging service self._tagging_clients = {} return for i, result in enumerate(results["path_result"]): if result["connection_status"] != 1: # OmniTaggingStatusCodeOk carb.log_warn(f"Tagging Connection Error Code: {result['connection_status']}") self._tagging_clients = {} return # TODO check connection status if host not in self._path_results: self._path_results[host] = {} self._path_results[host][paths[host][i]] = result["tags"] if callback is not None: callback() if self._delegate: self._delegate.finished_getting_tags(urls) return self.tags_for_url(urls[0]) def tags_for_url(self, url): broken_url = omni.client.break_url(url) host = broken_url.host path = broken_url.path if host in self._path_results and path in self._path_results[host]: return self._path_results[host][path] def pack_tag(self, namespace, hidden_label, kv_pair=None, key=None, value=None): """ Changes a keyvalue pair tag into a string like "namespace.key=value" Adds a leading . when the namespace has one, and ommits the =value when no value is present. Format of tags: [namespace].[key]{=value} .[namespace].[label].[key]{=value} For Example: appearance.car .appearance.generated.truck=60 .appearance.excluded.banana tag_without_namespace .excluded.tag_without_namespace """ if kv_pair is None: if not value: kv_pair = key else: kv_pair = key + "=" + value if hidden_label and len(hidden_label) > 0: if namespace == "": return ".".join(["", hidden_label, kv_pair]) return ".".join(["", namespace, hidden_label, kv_pair]) if namespace == "": return kv_pair return ".".join([namespace, kv_pair]) def validate_tag(self, tag, allow_hidden_tags=True): """ Validate the tag, make sure there is a category, namespace, and key, and return the dict if valid. """ is_hidden = False namespace = None hidden_label = None kv_split = tag.split("=") full_key = kv_split[0] val = "" if len(kv_split) > 2: carb.log_warn(f"Too many '=' characters in tag: {tag}") return False if ".." in full_key: carb.log_warn(f"Invalid tag (too many consecutive .'s): {tag}") return False if len(kv_split) > 1: val = kv_split[1] dot_split = full_key.split(".") # the full_namespace combines the hidden/system namespace with the normal one. if len(dot_split) <= 1: key = full_key full_namespace = "" else: key = dot_split[-1] full_namespace = ".".join(dot_split[:-1]) # remove the key dot_split = dot_split[:-1] if len(dot_split) >= 1 and dot_split[0] == "": # a hidden/system namespace begins with a . is_hidden = True # remove the empty string dot_split = dot_split[1:] if len(dot_split) == 0: carb.log_warn(f"Tag has an empty system namespace: {tag}") return False elif len(dot_split) == 1: namespace = "" hidden_label = "." + dot_split[0] else: # a namespace may contain multiple .'s, but the system namespace may not hidden_label = "." + dot_split[-1] namespace = ".".join(dot_split[:-1]) else: if full_namespace == "": namespace = "" else: namespace = ".".join(dot_split) if not key: return False if is_hidden and not allow_hidden_tags: return False return { "hidden_label": hidden_label, "namespace": namespace, "key": key, "value": val, "full_namespace": full_namespace, } def ordered_tag_list(self, tag_dict_list): """ Returns a sorted (user tags, then generated in order of value) list of unique tags. """ tag_tuples = [] namespaces = list(set([d["tag_namespace"] for d in tag_dict_list])) user_namespaces = [] generated_namespaces = [] excluded_namespaces = [] for n in namespaces: if n[0] != ".": user_namespaces.append(n) elif n[0] == "." and n.split(".")[-1] == "generated": generated_namespaces.append(n) elif n[0] == "." and n.split(".")[-1] == "excluded": excluded_namespaces.append(n) user_namespaces.sort() generated_namespaces.sort() for gen_namespace in generated_namespaces: stripped = gen_namespace[1 : -(1 + len("generated"))] if stripped not in user_namespaces: user_namespaces.append(stripped) def safe_int(value): try: return int(value) except ValueError: return 0 # for each namespace, add user tags # then add generated tags (if they are not already added or excluded) sorted by value for n in user_namespaces: g = "." + n + ".generated" e = "." + n + ".excluded" # tags will contain tuples (name, value) tags = [] excluded = [] for tag_dict in tag_dict_list: if tag_dict["tag_namespace"] == n: tags.append((tag_dict["name"], 100)) elif tag_dict["tag_namespace"] == e and tag_dict["name"] not in tags: excluded.append(tag_dict["name"]) for tag_dict in tag_dict_list: if tag_dict["tag_namespace"] == g: if tag_dict["name"] not in tags and tag_dict["name"] not in excluded: tags.append((tag_dict["name"], safe_int(tag_dict["value"]))) if len(tags) > 0: # sort by name, then by value descending tags.sort(key=lambda x: x[0]) tag_tuples += sorted(tags, key=lambda x: -x[1]) tags = [] for t in tag_tuples: # prevent duplicates if t[0] not in tags: tags.append(t[0]) return tags def unpack_raw_tags(self, tag_dict_list): """ Changes a list of strings into a dictionary. Example tag: {'name': 'notebook', 'tag_namespace': 'appearance', 'value': ''} Example tag: {'name': 'book', 'tag_namespace': 'appearance.generated', 'value': '50'} Returns a dictionary like: { "appearance": { "car": "", ".generated": { "truck": 99 }, ".excluded": { "banana": "" } } } """ tags = {} namespace = None for tag_dict in tag_dict_list: # join the namespace to the name and value of the tag. # Examples: appearance.notebook, appearance.generated.book=10 if tag_dict["tag_namespace"] == "": tag = tag_dict["name"] else: tag = ".".join([tag_dict["tag_namespace"], tag_dict["name"]]) if "value" in tag_dict and tag_dict["value"]: tag = f"{tag}={tag_dict['value']}" # recover namespace, key, value from single string tag = self.validate_tag(tag) if tag: hidden_label = tag["hidden_label"] namespace = tag["namespace"] key = tag["key"] val = tag["value"] if len(val) > 50: val = "(value too long to display)" if namespace not in tags: tags[namespace] = {} if hidden_label and hidden_label not in tags[namespace]: tags[namespace][hidden_label] = {} if hidden_label: tags[namespace][hidden_label][key] = val else: tags[namespace][key] = val return tags def get_tagging_instance(): return OmniKitTagging.static_instance
16,316
Python
35.179601
110
0.53898
omniverse-code/kit/exts/omni.kit.tagging/omni/kit/tagging/tests/test_tagging_plugin.py
import asyncio import math import unittest import omni.kit.test from omni.kit.tagging import get_tagging_instance class TestTaggingPlugin(omni.kit.test.AsyncTestCase): async def test_tagging_plugin_load(self): tagging_interface = get_tagging_instance() self.assertTrue(tagging_interface is not None) async def test_tagging_validation(self): tagging_interface = get_tagging_instance() valid_tags = [ "book", "book=10", "appearance.book", "appearance.book=10", "appearance.generated.book", "appearance.generated.book=10", "visual.appearance.generated.book", "visual.appearance.generated.book=10", ".appearance.generated.book", ".appearance.generated.book=10", ".generated.book", ".generated.book=10", ] invalid_tags = ["", ".", "a=b=c", "...", ".test", "test.", "test.=1", "test..test", "test..test=10"] for tag in valid_tags: self.assertTrue(tagging_interface.validate_tag(tag)) for tag in invalid_tags: self.assertFalse(tagging_interface.validate_tag(tag)) async def test_sorted_tags(self): expected_dict = [ {"name": "binder", "tag_namespace": ".appearance.generated", "value": "50"}, {"name": "notebook", "tag_namespace": "appearance", "value": ""}, {"name": "book", "tag_namespace": "appearance", "value": ""}, {"name": "book", "tag_namespace": ".appearance.generated", "value": "80"}, {"name": "Lighter", "tag_namespace": ".ImageNet.generated", "value": "36"}, {"name": "Wafer", "tag_namespace": ".ImageNet.generated", "value": "47"}, {"name": "Knife", "tag_namespace": ".ImageNet.generated", "value": "2"}, {"name": "Knife", "tag_namespace": ".ImageNet.excluded", "value": ""}, ] sorted_tags = ["book", "notebook", "binder", "Wafer", "Lighter"] tagging_interface = get_tagging_instance() ordered_tags = tagging_interface.ordered_tag_list(expected_dict) self.assertEqual(ordered_tags, sorted_tags)
2,201
Python
37.631578
108
0.574739
omniverse-code/kit/exts/omni.kit.window.toolbar/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.4.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI description = "Extension to create a dockable toolbar. It also comes with builtin tools for transform manipulation and animation playing." title = "Toolbar Extension" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Internal" feature = true # Keywords for the extension keywords = ["kit", "toolbar"] # Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content # of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.context_menu" = {} "omni.kit.menu.utils" = {} "omni.kit.widget.toolbar" = {} "omni.ui" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.kit.window.toolbar" [[test]] args = [ "--/app/window/width=480", "--/app/window/height=480", "--/app/renderer/resolution/width=480", "--/app/renderer/resolution/height=480", "--/app/window/scaleToMonitor=false", "--no-window", ] dependencies = [ "omni.kit.uiapp", "omni.kit.renderer.capture", ] stdoutFailPatterns.exclude = [ "*Failed to acquire interface*while unloading all plugins*", ]
1,538
TOML
28.037735
138
0.721066
omniverse-code/kit/exts/omni.kit.window.toolbar/omni/kit/window/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.kit.app omni.kit.app.log_deprecation( '"import omni.kit.window.toolbar.simple_tool_button" is deprecated. ' 'Please use "import omni.kit.widget.toolbar.simple_tool_button"' ) try: # pragma: no cover import inspect for stackframe in inspect.stack(): if stackframe.code_context is None: continue code = stackframe.code_context[0] if code and code.startswith(("import", "from")): # name of importing file omni.kit.app.log_deprecation(f"Imported from {stackframe.filename}") break except: # pragma: no cover pass from omni.kit.widget.toolbar.simple_tool_button import * # backward compatible
1,125
Python
37.827585
80
0.719111
omniverse-code/kit/exts/omni.kit.window.toolbar/omni/kit/window/toolbar/__init__.py
from .toolbar import * from omni.kit.widget.toolbar.simple_tool_button import * # backward compatible
103
Python
33.666655
79
0.786408
omniverse-code/kit/exts/omni.kit.window.toolbar/omni/kit/window/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 omni.kit.app # pragma: no cover omni.kit.app.log_deprecation( '"import omni.kit.window.toolbar.context_menu" is deprecated. ' 'Please use "import omni.kit.widget.toolbar.context_menu"' ) # pragma: no cover from omni.kit.widget.toolbar.context_menu import * # backward compatible # pragma: no cover
744
Python
48.666663
92
0.778226
omniverse-code/kit/exts/omni.kit.window.toolbar/omni/kit/window/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 weakref from functools import lru_cache, partial from pathlib import Path import omni.kit.context_menu import omni.ext import omni.kit.app import omni.ui as ui from omni.kit.widget.toolbar.builtin_tools.builtin_tools import BuiltinTools # backward compatible from omni.kit.widget.toolbar.commands import * # backward compatible from omni.kit.widget.toolbar.context_menu import * from omni.kit.widget.toolbar.widget_group import WidgetGroup # backward compatible from omni.kit.widget.toolbar import get_instance as _get_widget_instance DATA_PATH = Path() _toolbar_instance = None @lru_cache() def get_data_path() -> Path: return DATA_PATH def get_instance(): return _toolbar_instance # 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(omni.ext.IExt): WINDOW_NAME = "Main ToolBar" MENU_PATH = "Window/ToolBar" def __init__(self): self._main_toolbar = None super().__init__() # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) global DATA_PATH DATA_PATH = Path(extension_path).joinpath("data") ui.Workspace.set_show_window_fn(Toolbar.WINDOW_NAME, partial(self._show_hide_window, None)) self._sub_grab_mouse_pressed = None self._show_hide_menu_entry = None self._widget_instance = _get_widget_instance() self._main_toolbar = None self._dock_task = None self.create_main_toolbar() try: import omni.kit.ui self._menu = omni.kit.ui.get_editor_menu().add_item( self.MENU_PATH, self._show_hide_window, toggle=True, value=self._main_toolbar.visible ) except ImportError: # pragma: no cover pass global _toolbar_instance _toolbar_instance = self def on_shutdown(self): global _toolbar_instance _toolbar_instance = None if self._dock_task is not None: # pragma: no cover self._dock_task.cancel() try: import omni.kit.ui omni.kit.ui.get_editor_menu().remove_item(self.MENU_PATH) except ImportError: # pragma: no cover pass self._show_hide_menu_entry = None self._widget_instance = None self._menu = None if self._main_toolbar: self._main_toolbar.destroy() self._main_toolbar = None self._sub_grab_mouse_pressed = None ui.Workspace.set_show_window_fn(Toolbar.WINDOW_NAME, None) @property def context_menu(self): return self._widget_instance.context_menu def create_main_toolbar(self): self._main_toolbar = ui.ToolBar(Toolbar.WINDOW_NAME, noTabBar=False, padding_x=3, padding_y=3, margin=5) self._main_toolbar.set_axis_changed_fn(self._on_axis_changed) self._rebuild_toolbar() self._register_context_menu() self._dock_task = asyncio.ensure_future(Toolbar._dock()) def add_widget(self, widget_group: "WidgetGroup", priority: int, context: str = ""): self._widget_instance.add_widget(widget_group, priority, context=context) def remove_widget(self, widget_group: "WidgetGroup"): self._widget_instance.remove_widget(widget_group) def get_widget(self, name: str): return self._widget_instance.get_widget(name) 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 """ return self._widget_instance.acquire_toolbar_context(context) 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. """ self._widget_instance.release_toolbar_context(token) def get_context(self): return self._widget_instance.get_context() def _on_axis_changed(self, axis): self._widget_instance.set_axis(axis) self._rebuild_toolbar() def _rebuild_toolbar(self): self._main_toolbar.frame.clear() self._widget_instance.rebuild_toolbar(root_frame=self._main_toolbar.frame) self._sub_grab_mouse_pressed = self._widget_instance.subscribe_grab_mouse_pressed( self.__on_grab_mouse_pressed ) # Toolbar context menu on the grab area def __on_grab_mouse_pressed(self, x, y, button, *args, **kwargs): if button == 1: # Right click, show immediately event = ContextMenuEvent() event.payload["widget_name"] = "grab" self.context_menu.on_mouse_event(event) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): return objects.get("widget_name", None) == button_name if context_menu: menu = { "name": "Hide", "show_fn": [lambda obj: is_button(obj, "grab")], "onclick_fn": self._menu_hide_toolbar, } self._show_hide_menu_entry = omni.kit.context_menu.add_menu(menu, "grab", "omni.kit.window.toolbar") def _show_hide_window(self, menu, value): # pragma: no cover self._main_toolbar.visible = value @staticmethod async def _dock(): frame = 3 while frame > 0: viewport = ui.Workspace.get_window("Viewport") if viewport: # pragma: no cover await omni.kit.app.get_app().next_update_async() break await omni.kit.app.get_app().next_update_async() frame -= 1 toolbar = ui.Workspace.get_window(Toolbar.WINDOW_NAME) if viewport and toolbar: # pragma: no cover toolbar.dock_in(viewport, ui.DockPosition.LEFT) _toolbar_instance._dock_task = None def _menu_hide_toolbar(self, objects): # pragma: no cover if self._main_toolbar is not None: self._main_toolbar.visible = False import omni.kit.ui omni.kit.ui.get_editor_menu().set_value("Window/ToolBar", False) def add_custom_select_type(self, entry_name: str, selection_types: list): self._widget_instance.add_custom_select_type(entry_name, selection_types) def remove_custom_select(self, entry_name): self._widget_instance.remove_custom_select(entry_name)
7,683
Python
34.086758
119
0.645451
omniverse-code/kit/exts/omni.kit.window.toolbar/omni/kit/window/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 omni.kit.app omni.kit.app.log_deprecation( '"import omni.kit.window.toolbar.builtin_tools.play_button_group" is deprecated. ' 'Please use "import omni.kit.widget.toolbar.builtin_tools.play_button_group"' ) from omni.kit.widget.toolbar.builtin_tools.play_button_group import * # backward compatible
742
Python
48.53333
92
0.792453
omniverse-code/kit/exts/omni.kit.window.toolbar/omni/kit/window/toolbar/tests/__init__.py
from .test_docking import *
28
Python
13.499993
27
0.75
omniverse-code/kit/exts/omni.kit.window.toolbar/omni/kit/window/toolbar/tests/test_docking.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.input import omni.appwindow import omni.kit.app import omni.kit.test import omni.kit.window.toolbar import omni.ui as ui import omni.kit.ui_test as ui_test from omni.ui.tests.test_base import OmniUiTest from omni.kit.ui_test import emulate_mouse_move, emulate_mouse_move_and_click, Vec2 from omni.kit.ui_test.input import emulate_mouse from carb.input import MouseEventType from omni.kit.widget.toolbar.tests.helpers import reset_toolbar_settings from omni.kit.widget.toolbar import WidgetGroup GOLDEN_IMAGE_DIR = omni.kit.window.toolbar.get_data_path().joinpath("test", "golden_img").absolute() class ToolbarDockingTest(OmniUiTest): async def setUp(self): await super().setUp() reset_toolbar_settings() self._main_dockspace = ui.Workspace.get_window("DockSpace") self._toolbar_handle = ui.Workspace.get_window(omni.kit.window.toolbar.Toolbar.WINDOW_NAME) self._toolbar_handle.undock() # Move mouse to origin await emulate_mouse_move(Vec2(0, 0)) await ui_test.human_delay(10) async def test_docking_vertical(self): """Test vertical docking behavior.""" self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.LEFT) await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=GOLDEN_IMAGE_DIR, golden_img_name="v_dock.png") async def test_docking_horizontal(self): """Test horizontal docking behavior.""" self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.TOP) await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=GOLDEN_IMAGE_DIR, golden_img_name="h_dock.png") async def test_docking_vertical_context_menu(self): """Test vertical docking behavior showing context menu.""" self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.LEFT) await ui_test.human_delay(10) await emulate_mouse_move_and_click(Vec2(35, 135), right_click=True) await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=GOLDEN_IMAGE_DIR, golden_img_name="v_dock_menu.png") async def test_docking_horizontal_context_menu(self): """Test horizontal docking behavior showing context menu.""" self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.TOP) await ui_test.human_delay(10) await emulate_mouse_move_and_click(Vec2(125, 35), right_click=True) await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=GOLDEN_IMAGE_DIR, golden_img_name="h_dock_menu.png") async def test_docking_vertical_grab_context_menu(self): """Test vertical docking behavior showing grabber context menu.""" self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.LEFT) await ui_test.human_delay(10) await emulate_mouse_move_and_click(Vec2(15, 35), right_click=True) await ui_test.human_delay(10) # sometimes the menu appears 1 pixel lower than expected await self.finalize_test(golden_img_dir=GOLDEN_IMAGE_DIR, golden_img_name="v_dock_grab_menu.png", threshold=0.07) async def test_adding_widget(self): class TestToolButtonGroup(WidgetGroup): """ Test of how to create two ToolButton in one WidgetGroup """ def __init__(self): super().__init__() def get_style(self): return {} def create(self, default_size): button1 = ui.ToolButton( name="test1", width=default_size, height=default_size, ) button2 = ui.ToolButton( name="test2", width=default_size, height=default_size, ) # return a dictionary of name -> widget if you want to expose it to other widget_group return {"test1": button1, "test2": button2} widget_group = TestToolButtonGroup() toolbar = omni.kit.window.toolbar.get_instance() context = toolbar.acquire_toolbar_context('test') toolbar.add_widget(widget_group, 100) await ui_test.human_delay() self.assertIsNotNone(toolbar.get_widget('test1')) toolbar.remove_widget(widget_group) toolbar.add_custom_select_type('test', ['test']) toolbar.remove_custom_select('test') self.assertEqual(toolbar.get_context(), 'test') toolbar.release_toolbar_context(context)
5,035
Python
37.151515
121
0.662761
omniverse-code/kit/exts/omni.kit.window.toolbar/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.kit.window.toolbar`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [1.4.0] - 2022-11-29 ### Changed - Move part of the code in `omni.kit.widget.toolbar` ## [1.3.3] - 2022-09-26 ### Changed - Updated to use `omni.kit.actions.core` and `omni.kit.hotkeys.core` for hotkeys. ## [1.3.2] - 2022-09-01 ### Changed - Context menu without compatibility mode. ## [1.3.1] - 2022-06-23 ### Changed - Change how hotkey `W` is skipped during possible camera manipulation. ## [1.3.0] - 2022-05-17 ### Changed - Changed Snap button to legacy button. New snap button will be registered by extension. ## [1.2.4] - 2022-04-19 ### Fixed - Slienced menu_changed error on create exit ## [1.2.3] - 2022-04-06 ### Fixed - Message "Failed to acquire interface while unloading all plugins" ## [1.2.1] - 2021-06-22 ### Added - Fixed height of increment settings window ## [1.2.0] - 2021-06-04 ### Added - Moved all built-in toolbutton's flyout menu to use omni.kit.context_menu, making it easier to add additional menu items to exiting button from external extension. ## [1.1.0] - 2021-04-16 ### Added - Added "Context" concept to toolbar that can be used to control the effective scope of tool buttons. ## [1.0.0] - 2021-03-04 ### Added - Started tracking changelog. Added tests.
1,368
Markdown
26.379999
164
0.695175
omniverse-code/kit/exts/omni.kit.window.toolbar/docs/index.rst
omni.kit.window.toolbar ########################### Omniverse Kit Toolbar extension .. toctree:: :maxdepth: 1 CHANGELOG
129
reStructuredText
11.999999
31
0.565891
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/__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. """ from ._Gf import *
470
Python
41.818178
78
0.795745
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/_Gf.pyi
import usdrt.Gf._Gf import typing __all__ = [ "CompDiv", "CompMult", "Cross", "DegreesToRadians", "Dot", "GetComplement", "GetLength", "GetNormalized", "GetProjection", "IsClose", "Lerp", "Lerpf", "Matrix3d", "Matrix3f", "Matrix4d", "Matrix4f", "Max", "Min", "Normalize", "Quatd", "Quatf", "Quath", "RadiansToDegrees", "Range1d", "Range1f", "Range2d", "Range2f", "Range3d", "Range3f", "Rect2i", "Slerp", "Vec2d", "Vec2f", "Vec2h", "Vec2i", "Vec3d", "Vec3f", "Vec3h", "Vec3i", "Vec4d", "Vec4f", "Vec4h", "Vec4i" ] class Matrix3d(): def GetArrayItem(self, arg0: int) -> float: ... def GetColumn(self, arg0: int) -> Vec3d: ... def GetDeterminant(self) -> float: ... def GetHandedness(self) -> int: ... def GetInverse(self) -> Matrix3d: ... def GetOrthonormalized(self) -> Matrix3d: ... def GetRow(self, arg0: int) -> Vec3d: ... def GetTranspose(self) -> Matrix3d: ... def IsLeftHanded(self) -> bool: ... def IsRightHanded(self) -> bool: ... def Orthonormalize(self) -> bool: ... def Set(self, arg0: float, arg1: float, arg2: float, arg3: float, arg4: float, arg5: float, arg6: float, arg7: float, arg8: float) -> Matrix3d: ... def SetArrayItem(self, arg0: int, arg1: float) -> None: ... def SetColumn(self, arg0: int, arg1: Vec3d) -> None: ... @typing.overload def SetDiagonal(self, arg0: Vec3d) -> Matrix3d: ... @typing.overload def SetDiagonal(self, arg0: float) -> Matrix3d: ... def SetIdentity(self) -> Matrix3d: ... def SetRow(self, arg0: int, arg1: Vec3d) -> None: ... def SetZero(self) -> Matrix3d: ... def __add__(self, arg0: Matrix3d) -> Matrix3d: ... def __contains__(self, arg0: float) -> bool: ... def __copy__(self) -> Matrix3d: ... def __deepcopy__(self, memo: dict) -> Matrix3d: ... @staticmethod @typing.overload def __eq__(*args, **kwargs) -> typing.Any: ... @typing.overload def __eq__(self, arg0: Matrix3d) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> Vec3d: ... @typing.overload def __getitem__(self, arg0: tuple) -> float: ... def __iadd__(self, arg0: Matrix3d) -> Matrix3d: ... def __imul__(self, arg0: float) -> Matrix3d: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Matrix3d) -> None: ... @typing.overload def __init__(self, arg0: Vec3d) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float, arg4: float, arg5: float, arg6: float, arg7: float, arg8: float) -> None: ... def __isub__(self, arg0: Matrix3d) -> Matrix3d: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Matrix3d) -> Matrix3d: ... @typing.overload def __mul__(self, arg0: Vec3d) -> Vec3d: ... @typing.overload def __mul__(self, arg0: Vec3f) -> Vec3f: ... @typing.overload def __mul__(self, arg0: float) -> Matrix3d: ... @staticmethod @typing.overload def __ne__(*args, **kwargs) -> typing.Any: ... @typing.overload def __ne__(self, arg0: Matrix3d) -> bool: ... def __neg__(self) -> Matrix3d: ... def __repr__(self) -> str: ... @typing.overload def __rmul__(self, arg0: Vec3d) -> Vec3d: ... @typing.overload def __rmul__(self, arg0: Vec3f) -> Vec3f: ... @typing.overload def __rmul__(self, arg0: float) -> Matrix3d: ... @typing.overload def __setitem__(self, arg0: int, arg1: Vec3d) -> None: ... @typing.overload def __setitem__(self, arg0: tuple, arg1: float) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Matrix3d) -> Matrix3d: ... def __truediv__(self, arg0: Matrix3d) -> Matrix3d: ... __hash__ = None dimension = (3, 3) pass class Matrix3f(): def GetArrayItem(self, arg0: int) -> float: ... def GetColumn(self, arg0: int) -> Vec3f: ... def GetDeterminant(self) -> float: ... def GetHandedness(self) -> int: ... def GetInverse(self) -> Matrix3f: ... def GetOrthonormalized(self) -> Matrix3f: ... def GetRow(self, arg0: int) -> Vec3f: ... def GetTranspose(self) -> Matrix3f: ... def IsLeftHanded(self) -> bool: ... def IsRightHanded(self) -> bool: ... def Orthonormalize(self) -> bool: ... def Set(self, arg0: float, arg1: float, arg2: float, arg3: float, arg4: float, arg5: float, arg6: float, arg7: float, arg8: float) -> Matrix3f: ... def SetArrayItem(self, arg0: int, arg1: float) -> None: ... def SetColumn(self, arg0: int, arg1: Vec3f) -> None: ... @typing.overload def SetDiagonal(self, arg0: Vec3f) -> Matrix3f: ... @typing.overload def SetDiagonal(self, arg0: float) -> Matrix3f: ... def SetIdentity(self) -> Matrix3f: ... def SetRow(self, arg0: int, arg1: Vec3f) -> None: ... def SetZero(self) -> Matrix3f: ... def __add__(self, arg0: Matrix3f) -> Matrix3f: ... def __contains__(self, arg0: float) -> bool: ... def __copy__(self) -> Matrix3f: ... def __deepcopy__(self, memo: dict) -> Matrix3f: ... @typing.overload def __eq__(self, arg0: Matrix3d) -> bool: ... @typing.overload def __eq__(self, arg0: Matrix3f) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> Vec3f: ... @typing.overload def __getitem__(self, arg0: tuple) -> float: ... def __iadd__(self, arg0: Matrix3f) -> Matrix3f: ... def __imul__(self, arg0: float) -> Matrix3f: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Matrix3d) -> None: ... @typing.overload def __init__(self, arg0: Matrix3f) -> None: ... @typing.overload def __init__(self, arg0: Vec3f) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float, arg4: float, arg5: float, arg6: float, arg7: float, arg8: float) -> None: ... def __isub__(self, arg0: Matrix3f) -> Matrix3f: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Matrix3f) -> Matrix3f: ... @typing.overload def __mul__(self, arg0: Vec3f) -> Vec3f: ... @typing.overload def __mul__(self, arg0: float) -> Matrix3f: ... @typing.overload def __ne__(self, arg0: Matrix3d) -> bool: ... @typing.overload def __ne__(self, arg0: Matrix3f) -> bool: ... def __neg__(self) -> Matrix3f: ... def __repr__(self) -> str: ... @typing.overload def __rmul__(self, arg0: Vec3f) -> Vec3f: ... @typing.overload def __rmul__(self, arg0: float) -> Matrix3f: ... @typing.overload def __setitem__(self, arg0: int, arg1: Vec3f) -> None: ... @typing.overload def __setitem__(self, arg0: tuple, arg1: float) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Matrix3f) -> Matrix3f: ... def __truediv__(self, arg0: Matrix3f) -> Matrix3f: ... __hash__ = None dimension = (3, 3) pass class Matrix4d(): @staticmethod def ExtractRotation(*args, **kwargs) -> typing.Any: ... @staticmethod def ExtractRotationMatrix(*args, **kwargs) -> typing.Any: ... def ExtractTranslation(self) -> Vec3d: ... def GetArrayItem(self, arg0: int) -> float: ... def GetColumn(self, arg0: int) -> Vec4d: ... def GetDeterminant(self) -> float: ... def GetDeterminant3(self) -> float: ... def GetHandedness(self) -> int: ... def GetInverse(self) -> Matrix4d: ... def GetOrthonormalized(self) -> Matrix4d: ... def GetRow(self, arg0: int) -> Vec4d: ... def GetRow3(self, arg0: int) -> Vec3d: ... def GetTranspose(self) -> Matrix4d: ... def IsLeftHanded(self) -> bool: ... def IsRightHanded(self) -> bool: ... def Orthonormalize(self) -> bool: ... def RemoveScaleShear(self) -> Matrix4d: ... def Set(self, arg0: float, arg1: float, arg2: float, arg3: float, arg4: float, arg5: float, arg6: float, arg7: float, arg8: float, arg9: float, arg10: float, arg11: float, arg12: float, arg13: float, arg14: float, arg15: float) -> Matrix4d: ... def SetArrayItem(self, arg0: int, arg1: float) -> None: ... def SetColumn(self, arg0: int, arg1: Vec4d) -> None: ... @typing.overload def SetDiagonal(self, arg0: Vec4d) -> Matrix4d: ... @typing.overload def SetDiagonal(self, arg0: float) -> Matrix4d: ... def SetIdentity(self) -> Matrix4d: ... def SetLookAt(self, arg0: Vec3d, arg1: Vec3d, arg2: Vec3d) -> Matrix4d: ... @staticmethod def SetRotate(*args, **kwargs) -> typing.Any: ... @staticmethod def SetRotateOnly(*args, **kwargs) -> typing.Any: ... def SetRow(self, arg0: int, arg1: Vec4d) -> None: ... def SetRow3(self, arg0: int, arg1: Vec3d) -> None: ... @typing.overload def SetScale(self, arg0: Vec3d) -> Matrix4d: ... @typing.overload def SetScale(self, arg0: float) -> Matrix4d: ... def SetTranslate(self, arg0: Vec3d) -> Matrix4d: ... def SetTranslateOnly(self, arg0: Vec3d) -> Matrix4d: ... def SetZero(self) -> Matrix4d: ... @typing.overload def Transform(self, arg0: Vec3d) -> Vec3d: ... @typing.overload def Transform(self, arg0: Vec3f) -> Vec3f: ... @typing.overload def TransformAffine(self, arg0: Vec3d) -> Vec3d: ... @typing.overload def TransformAffine(self, arg0: Vec3f) -> Vec3f: ... @typing.overload def TransformDir(self, arg0: Vec3d) -> Vec3d: ... @typing.overload def TransformDir(self, arg0: Vec3f) -> Vec3f: ... def __add__(self, arg0: Matrix4d) -> Matrix4d: ... def __contains__(self, arg0: float) -> bool: ... def __copy__(self) -> Matrix4d: ... def __deepcopy__(self, memo: dict) -> Matrix4d: ... @staticmethod @typing.overload def __eq__(*args, **kwargs) -> typing.Any: ... @typing.overload def __eq__(self, arg0: Matrix4d) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> Vec4d: ... @typing.overload def __getitem__(self, arg0: tuple) -> float: ... def __iadd__(self, arg0: Matrix4d) -> Matrix4d: ... def __imul__(self, arg0: float) -> Matrix4d: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Matrix4d) -> None: ... @typing.overload def __init__(self, arg0: Vec4d) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float, arg4: float, arg5: float, arg6: float, arg7: float, arg8: float, arg9: float, arg10: float, arg11: float, arg12: float, arg13: float, arg14: float, arg15: float) -> None: ... def __isub__(self, arg0: Matrix4d) -> Matrix4d: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Matrix4d) -> Matrix4d: ... @typing.overload def __mul__(self, arg0: Vec4d) -> Vec4d: ... @typing.overload def __mul__(self, arg0: Vec4f) -> Vec4f: ... @typing.overload def __mul__(self, arg0: float) -> Matrix4d: ... @staticmethod @typing.overload def __ne__(*args, **kwargs) -> typing.Any: ... @typing.overload def __ne__(self, arg0: Matrix4d) -> bool: ... def __neg__(self) -> Matrix4d: ... def __repr__(self) -> str: ... @typing.overload def __rmul__(self, arg0: Vec4d) -> Vec4d: ... @typing.overload def __rmul__(self, arg0: Vec4f) -> Vec4f: ... @typing.overload def __rmul__(self, arg0: float) -> Matrix4d: ... @typing.overload def __setitem__(self, arg0: int, arg1: Vec4d) -> None: ... @typing.overload def __setitem__(self, arg0: tuple, arg1: float) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Matrix4d) -> Matrix4d: ... def __truediv__(self, arg0: Matrix4d) -> Matrix4d: ... __hash__ = None dimension = (4, 4) pass class Matrix4f(): @staticmethod def ExtractRotation(*args, **kwargs) -> typing.Any: ... @staticmethod def ExtractRotationMatrix(*args, **kwargs) -> typing.Any: ... def ExtractTranslation(self) -> Vec3f: ... def GetArrayItem(self, arg0: int) -> float: ... def GetColumn(self, arg0: int) -> Vec4f: ... def GetDeterminant(self) -> float: ... def GetDeterminant3(self) -> float: ... def GetHandedness(self) -> int: ... def GetInverse(self) -> Matrix4f: ... def GetOrthonormalized(self) -> Matrix4f: ... def GetRow(self, arg0: int) -> Vec4f: ... def GetRow3(self, arg0: int) -> Vec3f: ... def GetTranspose(self) -> Matrix4f: ... def IsLeftHanded(self) -> bool: ... def IsRightHanded(self) -> bool: ... def Orthonormalize(self) -> bool: ... def RemoveScaleShear(self) -> Matrix4f: ... def Set(self, arg0: float, arg1: float, arg2: float, arg3: float, arg4: float, arg5: float, arg6: float, arg7: float, arg8: float, arg9: float, arg10: float, arg11: float, arg12: float, arg13: float, arg14: float, arg15: float) -> Matrix4f: ... def SetArrayItem(self, arg0: int, arg1: float) -> None: ... def SetColumn(self, arg0: int, arg1: Vec4f) -> None: ... @typing.overload def SetDiagonal(self, arg0: Vec4f) -> Matrix4f: ... @typing.overload def SetDiagonal(self, arg0: float) -> Matrix4f: ... def SetIdentity(self) -> Matrix4f: ... def SetLookAt(self, arg0: Vec3f, arg1: Vec3f, arg2: Vec3f) -> Matrix4f: ... @staticmethod def SetRotate(*args, **kwargs) -> typing.Any: ... @staticmethod def SetRotateOnly(*args, **kwargs) -> typing.Any: ... def SetRow(self, arg0: int, arg1: Vec4f) -> None: ... def SetRow3(self, arg0: int, arg1: Vec3f) -> None: ... @typing.overload def SetScale(self, arg0: Vec3f) -> Matrix4f: ... @typing.overload def SetScale(self, arg0: float) -> Matrix4f: ... def SetTranslate(self, arg0: Vec3f) -> Matrix4f: ... def SetTranslateOnly(self, arg0: Vec3f) -> Matrix4f: ... def SetZero(self) -> Matrix4f: ... @typing.overload def Transform(self, arg0: Vec3d) -> Vec3d: ... @typing.overload def Transform(self, arg0: Vec3f) -> Vec3f: ... @typing.overload def TransformAffine(self, arg0: Vec3d) -> Vec3d: ... @typing.overload def TransformAffine(self, arg0: Vec3f) -> Vec3f: ... @typing.overload def TransformDir(self, arg0: Vec3d) -> Vec3d: ... @typing.overload def TransformDir(self, arg0: Vec3f) -> Vec3f: ... def __add__(self, arg0: Matrix4f) -> Matrix4f: ... def __contains__(self, arg0: float) -> bool: ... def __copy__(self) -> Matrix4f: ... def __deepcopy__(self, memo: dict) -> Matrix4f: ... @typing.overload def __eq__(self, arg0: Matrix4d) -> bool: ... @typing.overload def __eq__(self, arg0: Matrix4f) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> Vec4f: ... @typing.overload def __getitem__(self, arg0: tuple) -> float: ... def __iadd__(self, arg0: Matrix4f) -> Matrix4f: ... def __imul__(self, arg0: float) -> Matrix4f: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Matrix4d) -> None: ... @typing.overload def __init__(self, arg0: Matrix4f) -> None: ... @typing.overload def __init__(self, arg0: Vec4f) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float, arg4: float, arg5: float, arg6: float, arg7: float, arg8: float, arg9: float, arg10: float, arg11: float, arg12: float, arg13: float, arg14: float, arg15: float) -> None: ... def __isub__(self, arg0: Matrix4f) -> Matrix4f: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Matrix4f) -> Matrix4f: ... @typing.overload def __mul__(self, arg0: Vec4f) -> Vec4f: ... @typing.overload def __mul__(self, arg0: float) -> Matrix4f: ... @typing.overload def __ne__(self, arg0: Matrix4d) -> bool: ... @typing.overload def __ne__(self, arg0: Matrix4f) -> bool: ... def __neg__(self) -> Matrix4f: ... def __repr__(self) -> str: ... @typing.overload def __rmul__(self, arg0: Vec4f) -> Vec4f: ... @typing.overload def __rmul__(self, arg0: float) -> Matrix4f: ... @typing.overload def __setitem__(self, arg0: int, arg1: Vec4f) -> None: ... @typing.overload def __setitem__(self, arg0: tuple, arg1: float) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Matrix4f) -> Matrix4f: ... def __truediv__(self, arg0: Matrix4f) -> Matrix4f: ... __hash__ = None dimension = (4, 4) pass class Quatd(): def Dot(self, arg0: Quatd) -> float: ... def GetConjugate(self) -> Quatd: ... @staticmethod def GetIdentity() -> Quatd: ... def GetImaginary(self) -> Vec3d: ... def GetInverse(self) -> Quatd: ... def GetLength(self) -> float: ... def GetLengthSq(self) -> float: ... def GetNormalized(self) -> Quatd: ... def GetReal(self) -> float: ... def Normalize(self) -> float: ... @typing.overload def SetImaginary(self, i: float, j: float, k: float) -> None: ... @typing.overload def SetImaginary(self, imaginary: Vec3d) -> None: ... def SetReal(self, real: float) -> None: ... def Transform(self, point: Vec3d) -> Vec3d: ... def __add__(self, arg0: Quatd) -> Quatd: ... def __copy__(self) -> Quatd: ... def __deepcopy__(self, memo: dict) -> Quatd: ... def __eq__(self, arg0: Quatd) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> float: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[float]: ... def __iadd__(self, arg0: Quatd) -> Quatd: ... @typing.overload def __imul__(self, arg0: Quatd) -> Quatd: ... @typing.overload def __imul__(self, arg0: float) -> Quatd: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Quatd) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: Vec3d) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: typing.Tuple[float, float, float]) -> None: ... def __isub__(self, arg0: Quatd) -> Quatd: ... def __itruediv__(self, arg0: float) -> Quatd: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Quatd) -> Quatd: ... @typing.overload def __mul__(self, arg0: float) -> Quatd: ... def __ne__(self, arg0: Quatd) -> bool: ... def __neg__(self) -> Quatd: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Quatd: ... @typing.overload def __setitem__(self, arg0: int, arg1: float) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Quatd) -> Quatd: ... def __truediv__(self, arg0: float) -> Quatd: ... @property def imaginary(self) -> Vec3d: """ :type: Vec3d """ @imaginary.setter def imaginary(self, arg1: Vec3d) -> None: pass @property def real(self) -> float: """ :type: float """ @real.setter def real(self, arg1: float) -> None: pass __hash__ = None pass class Quatf(): def Dot(self, arg0: Quatf) -> float: ... def GetConjugate(self) -> Quatf: ... @staticmethod def GetIdentity() -> Quatf: ... def GetImaginary(self) -> Vec3f: ... def GetInverse(self) -> Quatf: ... def GetLength(self) -> float: ... def GetLengthSq(self) -> float: ... def GetNormalized(self) -> Quatf: ... def GetReal(self) -> float: ... def Normalize(self) -> float: ... @typing.overload def SetImaginary(self, i: float, j: float, k: float) -> None: ... @typing.overload def SetImaginary(self, imaginary: Vec3f) -> None: ... def SetReal(self, real: float) -> None: ... def Transform(self, point: Vec3f) -> Vec3f: ... def __add__(self, arg0: Quatf) -> Quatf: ... def __copy__(self) -> Quatf: ... def __deepcopy__(self, memo: dict) -> Quatf: ... def __eq__(self, arg0: Quatf) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> float: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[float]: ... def __iadd__(self, arg0: Quatf) -> Quatf: ... @typing.overload def __imul__(self, arg0: Quatf) -> Quatf: ... @typing.overload def __imul__(self, arg0: float) -> Quatf: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Quatd) -> None: ... @typing.overload def __init__(self, arg0: Quatf) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: Vec3f) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: typing.Tuple[float, float, float]) -> None: ... def __isub__(self, arg0: Quatf) -> Quatf: ... def __itruediv__(self, arg0: float) -> Quatf: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Quatf) -> Quatf: ... @typing.overload def __mul__(self, arg0: float) -> Quatf: ... def __ne__(self, arg0: Quatf) -> bool: ... def __neg__(self) -> Quatf: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Quatf: ... @typing.overload def __setitem__(self, arg0: int, arg1: float) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Quatf) -> Quatf: ... def __truediv__(self, arg0: float) -> Quatf: ... @property def imaginary(self) -> Vec3f: """ :type: Vec3f """ @imaginary.setter def imaginary(self, arg1: Vec3f) -> None: pass @property def real(self) -> float: """ :type: float """ @real.setter def real(self, arg1: float) -> None: pass __hash__ = None pass class Quath(): def Dot(self, arg0: Quath) -> GfHalf: ... def GetConjugate(self) -> Quath: ... @staticmethod def GetIdentity() -> Quath: ... def GetImaginary(self) -> Vec3h: ... def GetInverse(self) -> Quath: ... def GetLength(self) -> float: ... def GetLengthSq(self) -> GfHalf: ... def GetNormalized(self) -> Quath: ... def GetReal(self) -> GfHalf: ... def Normalize(self) -> float: ... @typing.overload def SetImaginary(self, i: GfHalf, j: GfHalf, k: GfHalf) -> None: ... @typing.overload def SetImaginary(self, imaginary: Vec3h) -> None: ... def SetReal(self, real: GfHalf) -> None: ... def Transform(self, point: Vec3h) -> Vec3h: ... def __add__(self, arg0: Quath) -> Quath: ... def __copy__(self) -> Quath: ... def __deepcopy__(self, memo: dict) -> Quath: ... def __eq__(self, arg0: Quath) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> GfHalf: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[GfHalf]: ... def __iadd__(self, arg0: Quath) -> Quath: ... @typing.overload def __imul__(self, arg0: GfHalf) -> Quath: ... @typing.overload def __imul__(self, arg0: Quath) -> Quath: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: GfHalf) -> None: ... @typing.overload def __init__(self, arg0: GfHalf, arg1: GfHalf, arg2: GfHalf, arg3: GfHalf) -> None: ... @typing.overload def __init__(self, arg0: GfHalf, arg1: Vec3h) -> None: ... @typing.overload def __init__(self, arg0: GfHalf, arg1: typing.Tuple[GfHalf, GfHalf, GfHalf]) -> None: ... @typing.overload def __init__(self, arg0: Quatd) -> None: ... @typing.overload def __init__(self, arg0: Quatf) -> None: ... @typing.overload def __init__(self, arg0: Quath) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... def __isub__(self, arg0: Quath) -> Quath: ... def __itruediv__(self, arg0: GfHalf) -> Quath: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: GfHalf) -> Quath: ... @typing.overload def __mul__(self, arg0: Quath) -> Quath: ... def __ne__(self, arg0: Quath) -> bool: ... def __neg__(self) -> Quath: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: GfHalf) -> Quath: ... @typing.overload def __setitem__(self, arg0: int, arg1: GfHalf) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Quath) -> Quath: ... def __truediv__(self, arg0: GfHalf) -> Quath: ... @property def imaginary(self) -> Vec3h: """ :type: Vec3h """ @imaginary.setter def imaginary(self, arg1: Vec3h) -> None: pass @property def real(self) -> GfHalf: """ :type: GfHalf """ @real.setter def real(self, arg1: GfHalf) -> None: pass __hash__ = None pass class Range1d(): @typing.overload def Contains(self, arg0: Range1d) -> bool: ... @typing.overload def Contains(self, arg0: float) -> bool: ... def GetDistanceSquared(self, arg0: float) -> float: ... @staticmethod def GetIntersection(arg0: Range1d, arg1: Range1d) -> Range1d: ... def GetMax(self) -> float: ... def GetMidpoint(self) -> float: ... def GetMin(self) -> float: ... def GetSize(self) -> float: ... @staticmethod def GetUnion(arg0: Range1d, arg1: Range1d) -> Range1d: ... def IntersectWith(self, arg0: Range1d) -> Range1d: ... def IsEmpty(self) -> bool: ... def SetEmpty(self) -> None: ... def SetMax(self, arg0: float) -> None: ... def SetMin(self, arg0: float) -> None: ... @typing.overload def UnionWith(self, arg0: Range1d) -> Range1d: ... @typing.overload def UnionWith(self, arg0: float) -> Range1d: ... def __add__(self, arg0: Range1d) -> Range1d: ... def __copy__(self) -> Range1d: ... def __deepcopy__(self, memo: dict) -> Range1d: ... def __eq__(self, arg0: Range1d) -> bool: ... def __iadd__(self, arg0: Range1d) -> Range1d: ... def __imul__(self, arg0: float) -> Range1d: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Range1d) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float) -> None: ... def __isub__(self, arg0: Range1d) -> Range1d: ... def __itruediv__(self, arg0: float) -> Range1d: ... def __mul__(self, arg0: float) -> Range1d: ... def __ne__(self, arg0: Range1d) -> bool: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Range1d: ... def __str__(self) -> str: ... def __sub__(self, arg0: Range1d) -> Range1d: ... def __truediv__(self, arg0: float) -> Range1d: ... @property def max(self) -> float: """ :type: float """ @max.setter def max(self, arg1: float) -> None: pass @property def min(self) -> float: """ :type: float """ @min.setter def min(self, arg1: float) -> None: pass __hash__ = None pass class Range1f(): @typing.overload def Contains(self, arg0: Range1f) -> bool: ... @typing.overload def Contains(self, arg0: float) -> bool: ... def GetDistanceSquared(self, arg0: float) -> float: ... @staticmethod def GetIntersection(arg0: Range1f, arg1: Range1f) -> Range1f: ... def GetMax(self) -> float: ... def GetMidpoint(self) -> float: ... def GetMin(self) -> float: ... def GetSize(self) -> float: ... @staticmethod def GetUnion(arg0: Range1f, arg1: Range1f) -> Range1f: ... def IntersectWith(self, arg0: Range1f) -> Range1f: ... def IsEmpty(self) -> bool: ... def SetEmpty(self) -> None: ... def SetMax(self, arg0: float) -> None: ... def SetMin(self, arg0: float) -> None: ... @typing.overload def UnionWith(self, arg0: Range1f) -> Range1f: ... @typing.overload def UnionWith(self, arg0: float) -> Range1f: ... def __add__(self, arg0: Range1f) -> Range1f: ... def __copy__(self) -> Range1f: ... def __deepcopy__(self, memo: dict) -> Range1f: ... def __eq__(self, arg0: Range1f) -> bool: ... def __iadd__(self, arg0: Range1f) -> Range1f: ... def __imul__(self, arg0: float) -> Range1f: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Range1f) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float) -> None: ... def __isub__(self, arg0: Range1f) -> Range1f: ... def __itruediv__(self, arg0: float) -> Range1f: ... def __mul__(self, arg0: float) -> Range1f: ... def __ne__(self, arg0: Range1f) -> bool: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Range1f: ... def __str__(self) -> str: ... def __sub__(self, arg0: Range1f) -> Range1f: ... def __truediv__(self, arg0: float) -> Range1f: ... @property def max(self) -> float: """ :type: float """ @max.setter def max(self, arg1: float) -> None: pass @property def min(self) -> float: """ :type: float """ @min.setter def min(self, arg1: float) -> None: pass __hash__ = None pass class Range2d(): @typing.overload def Contains(self, arg0: Range2d) -> bool: ... @typing.overload def Contains(self, arg0: Vec2d) -> bool: ... def GetCorner(self, arg0: int) -> Vec2d: ... def GetDistanceSquared(self, arg0: Vec2d) -> float: ... @staticmethod def GetIntersection(arg0: Range2d, arg1: Range2d) -> Range2d: ... def GetMax(self) -> Vec2d: ... def GetMidpoint(self) -> Vec2d: ... def GetMin(self) -> Vec2d: ... def GetQuadrant(self, arg0: int) -> Range2d: ... def GetSize(self) -> Vec2d: ... @staticmethod def GetUnion(arg0: Range2d, arg1: Range2d) -> Range2d: ... def IntersectWith(self, arg0: Range2d) -> Range2d: ... def IsEmpty(self) -> bool: ... def SetEmpty(self) -> None: ... def SetMax(self, arg0: Vec2d) -> None: ... def SetMin(self, arg0: Vec2d) -> None: ... @typing.overload def UnionWith(self, arg0: Range2d) -> Range2d: ... @typing.overload def UnionWith(self, arg0: Vec2d) -> Range2d: ... def __add__(self, arg0: Range2d) -> Range2d: ... def __copy__(self) -> Range2d: ... def __deepcopy__(self, memo: dict) -> Range2d: ... def __eq__(self, arg0: Range2d) -> bool: ... def __iadd__(self, arg0: Range2d) -> Range2d: ... def __imul__(self, arg0: float) -> Range2d: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Range2d) -> None: ... @typing.overload def __init__(self, arg0: Vec2d, arg1: Vec2d) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... def __isub__(self, arg0: Range2d) -> Range2d: ... def __itruediv__(self, arg0: float) -> Range2d: ... def __mul__(self, arg0: float) -> Range2d: ... def __ne__(self, arg0: Range2d) -> bool: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Range2d: ... def __str__(self) -> str: ... def __sub__(self, arg0: Range2d) -> Range2d: ... def __truediv__(self, arg0: float) -> Range2d: ... @staticmethod def unitSquare() -> Range2d: ... @property def max(self) -> Vec2d: """ :type: Vec2d """ @max.setter def max(self, arg1: Vec2d) -> None: pass @property def min(self) -> Vec2d: """ :type: Vec2d """ @min.setter def min(self, arg1: Vec2d) -> None: pass __hash__ = None pass class Range2f(): @typing.overload def Contains(self, arg0: Range2f) -> bool: ... @typing.overload def Contains(self, arg0: Vec2f) -> bool: ... def GetCorner(self, arg0: int) -> Vec2f: ... def GetDistanceSquared(self, arg0: Vec2f) -> float: ... @staticmethod def GetIntersection(arg0: Range2f, arg1: Range2f) -> Range2f: ... def GetMax(self) -> Vec2f: ... def GetMidpoint(self) -> Vec2f: ... def GetMin(self) -> Vec2f: ... def GetQuadrant(self, arg0: int) -> Range2f: ... def GetSize(self) -> Vec2f: ... @staticmethod def GetUnion(arg0: Range2f, arg1: Range2f) -> Range2f: ... def IntersectWith(self, arg0: Range2f) -> Range2f: ... def IsEmpty(self) -> bool: ... def SetEmpty(self) -> None: ... def SetMax(self, arg0: Vec2f) -> None: ... def SetMin(self, arg0: Vec2f) -> None: ... @typing.overload def UnionWith(self, arg0: Range2f) -> Range2f: ... @typing.overload def UnionWith(self, arg0: Vec2f) -> Range2f: ... def __add__(self, arg0: Range2f) -> Range2f: ... def __copy__(self) -> Range2f: ... def __deepcopy__(self, memo: dict) -> Range2f: ... def __eq__(self, arg0: Range2f) -> bool: ... def __iadd__(self, arg0: Range2f) -> Range2f: ... def __imul__(self, arg0: float) -> Range2f: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Range2f) -> None: ... @typing.overload def __init__(self, arg0: Vec2f, arg1: Vec2f) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... def __isub__(self, arg0: Range2f) -> Range2f: ... def __itruediv__(self, arg0: float) -> Range2f: ... def __mul__(self, arg0: float) -> Range2f: ... def __ne__(self, arg0: Range2f) -> bool: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Range2f: ... def __str__(self) -> str: ... def __sub__(self, arg0: Range2f) -> Range2f: ... def __truediv__(self, arg0: float) -> Range2f: ... @staticmethod def unitSquare() -> Range2f: ... @property def max(self) -> Vec2f: """ :type: Vec2f """ @max.setter def max(self, arg1: Vec2f) -> None: pass @property def min(self) -> Vec2f: """ :type: Vec2f """ @min.setter def min(self, arg1: Vec2f) -> None: pass __hash__ = None pass class Range3d(): @typing.overload def Contains(self, arg0: Range3d) -> bool: ... @typing.overload def Contains(self, arg0: Vec3d) -> bool: ... def GetCorner(self, arg0: int) -> Vec3d: ... def GetDistanceSquared(self, arg0: Vec3d) -> float: ... @staticmethod def GetIntersection(arg0: Range3d, arg1: Range3d) -> Range3d: ... def GetMax(self) -> Vec3d: ... def GetMidpoint(self) -> Vec3d: ... def GetMin(self) -> Vec3d: ... def GetOctant(self, arg0: int) -> Range3d: ... def GetSize(self) -> Vec3d: ... @staticmethod def GetUnion(arg0: Range3d, arg1: Range3d) -> Range3d: ... def IntersectWith(self, arg0: Range3d) -> Range3d: ... def IsEmpty(self) -> bool: ... def SetEmpty(self) -> None: ... def SetMax(self, arg0: Vec3d) -> None: ... def SetMin(self, arg0: Vec3d) -> None: ... @typing.overload def UnionWith(self, arg0: Range3d) -> Range3d: ... @typing.overload def UnionWith(self, arg0: Vec3d) -> Range3d: ... def __add__(self, arg0: Range3d) -> Range3d: ... def __copy__(self) -> Range3d: ... def __deepcopy__(self, memo: dict) -> Range3d: ... def __eq__(self, arg0: Range3d) -> bool: ... def __iadd__(self, arg0: Range3d) -> Range3d: ... def __imul__(self, arg0: float) -> Range3d: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Range3d) -> None: ... @typing.overload def __init__(self, arg0: Vec3d, arg1: Vec3d) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... def __isub__(self, arg0: Range3d) -> Range3d: ... def __itruediv__(self, arg0: float) -> Range3d: ... def __mul__(self, arg0: float) -> Range3d: ... def __ne__(self, arg0: Range3d) -> bool: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Range3d: ... def __str__(self) -> str: ... def __sub__(self, arg0: Range3d) -> Range3d: ... def __truediv__(self, arg0: float) -> Range3d: ... @staticmethod def unitCube() -> Range3d: ... @property def max(self) -> Vec3d: """ :type: Vec3d """ @max.setter def max(self, arg1: Vec3d) -> None: pass @property def min(self) -> Vec3d: """ :type: Vec3d """ @min.setter def min(self, arg1: Vec3d) -> None: pass __hash__ = None pass class Range3f(): @typing.overload def Contains(self, arg0: Range3f) -> bool: ... @typing.overload def Contains(self, arg0: Vec3f) -> bool: ... def GetCorner(self, arg0: int) -> Vec3f: ... def GetDistanceSquared(self, arg0: Vec3f) -> float: ... @staticmethod def GetIntersection(arg0: Range3f, arg1: Range3f) -> Range3f: ... def GetMax(self) -> Vec3f: ... def GetMidpoint(self) -> Vec3f: ... def GetMin(self) -> Vec3f: ... def GetOctant(self, arg0: int) -> Range3f: ... def GetSize(self) -> Vec3f: ... @staticmethod def GetUnion(arg0: Range3f, arg1: Range3f) -> Range3f: ... def IntersectWith(self, arg0: Range3f) -> Range3f: ... def IsEmpty(self) -> bool: ... def SetEmpty(self) -> None: ... def SetMax(self, arg0: Vec3f) -> None: ... def SetMin(self, arg0: Vec3f) -> None: ... @typing.overload def UnionWith(self, arg0: Range3f) -> Range3f: ... @typing.overload def UnionWith(self, arg0: Vec3f) -> Range3f: ... def __add__(self, arg0: Range3f) -> Range3f: ... def __copy__(self) -> Range3f: ... def __deepcopy__(self, memo: dict) -> Range3f: ... def __eq__(self, arg0: Range3f) -> bool: ... def __iadd__(self, arg0: Range3f) -> Range3f: ... def __imul__(self, arg0: float) -> Range3f: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Range3f) -> None: ... @typing.overload def __init__(self, arg0: Vec3f, arg1: Vec3f) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... def __isub__(self, arg0: Range3f) -> Range3f: ... def __itruediv__(self, arg0: float) -> Range3f: ... def __mul__(self, arg0: float) -> Range3f: ... def __ne__(self, arg0: Range3f) -> bool: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Range3f: ... def __str__(self) -> str: ... def __sub__(self, arg0: Range3f) -> Range3f: ... def __truediv__(self, arg0: float) -> Range3f: ... @staticmethod def unitCube() -> Range3f: ... @property def max(self) -> Vec3f: """ :type: Vec3f """ @max.setter def max(self, arg1: Vec3f) -> None: pass @property def min(self) -> Vec3f: """ :type: Vec3f """ @min.setter def min(self, arg1: Vec3f) -> None: pass __hash__ = None pass class Rect2i(): def Contains(self, arg0: Vec2i) -> bool: ... def GetArea(self) -> int: ... def GetCenter(self) -> Vec2i: ... def GetHeight(self) -> int: ... def GetIntersection(self, arg0: Rect2i) -> Rect2i: ... def GetMax(self) -> Vec2i: ... def GetMaxX(self) -> int: ... def GetMaxY(self) -> int: ... def GetMin(self) -> Vec2i: ... def GetMinX(self) -> int: ... def GetMinY(self) -> int: ... def GetNormalized(self) -> Rect2i: ... def GetSize(self) -> Vec2i: ... def GetUnion(self, arg0: Rect2i) -> Rect2i: ... def GetWidth(self) -> int: ... def Intersect(self, arg0: Rect2i) -> Rect2i: ... def IsEmpty(self) -> bool: ... def IsNull(self) -> bool: ... def IsValid(self) -> bool: ... def SetMax(self, arg0: Vec2i) -> None: ... def SetMaxX(self, arg0: int) -> None: ... def SetMaxY(self, arg0: int) -> None: ... def SetMin(self, arg0: Vec2i) -> None: ... def SetMinX(self, arg0: int) -> None: ... def SetMinY(self, arg0: int) -> None: ... def Translate(self, arg0: Vec2i) -> None: ... def Union(self, arg0: Rect2i) -> Rect2i: ... def __add__(self, arg0: Rect2i) -> Rect2i: ... def __copy__(self) -> Rect2i: ... def __deepcopy__(self, memo: dict) -> Rect2i: ... def __eq__(self, arg0: Rect2i) -> bool: ... def __iadd__(self, arg0: Rect2i) -> Rect2i: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Rect2i) -> None: ... @typing.overload def __init__(self, arg0: Vec2i, arg1: Vec2i) -> None: ... @typing.overload def __init__(self, arg0: Vec2i, arg1: int, arg2: int) -> None: ... def __ne__(self, arg0: Rect2i) -> bool: ... def __repr__(self) -> str: ... def __str__(self) -> str: ... @property def area(self) -> int: """ :type: int """ @property def center(self) -> Vec2i: """ :type: Vec2i """ @property def height(self) -> int: """ :type: int """ @property def max(self) -> Vec2i: """ :type: Vec2i """ @max.setter def max(self, arg1: Vec2i) -> None: pass @property def maxX(self) -> int: """ :type: int """ @maxX.setter def maxX(self, arg1: int) -> None: pass @property def maxY(self) -> int: """ :type: int """ @maxY.setter def maxY(self, arg1: int) -> None: pass @property def min(self) -> Vec2i: """ :type: Vec2i """ @min.setter def min(self, arg1: Vec2i) -> None: pass @property def minX(self) -> int: """ :type: int """ @minX.setter def minX(self, arg1: int) -> None: pass @property def minY(self) -> int: """ :type: int """ @minY.setter def minY(self, arg1: int) -> None: pass @property def size(self) -> Vec2i: """ :type: Vec2i """ @property def width(self) -> int: """ :type: int """ __hash__ = None pass class Vec2d(): @staticmethod def Axis(arg0: int) -> Vec2d: ... def GetComplement(self, arg0: Vec2d) -> Vec2d: ... def GetDot(self, arg0: Vec2d) -> float: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec2d: ... def GetProjection(self, arg0: Vec2d) -> Vec2d: ... def Normalize(self) -> float: ... @staticmethod def XAxis() -> Vec2d: ... @staticmethod def YAxis() -> Vec2d: ... def __add__(self, arg0: Vec2d) -> Vec2d: ... def __copy__(self) -> Vec2d: ... def __deepcopy__(self, memo: dict) -> Vec2d: ... @staticmethod @typing.overload def __eq__(*args, **kwargs) -> typing.Any: ... @typing.overload def __eq__(self, arg0: Vec2d) -> bool: ... @typing.overload def __eq__(self, arg0: Vec2f) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> float: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[float]: ... def __iadd__(self, arg0: Vec2d) -> Vec2d: ... def __imul__(self, arg0: float) -> Vec2d: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Vec2d) -> None: ... @typing.overload def __init__(self, arg0: Vec2f) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[float, float]) -> None: ... def __isub__(self, arg0: Vec2d) -> Vec2d: ... def __itruediv__(self, arg0: float) -> Vec2d: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Vec2d) -> float: ... @typing.overload def __mul__(self, arg0: float) -> Vec2d: ... @staticmethod @typing.overload def __ne__(*args, **kwargs) -> typing.Any: ... @typing.overload def __ne__(self, arg0: Vec2d) -> bool: ... @typing.overload def __ne__(self, arg0: Vec2f) -> bool: ... def __neg__(self) -> Vec2d: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Vec2d: ... @typing.overload def __setitem__(self, arg0: int, arg1: float) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec2d) -> Vec2d: ... def __truediv__(self, arg0: float) -> Vec2d: ... __hash__ = None __isGfVec = True dimension = 2 pass class Vec2f(): @staticmethod def Axis(arg0: int) -> Vec2f: ... def GetComplement(self, arg0: Vec2f) -> Vec2f: ... def GetDot(self, arg0: Vec2f) -> float: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec2f: ... def GetProjection(self, arg0: Vec2f) -> Vec2f: ... def Normalize(self) -> float: ... @staticmethod def XAxis() -> Vec2f: ... @staticmethod def YAxis() -> Vec2f: ... def __add__(self, arg0: Vec2f) -> Vec2f: ... def __copy__(self) -> Vec2f: ... def __deepcopy__(self, memo: dict) -> Vec2f: ... @staticmethod @typing.overload def __eq__(*args, **kwargs) -> typing.Any: ... @typing.overload def __eq__(self, arg0: Vec2f) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> float: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[float]: ... def __iadd__(self, arg0: Vec2f) -> Vec2f: ... def __imul__(self, arg0: float) -> Vec2f: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Vec2f) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[float, float]) -> None: ... def __isub__(self, arg0: Vec2f) -> Vec2f: ... def __itruediv__(self, arg0: float) -> Vec2f: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Vec2f) -> float: ... @typing.overload def __mul__(self, arg0: float) -> Vec2f: ... @staticmethod @typing.overload def __ne__(*args, **kwargs) -> typing.Any: ... @typing.overload def __ne__(self, arg0: Vec2f) -> bool: ... def __neg__(self) -> Vec2f: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Vec2f: ... @typing.overload def __setitem__(self, arg0: int, arg1: float) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec2f) -> Vec2f: ... def __truediv__(self, arg0: float) -> Vec2f: ... __hash__ = None __isGfVec = True dimension = 2 pass class Vec2h(): @staticmethod def Axis(arg0: int) -> Vec2h: ... def GetComplement(self, arg0: Vec2h) -> Vec2h: ... def GetDot(self, arg0: Vec2h) -> GfHalf: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec2h: ... def GetProjection(self, arg0: Vec2h) -> Vec2h: ... def Normalize(self) -> float: ... @staticmethod def XAxis() -> Vec2h: ... @staticmethod def YAxis() -> Vec2h: ... def __add__(self, arg0: Vec2h) -> Vec2h: ... def __copy__(self) -> Vec2h: ... def __deepcopy__(self, memo: dict) -> Vec2h: ... @typing.overload def __eq__(self, arg0: Vec2h) -> bool: ... @typing.overload def __eq__(self, arg0: Vec2i) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> GfHalf: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[GfHalf]: ... def __iadd__(self, arg0: Vec2h) -> Vec2h: ... def __imul__(self, arg0: GfHalf) -> Vec2h: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: GfHalf) -> None: ... @typing.overload def __init__(self, arg0: GfHalf, arg1: GfHalf) -> None: ... @typing.overload def __init__(self, arg0: Vec2d) -> None: ... @typing.overload def __init__(self, arg0: Vec2f) -> None: ... @typing.overload def __init__(self, arg0: Vec2h) -> None: ... @typing.overload def __init__(self, arg0: Vec2i) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[GfHalf, GfHalf]) -> None: ... def __isub__(self, arg0: Vec2h) -> Vec2h: ... def __itruediv__(self, arg0: GfHalf) -> Vec2h: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: GfHalf) -> Vec2h: ... @typing.overload def __mul__(self, arg0: Vec2h) -> GfHalf: ... @typing.overload def __ne__(self, arg0: Vec2h) -> bool: ... @typing.overload def __ne__(self, arg0: Vec2i) -> bool: ... def __neg__(self) -> Vec2h: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: GfHalf) -> Vec2h: ... @typing.overload def __setitem__(self, arg0: int, arg1: GfHalf) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec2h) -> Vec2h: ... def __truediv__(self, arg0: GfHalf) -> Vec2h: ... __hash__ = None __isGfVec = True dimension = 2 pass class Vec2i(): @staticmethod def Axis(arg0: int) -> Vec2i: ... def GetComplement(self, arg0: Vec2i) -> Vec2i: ... def GetDot(self, arg0: Vec2i) -> int: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec2i: ... def GetProjection(self, arg0: Vec2i) -> Vec2i: ... def Normalize(self) -> float: ... @staticmethod def XAxis() -> Vec2i: ... @staticmethod def YAxis() -> Vec2i: ... def __add__(self, arg0: Vec2i) -> Vec2i: ... def __copy__(self) -> Vec2i: ... def __deepcopy__(self, memo: dict) -> Vec2i: ... def __eq__(self, arg0: Vec2i) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> int: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[int]: ... def __iadd__(self, arg0: Vec2i) -> Vec2i: ... def __imul__(self, arg0: int) -> Vec2i: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Vec2d) -> None: ... @typing.overload def __init__(self, arg0: Vec2f) -> None: ... @typing.overload def __init__(self, arg0: Vec2i) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: int) -> None: ... @typing.overload def __init__(self, arg0: int, arg1: int) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[int, int]) -> None: ... def __isub__(self, arg0: Vec2i) -> Vec2i: ... def __itruediv__(self, arg0: int) -> Vec2i: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Vec2i) -> int: ... @typing.overload def __mul__(self, arg0: int) -> Vec2i: ... def __ne__(self, arg0: Vec2i) -> bool: ... def __neg__(self) -> Vec2i: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: int) -> Vec2i: ... @typing.overload def __setitem__(self, arg0: int, arg1: int) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec2i) -> Vec2i: ... def __truediv__(self, arg0: int) -> Vec2i: ... __hash__ = None __isGfVec = True dimension = 2 pass class Vec3d(): @staticmethod def Axis(arg0: int) -> Vec3d: ... def BuildOrthonormalFrame(self, eps: float = 1e-10) -> tuple: ... def GetComplement(self, arg0: Vec3d) -> Vec3d: ... def GetCross(self, arg0: Vec3d) -> Vec3d: ... def GetDot(self, arg0: Vec3d) -> float: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec3d: ... def GetProjection(self, arg0: Vec3d) -> Vec3d: ... def Normalize(self) -> float: ... @staticmethod def OrthogonalizeBasis(v1: Vec3d, v2: Vec3d, v3: Vec3d, normalize: bool = True) -> bool: ... @staticmethod def XAxis() -> Vec3d: ... @staticmethod def YAxis() -> Vec3d: ... @staticmethod def ZAxis() -> Vec3d: ... def __add__(self, arg0: Vec3d) -> Vec3d: ... def __copy__(self) -> Vec3d: ... def __deepcopy__(self, memo: dict) -> Vec3d: ... @staticmethod @typing.overload def __eq__(*args, **kwargs) -> typing.Any: ... @typing.overload def __eq__(self, arg0: Vec3d) -> bool: ... @typing.overload def __eq__(self, arg0: Vec3f) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> float: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[float]: ... def __iadd__(self, arg0: Vec3d) -> Vec3d: ... def __imul__(self, arg0: float) -> Vec3d: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Vec3d) -> None: ... @typing.overload def __init__(self, arg0: Vec3f) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[float, float, float]) -> None: ... def __isub__(self, arg0: Vec3d) -> Vec3d: ... def __itruediv__(self, arg0: float) -> Vec3d: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Vec3d) -> float: ... @typing.overload def __mul__(self, arg0: float) -> Vec3d: ... @staticmethod @typing.overload def __ne__(*args, **kwargs) -> typing.Any: ... @typing.overload def __ne__(self, arg0: Vec3d) -> bool: ... @typing.overload def __ne__(self, arg0: Vec3f) -> bool: ... def __neg__(self) -> Vec3d: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Vec3d: ... @typing.overload def __setitem__(self, arg0: int, arg1: float) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec3d) -> Vec3d: ... def __truediv__(self, arg0: float) -> Vec3d: ... def __xor__(self, arg0: Vec3d) -> Vec3d: ... __hash__ = None __isGfVec = True dimension = 3 pass class Vec3f(): @staticmethod def Axis(arg0: int) -> Vec3f: ... def BuildOrthonormalFrame(self, eps: float = 1e-10) -> tuple: ... def GetComplement(self, arg0: Vec3f) -> Vec3f: ... def GetCross(self, arg0: Vec3f) -> Vec3f: ... def GetDot(self, arg0: Vec3f) -> float: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec3f: ... def GetProjection(self, arg0: Vec3f) -> Vec3f: ... def Normalize(self) -> float: ... @staticmethod def OrthogonalizeBasis(v1: Vec3f, v2: Vec3f, v3: Vec3f, normalize: bool = True) -> bool: ... @staticmethod def XAxis() -> Vec3f: ... @staticmethod def YAxis() -> Vec3f: ... @staticmethod def ZAxis() -> Vec3f: ... def __add__(self, arg0: Vec3f) -> Vec3f: ... def __copy__(self) -> Vec3f: ... def __deepcopy__(self, memo: dict) -> Vec3f: ... @staticmethod @typing.overload def __eq__(*args, **kwargs) -> typing.Any: ... @typing.overload def __eq__(self, arg0: Vec3f) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> float: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[float]: ... def __iadd__(self, arg0: Vec3f) -> Vec3f: ... def __imul__(self, arg0: float) -> Vec3f: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Vec3f) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[float, float, float]) -> None: ... def __isub__(self, arg0: Vec3f) -> Vec3f: ... def __itruediv__(self, arg0: float) -> Vec3f: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Vec3f) -> float: ... @typing.overload def __mul__(self, arg0: float) -> Vec3f: ... @staticmethod @typing.overload def __ne__(*args, **kwargs) -> typing.Any: ... @typing.overload def __ne__(self, arg0: Vec3f) -> bool: ... def __neg__(self) -> Vec3f: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Vec3f: ... @typing.overload def __setitem__(self, arg0: int, arg1: float) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec3f) -> Vec3f: ... def __truediv__(self, arg0: float) -> Vec3f: ... def __xor__(self, arg0: Vec3f) -> Vec3f: ... __hash__ = None __isGfVec = True dimension = 3 pass class Vec3h(): @staticmethod def Axis(arg0: int) -> Vec3h: ... def BuildOrthonormalFrame(self, eps: float = 1e-10) -> tuple: ... def GetComplement(self, arg0: Vec3h) -> Vec3h: ... def GetCross(self, arg0: Vec3h) -> Vec3h: ... def GetDot(self, arg0: Vec3h) -> GfHalf: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec3h: ... def GetProjection(self, arg0: Vec3h) -> Vec3h: ... def Normalize(self) -> float: ... @staticmethod def OrthogonalizeBasis(v1: Vec3h, v2: Vec3h, v3: Vec3h, normalize: bool = True) -> bool: ... @staticmethod def XAxis() -> Vec3h: ... @staticmethod def YAxis() -> Vec3h: ... @staticmethod def ZAxis() -> Vec3h: ... def __add__(self, arg0: Vec3h) -> Vec3h: ... def __copy__(self) -> Vec3h: ... def __deepcopy__(self, memo: dict) -> Vec3h: ... @typing.overload def __eq__(self, arg0: Vec3h) -> bool: ... @typing.overload def __eq__(self, arg0: Vec3i) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> GfHalf: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[GfHalf]: ... def __iadd__(self, arg0: Vec3h) -> Vec3h: ... def __imul__(self, arg0: GfHalf) -> Vec3h: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: GfHalf) -> None: ... @typing.overload def __init__(self, arg0: GfHalf, arg1: GfHalf, arg2: GfHalf) -> None: ... @typing.overload def __init__(self, arg0: Vec3d) -> None: ... @typing.overload def __init__(self, arg0: Vec3f) -> None: ... @typing.overload def __init__(self, arg0: Vec3h) -> None: ... @typing.overload def __init__(self, arg0: Vec3i) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[GfHalf, GfHalf, GfHalf]) -> None: ... def __isub__(self, arg0: Vec3h) -> Vec3h: ... def __itruediv__(self, arg0: GfHalf) -> Vec3h: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: GfHalf) -> Vec3h: ... @typing.overload def __mul__(self, arg0: Vec3h) -> GfHalf: ... @typing.overload def __ne__(self, arg0: Vec3h) -> bool: ... @typing.overload def __ne__(self, arg0: Vec3i) -> bool: ... def __neg__(self) -> Vec3h: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: GfHalf) -> Vec3h: ... @typing.overload def __setitem__(self, arg0: int, arg1: GfHalf) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec3h) -> Vec3h: ... def __truediv__(self, arg0: GfHalf) -> Vec3h: ... def __xor__(self, arg0: Vec3h) -> Vec3h: ... __hash__ = None __isGfVec = True dimension = 3 pass class Vec3i(): @staticmethod def Axis(arg0: int) -> Vec3i: ... def BuildOrthonormalFrame(self, eps: float = 1e-10) -> tuple: ... def GetComplement(self, arg0: Vec3i) -> Vec3i: ... def GetCross(self, arg0: Vec3i) -> Vec3i: ... def GetDot(self, arg0: Vec3i) -> int: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec3i: ... def GetProjection(self, arg0: Vec3i) -> Vec3i: ... def Normalize(self) -> float: ... @staticmethod def OrthogonalizeBasis(v1: Vec3i, v2: Vec3i, v3: Vec3i, normalize: bool = True) -> bool: ... @staticmethod def XAxis() -> Vec3i: ... @staticmethod def YAxis() -> Vec3i: ... @staticmethod def ZAxis() -> Vec3i: ... def __add__(self, arg0: Vec3i) -> Vec3i: ... def __copy__(self) -> Vec3i: ... def __deepcopy__(self, memo: dict) -> Vec3i: ... def __eq__(self, arg0: Vec3i) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> int: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[int]: ... def __iadd__(self, arg0: Vec3i) -> Vec3i: ... def __imul__(self, arg0: int) -> Vec3i: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Vec3d) -> None: ... @typing.overload def __init__(self, arg0: Vec3f) -> None: ... @typing.overload def __init__(self, arg0: Vec3i) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: int) -> None: ... @typing.overload def __init__(self, arg0: int, arg1: int, arg2: int) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[int, int, int]) -> None: ... def __isub__(self, arg0: Vec3i) -> Vec3i: ... def __itruediv__(self, arg0: int) -> Vec3i: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Vec3i) -> int: ... @typing.overload def __mul__(self, arg0: int) -> Vec3i: ... def __ne__(self, arg0: Vec3i) -> bool: ... def __neg__(self) -> Vec3i: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: int) -> Vec3i: ... @typing.overload def __setitem__(self, arg0: int, arg1: int) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec3i) -> Vec3i: ... def __truediv__(self, arg0: int) -> Vec3i: ... def __xor__(self, arg0: Vec3i) -> Vec3i: ... __hash__ = None __isGfVec = True dimension = 3 pass class Vec4d(): @staticmethod def Axis(arg0: int) -> Vec4d: ... def GetComplement(self, arg0: Vec4d) -> Vec4d: ... def GetDot(self, arg0: Vec4d) -> float: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec4d: ... def GetProjection(self, arg0: Vec4d) -> Vec4d: ... def Normalize(self) -> float: ... @staticmethod def WAxis() -> Vec4d: ... @staticmethod def XAxis() -> Vec4d: ... @staticmethod def YAxis() -> Vec4d: ... @staticmethod def ZAxis() -> Vec4d: ... def __add__(self, arg0: Vec4d) -> Vec4d: ... def __copy__(self) -> Vec4d: ... def __deepcopy__(self, memo: dict) -> Vec4d: ... @staticmethod @typing.overload def __eq__(*args, **kwargs) -> typing.Any: ... @typing.overload def __eq__(self, arg0: Vec4d) -> bool: ... @typing.overload def __eq__(self, arg0: Vec4f) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> float: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[float]: ... def __iadd__(self, arg0: Vec4d) -> Vec4d: ... def __imul__(self, arg0: float) -> Vec4d: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Vec4d) -> None: ... @typing.overload def __init__(self, arg0: Vec4f) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[float, float, float, float]) -> None: ... def __isub__(self, arg0: Vec4d) -> Vec4d: ... def __itruediv__(self, arg0: float) -> Vec4d: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Vec4d) -> float: ... @typing.overload def __mul__(self, arg0: float) -> Vec4d: ... @staticmethod @typing.overload def __ne__(*args, **kwargs) -> typing.Any: ... @typing.overload def __ne__(self, arg0: Vec4d) -> bool: ... @typing.overload def __ne__(self, arg0: Vec4f) -> bool: ... def __neg__(self) -> Vec4d: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Vec4d: ... @typing.overload def __setitem__(self, arg0: int, arg1: float) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec4d) -> Vec4d: ... def __truediv__(self, arg0: float) -> Vec4d: ... __hash__ = None __isGfVec = True dimension = 4 pass class Vec4f(): @staticmethod def Axis(arg0: int) -> Vec4f: ... def GetComplement(self, arg0: Vec4f) -> Vec4f: ... def GetDot(self, arg0: Vec4f) -> float: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec4f: ... def GetProjection(self, arg0: Vec4f) -> Vec4f: ... def Normalize(self) -> float: ... @staticmethod def WAxis() -> Vec4f: ... @staticmethod def XAxis() -> Vec4f: ... @staticmethod def YAxis() -> Vec4f: ... @staticmethod def ZAxis() -> Vec4f: ... def __add__(self, arg0: Vec4f) -> Vec4f: ... def __copy__(self) -> Vec4f: ... def __deepcopy__(self, memo: dict) -> Vec4f: ... @staticmethod @typing.overload def __eq__(*args, **kwargs) -> typing.Any: ... @typing.overload def __eq__(self, arg0: Vec4f) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> float: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[float]: ... def __iadd__(self, arg0: Vec4f) -> Vec4f: ... def __imul__(self, arg0: float) -> Vec4f: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Vec4f) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[float, float, float, float]) -> None: ... def __isub__(self, arg0: Vec4f) -> Vec4f: ... def __itruediv__(self, arg0: float) -> Vec4f: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Vec4f) -> float: ... @typing.overload def __mul__(self, arg0: float) -> Vec4f: ... @staticmethod @typing.overload def __ne__(*args, **kwargs) -> typing.Any: ... @typing.overload def __ne__(self, arg0: Vec4f) -> bool: ... def __neg__(self) -> Vec4f: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: float) -> Vec4f: ... @typing.overload def __setitem__(self, arg0: int, arg1: float) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec4f) -> Vec4f: ... def __truediv__(self, arg0: float) -> Vec4f: ... __hash__ = None __isGfVec = True dimension = 4 pass class Vec4h(): @staticmethod def Axis(arg0: int) -> Vec4h: ... def GetComplement(self, arg0: Vec4h) -> Vec4h: ... def GetDot(self, arg0: Vec4h) -> GfHalf: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec4h: ... def GetProjection(self, arg0: Vec4h) -> Vec4h: ... def Normalize(self) -> float: ... @staticmethod def WAxis() -> Vec4h: ... @staticmethod def XAxis() -> Vec4h: ... @staticmethod def YAxis() -> Vec4h: ... @staticmethod def ZAxis() -> Vec4h: ... def __add__(self, arg0: Vec4h) -> Vec4h: ... def __copy__(self) -> Vec4h: ... def __deepcopy__(self, memo: dict) -> Vec4h: ... @typing.overload def __eq__(self, arg0: Vec4h) -> bool: ... @typing.overload def __eq__(self, arg0: Vec4i) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> GfHalf: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[GfHalf]: ... def __iadd__(self, arg0: Vec4h) -> Vec4h: ... def __imul__(self, arg0: GfHalf) -> Vec4h: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: GfHalf) -> None: ... @typing.overload def __init__(self, arg0: GfHalf, arg1: GfHalf, arg2: GfHalf, arg3: GfHalf) -> None: ... @typing.overload def __init__(self, arg0: Vec4d) -> None: ... @typing.overload def __init__(self, arg0: Vec4f) -> None: ... @typing.overload def __init__(self, arg0: Vec4h) -> None: ... @typing.overload def __init__(self, arg0: Vec4i) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[GfHalf, GfHalf, GfHalf, GfHalf]) -> None: ... def __isub__(self, arg0: Vec4h) -> Vec4h: ... def __itruediv__(self, arg0: GfHalf) -> Vec4h: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: GfHalf) -> Vec4h: ... @typing.overload def __mul__(self, arg0: Vec4h) -> GfHalf: ... @typing.overload def __ne__(self, arg0: Vec4h) -> bool: ... @typing.overload def __ne__(self, arg0: Vec4i) -> bool: ... def __neg__(self) -> Vec4h: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: GfHalf) -> Vec4h: ... @typing.overload def __setitem__(self, arg0: int, arg1: GfHalf) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec4h) -> Vec4h: ... def __truediv__(self, arg0: GfHalf) -> Vec4h: ... __hash__ = None __isGfVec = True dimension = 4 pass class Vec4i(): @staticmethod def Axis(arg0: int) -> Vec4i: ... def GetComplement(self, arg0: Vec4i) -> Vec4i: ... def GetDot(self, arg0: Vec4i) -> int: ... def GetLength(self) -> float: ... def GetNormalized(self) -> Vec4i: ... def GetProjection(self, arg0: Vec4i) -> Vec4i: ... def Normalize(self) -> float: ... @staticmethod def WAxis() -> Vec4i: ... @staticmethod def XAxis() -> Vec4i: ... @staticmethod def YAxis() -> Vec4i: ... @staticmethod def ZAxis() -> Vec4i: ... def __add__(self, arg0: Vec4i) -> Vec4i: ... def __copy__(self) -> Vec4i: ... def __deepcopy__(self, memo: dict) -> Vec4i: ... def __eq__(self, arg0: Vec4i) -> bool: ... @typing.overload def __getitem__(self, arg0: int) -> int: ... @typing.overload def __getitem__(self, arg0: slice) -> typing.List[int]: ... def __iadd__(self, arg0: Vec4i) -> Vec4i: ... def __imul__(self, arg0: int) -> Vec4i: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @typing.overload def __init__(self) -> None: ... @typing.overload def __init__(self, arg0: Vec4d) -> None: ... @typing.overload def __init__(self, arg0: Vec4f) -> None: ... @typing.overload def __init__(self, arg0: Vec4i) -> None: ... @typing.overload def __init__(self, arg0: buffer) -> None: ... @typing.overload def __init__(self, arg0: int) -> None: ... @typing.overload def __init__(self, arg0: int, arg1: int, arg2: int, arg3: int) -> None: ... @typing.overload def __init__(self, arg0: typing.Tuple[int, int, int, int]) -> None: ... def __isub__(self, arg0: Vec4i) -> Vec4i: ... def __itruediv__(self, arg0: int) -> Vec4i: ... def __len__(self) -> int: ... @typing.overload def __mul__(self, arg0: Vec4i) -> int: ... @typing.overload def __mul__(self, arg0: int) -> Vec4i: ... def __ne__(self, arg0: Vec4i) -> bool: ... def __neg__(self) -> Vec4i: ... def __repr__(self) -> str: ... def __rmul__(self, arg0: int) -> Vec4i: ... @typing.overload def __setitem__(self, arg0: int, arg1: int) -> None: ... @typing.overload def __setitem__(self, arg0: slice, arg1: sequence) -> None: ... def __str__(self) -> str: ... def __sub__(self, arg0: Vec4i) -> Vec4i: ... def __truediv__(self, arg0: int) -> Vec4i: ... __hash__ = None __isGfVec = True dimension = 4 pass @typing.overload def CompDiv(arg0: Vec2d, arg1: Vec2d) -> Vec2d: pass @typing.overload def CompDiv(arg0: Vec2f, arg1: Vec2f) -> Vec2f: pass @typing.overload def CompDiv(arg0: Vec2h, arg1: Vec2h) -> Vec2h: pass @typing.overload def CompDiv(arg0: Vec2i, arg1: Vec2i) -> Vec2i: pass @typing.overload def CompDiv(arg0: Vec3d, arg1: Vec3d) -> Vec3d: pass @typing.overload def CompDiv(arg0: Vec3f, arg1: Vec3f) -> Vec3f: pass @typing.overload def CompDiv(arg0: Vec3h, arg1: Vec3h) -> Vec3h: pass @typing.overload def CompDiv(arg0: Vec3i, arg1: Vec3i) -> Vec3i: pass @typing.overload def CompDiv(arg0: Vec4d, arg1: Vec4d) -> Vec4d: pass @typing.overload def CompDiv(arg0: Vec4f, arg1: Vec4f) -> Vec4f: pass @typing.overload def CompDiv(arg0: Vec4h, arg1: Vec4h) -> Vec4h: pass @typing.overload def CompDiv(arg0: Vec4i, arg1: Vec4i) -> Vec4i: pass @typing.overload def CompMult(arg0: Vec2d, arg1: Vec2d) -> Vec2d: pass @typing.overload def CompMult(arg0: Vec2f, arg1: Vec2f) -> Vec2f: pass @typing.overload def CompMult(arg0: Vec2h, arg1: Vec2h) -> Vec2h: pass @typing.overload def CompMult(arg0: Vec2i, arg1: Vec2i) -> Vec2i: pass @typing.overload def CompMult(arg0: Vec3d, arg1: Vec3d) -> Vec3d: pass @typing.overload def CompMult(arg0: Vec3f, arg1: Vec3f) -> Vec3f: pass @typing.overload def CompMult(arg0: Vec3h, arg1: Vec3h) -> Vec3h: pass @typing.overload def CompMult(arg0: Vec3i, arg1: Vec3i) -> Vec3i: pass @typing.overload def CompMult(arg0: Vec4d, arg1: Vec4d) -> Vec4d: pass @typing.overload def CompMult(arg0: Vec4f, arg1: Vec4f) -> Vec4f: pass @typing.overload def CompMult(arg0: Vec4h, arg1: Vec4h) -> Vec4h: pass @typing.overload def CompMult(arg0: Vec4i, arg1: Vec4i) -> Vec4i: pass @typing.overload def Cross(arg0: Vec3d, arg1: Vec3d) -> Vec3d: pass @typing.overload def Cross(arg0: Vec3f, arg1: Vec3f) -> Vec3f: pass @typing.overload def Cross(arg0: Vec3h, arg1: Vec3h) -> Vec3h: pass @typing.overload def Cross(arg0: Vec3i, arg1: Vec3i) -> Vec3i: pass def DegreesToRadians(arg0: float) -> float: pass @typing.overload def Dot(arg0: Quatd, arg1: Quatd) -> float: pass @typing.overload def Dot(arg0: Quatf, arg1: Quatf) -> float: pass @typing.overload def Dot(arg0: Quath, arg1: Quath) -> GfHalf: pass @typing.overload def Dot(arg0: Vec2d, arg1: Vec2d) -> float: pass @typing.overload def Dot(arg0: Vec2f, arg1: Vec2f) -> float: pass @typing.overload def Dot(arg0: Vec2h, arg1: Vec2h) -> GfHalf: pass @typing.overload def Dot(arg0: Vec2i, arg1: Vec2i) -> int: pass @typing.overload def Dot(arg0: Vec3d, arg1: Vec3d) -> float: pass @typing.overload def Dot(arg0: Vec3f, arg1: Vec3f) -> float: pass @typing.overload def Dot(arg0: Vec3h, arg1: Vec3h) -> GfHalf: pass @typing.overload def Dot(arg0: Vec3i, arg1: Vec3i) -> int: pass @typing.overload def Dot(arg0: Vec4d, arg1: Vec4d) -> float: pass @typing.overload def Dot(arg0: Vec4f, arg1: Vec4f) -> float: pass @typing.overload def Dot(arg0: Vec4h, arg1: Vec4h) -> GfHalf: pass @typing.overload def Dot(arg0: Vec4i, arg1: Vec4i) -> int: pass @typing.overload def GetComplement(arg0: Vec2d, arg1: Vec2d) -> Vec2d: pass @typing.overload def GetComplement(arg0: Vec2f, arg1: Vec2f) -> Vec2f: pass @typing.overload def GetComplement(arg0: Vec2h, arg1: Vec2h) -> Vec2h: pass @typing.overload def GetComplement(arg0: Vec2i, arg1: Vec2i) -> Vec2i: pass @typing.overload def GetComplement(arg0: Vec3d, arg1: Vec3d) -> Vec3d: pass @typing.overload def GetComplement(arg0: Vec3f, arg1: Vec3f) -> Vec3f: pass @typing.overload def GetComplement(arg0: Vec3h, arg1: Vec3h) -> Vec3h: pass @typing.overload def GetComplement(arg0: Vec3i, arg1: Vec3i) -> Vec3i: pass @typing.overload def GetComplement(arg0: Vec4d, arg1: Vec4d) -> Vec4d: pass @typing.overload def GetComplement(arg0: Vec4f, arg1: Vec4f) -> Vec4f: pass @typing.overload def GetComplement(arg0: Vec4h, arg1: Vec4h) -> Vec4h: pass @typing.overload def GetComplement(arg0: Vec4i, arg1: Vec4i) -> Vec4i: pass @typing.overload def GetLength(arg0: Vec2d) -> float: pass @typing.overload def GetLength(arg0: Vec2f) -> float: pass @typing.overload def GetLength(arg0: Vec2h) -> float: pass @typing.overload def GetLength(arg0: Vec2i) -> float: pass @typing.overload def GetLength(arg0: Vec3d) -> float: pass @typing.overload def GetLength(arg0: Vec3f) -> float: pass @typing.overload def GetLength(arg0: Vec3h) -> float: pass @typing.overload def GetLength(arg0: Vec3i) -> float: pass @typing.overload def GetLength(arg0: Vec4d) -> float: pass @typing.overload def GetLength(arg0: Vec4f) -> float: pass @typing.overload def GetLength(arg0: Vec4h) -> float: pass @typing.overload def GetLength(arg0: Vec4i) -> float: pass @typing.overload def GetNormalized(arg0: Vec2d) -> Vec2d: pass @typing.overload def GetNormalized(arg0: Vec2f) -> Vec2f: pass @typing.overload def GetNormalized(arg0: Vec2h) -> Vec2h: pass @typing.overload def GetNormalized(arg0: Vec2i) -> Vec2i: pass @typing.overload def GetNormalized(arg0: Vec3d) -> Vec3d: pass @typing.overload def GetNormalized(arg0: Vec3f) -> Vec3f: pass @typing.overload def GetNormalized(arg0: Vec3h) -> Vec3h: pass @typing.overload def GetNormalized(arg0: Vec3i) -> Vec3i: pass @typing.overload def GetNormalized(arg0: Vec4d) -> Vec4d: pass @typing.overload def GetNormalized(arg0: Vec4f) -> Vec4f: pass @typing.overload def GetNormalized(arg0: Vec4h) -> Vec4h: pass @typing.overload def GetNormalized(arg0: Vec4i) -> Vec4i: pass @typing.overload def GetProjection(arg0: Vec2d, arg1: Vec2d) -> Vec2d: pass @typing.overload def GetProjection(arg0: Vec2f, arg1: Vec2f) -> Vec2f: pass @typing.overload def GetProjection(arg0: Vec2h, arg1: Vec2h) -> Vec2h: pass @typing.overload def GetProjection(arg0: Vec2i, arg1: Vec2i) -> Vec2i: pass @typing.overload def GetProjection(arg0: Vec3d, arg1: Vec3d) -> Vec3d: pass @typing.overload def GetProjection(arg0: Vec3f, arg1: Vec3f) -> Vec3f: pass @typing.overload def GetProjection(arg0: Vec3h, arg1: Vec3h) -> Vec3h: pass @typing.overload def GetProjection(arg0: Vec3i, arg1: Vec3i) -> Vec3i: pass @typing.overload def GetProjection(arg0: Vec4d, arg1: Vec4d) -> Vec4d: pass @typing.overload def GetProjection(arg0: Vec4f, arg1: Vec4f) -> Vec4f: pass @typing.overload def GetProjection(arg0: Vec4h, arg1: Vec4h) -> Vec4h: pass @typing.overload def GetProjection(arg0: Vec4i, arg1: Vec4i) -> Vec4i: pass @typing.overload def IsClose(arg0: Matrix4d, arg1: Matrix4d, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Matrix4f, arg1: Matrix4f, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Quatd, arg1: Quatd, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Quatf, arg1: Quatf, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Quath, arg1: Quath, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec2d, arg1: Vec2d, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec2f, arg1: Vec2f, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec2h, arg1: Vec2h, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec2i, arg1: Vec2i, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec3d, arg1: Vec3d, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec3f, arg1: Vec3f, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec3h, arg1: Vec3h, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec3i, arg1: Vec3i, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec4d, arg1: Vec4d, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec4f, arg1: Vec4f, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec4h, arg1: Vec4h, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: Vec4i, arg1: Vec4i, arg2: float) -> bool: pass @typing.overload def IsClose(arg0: float, arg1: float, arg2: float) -> bool: pass @typing.overload def Lerp(alpha: float, a: Vec2d, b: Vec2d) -> Vec2d: pass @typing.overload def Lerp(alpha: float, a: Vec2f, b: Vec2f) -> Vec2f: pass @typing.overload def Lerp(alpha: float, a: Vec2h, b: Vec2h) -> Vec2h: pass @typing.overload def Lerp(alpha: float, a: Vec2i, b: Vec2i) -> Vec2i: pass @typing.overload def Lerp(alpha: float, a: Vec3d, b: Vec3d) -> Vec3d: pass @typing.overload def Lerp(alpha: float, a: Vec3f, b: Vec3f) -> Vec3f: pass @typing.overload def Lerp(alpha: float, a: Vec3h, b: Vec3h) -> Vec3h: pass @typing.overload def Lerp(alpha: float, a: Vec3i, b: Vec3i) -> Vec3i: pass @typing.overload def Lerp(alpha: float, a: Vec4d, b: Vec4d) -> Vec4d: pass @typing.overload def Lerp(alpha: float, a: Vec4f, b: Vec4f) -> Vec4f: pass @typing.overload def Lerp(alpha: float, a: Vec4h, b: Vec4h) -> Vec4h: pass @typing.overload def Lerp(alpha: float, a: Vec4i, b: Vec4i) -> Vec4i: pass @typing.overload def Lerp(alpha: float, a: float, b: float) -> float: pass def Lerpf(alpha: float, a: float, b: float) -> float: pass @typing.overload def Max(arg0: float, arg1: float) -> float: pass @typing.overload def Max(arg0: float, arg1: float, arg2: float) -> float: pass @typing.overload def Max(arg0: float, arg1: float, arg2: float, arg3: float) -> float: pass @typing.overload def Max(arg0: float, arg1: float, arg2: float, arg3: float, arg4: float) -> float: pass @typing.overload def Max(arg0: int, arg1: int) -> int: pass @typing.overload def Max(arg0: int, arg1: int, arg2: int) -> int: pass @typing.overload def Max(arg0: int, arg1: int, arg2: int, arg3: int) -> int: pass @typing.overload def Max(arg0: int, arg1: int, arg2: int, arg3: int, arg4: int) -> int: pass @typing.overload def Min(arg0: float, arg1: float) -> float: pass @typing.overload def Min(arg0: float, arg1: float, arg2: float) -> float: pass @typing.overload def Min(arg0: float, arg1: float, arg2: float, arg3: float) -> float: pass @typing.overload def Min(arg0: float, arg1: float, arg2: float, arg3: float, arg4: float) -> float: pass @typing.overload def Min(arg0: int, arg1: int) -> int: pass @typing.overload def Min(arg0: int, arg1: int, arg2: int) -> int: pass @typing.overload def Min(arg0: int, arg1: int, arg2: int, arg3: int) -> int: pass @typing.overload def Min(arg0: int, arg1: int, arg2: int, arg3: int, arg4: int) -> int: pass @typing.overload def Normalize(arg0: Vec2d) -> float: pass @typing.overload def Normalize(arg0: Vec2f) -> float: pass @typing.overload def Normalize(arg0: Vec2h) -> float: pass @typing.overload def Normalize(arg0: Vec2i) -> float: pass @typing.overload def Normalize(arg0: Vec3d) -> float: pass @typing.overload def Normalize(arg0: Vec3f) -> float: pass @typing.overload def Normalize(arg0: Vec3h) -> float: pass @typing.overload def Normalize(arg0: Vec3i) -> float: pass @typing.overload def Normalize(arg0: Vec4d) -> float: pass @typing.overload def Normalize(arg0: Vec4f) -> float: pass @typing.overload def Normalize(arg0: Vec4h) -> float: pass @typing.overload def Normalize(arg0: Vec4i) -> float: pass def RadiansToDegrees(arg0: float) -> float: pass @typing.overload def Slerp(alpha: float, v1: Vec2d, v2: Vec2d) -> Vec2d: pass @typing.overload def Slerp(alpha: float, v1: Vec2f, v2: Vec2f) -> Vec2f: pass @typing.overload def Slerp(alpha: float, v1: Vec2h, v2: Vec2h) -> Vec2h: pass @typing.overload def Slerp(alpha: float, v1: Vec2i, v2: Vec2i) -> Vec2i: pass @typing.overload def Slerp(alpha: float, v1: Vec3d, v2: Vec3d) -> Vec3d: pass @typing.overload def Slerp(alpha: float, v1: Vec3f, v2: Vec3f) -> Vec3f: pass @typing.overload def Slerp(alpha: float, v1: Vec3h, v2: Vec3h) -> Vec3h: pass @typing.overload def Slerp(alpha: float, v1: Vec3i, v2: Vec3i) -> Vec3i: pass @typing.overload def Slerp(alpha: float, v1: Vec4d, v2: Vec4d) -> Vec4d: pass @typing.overload def Slerp(alpha: float, v1: Vec4f, v2: Vec4f) -> Vec4f: pass @typing.overload def Slerp(alpha: float, v1: Vec4h, v2: Vec4h) -> Vec4h: pass @typing.overload def Slerp(alpha: float, v1: Vec4i, v2: Vec4i) -> Vec4i: pass @typing.overload def Slerp(arg0: float, arg1: Quatd, arg2: Quatd) -> Quatd: pass @typing.overload def Slerp(arg0: float, arg1: Quatf, arg2: Quatf) -> Quatf: pass @typing.overload def Slerp(arg0: float, arg1: Quath, arg2: Quath) -> Quath: pass
88,849
unknown
33.371373
249
0.565758
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/testGfRect.py
#!/pxrpythonsubst # # Copyright 2016 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. # # Note: This is just pulled directly from USD and modified. # https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfRect2i.py from __future__ import division import math import sys import unittest 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 except ImportError: TestClass = unittest.TestCase from usdrt import Gf class TestGfRect2i(TestClass): def test_Constructor(self): self.assertIsInstance(Gf.Rect2i(), Gf.Rect2i) self.assertIsInstance(Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i()), Gf.Rect2i) self.assertIsInstance(Gf.Rect2i(Gf.Vec2i(), 1, 1), Gf.Rect2i) self.assertTrue(Gf.Rect2i().IsNull()) self.assertTrue(Gf.Rect2i().IsEmpty()) self.assertFalse(Gf.Rect2i().IsValid()) # further test of above. r = Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i(-1, 0)) self.assertTrue(not r.IsNull() and r.IsEmpty()) self.assertEqual( Gf.Rect2i(Gf.Vec2i(-1, 1), Gf.Vec2i(1, -1)).GetNormalized(), Gf.Rect2i(Gf.Vec2i(-1, -1), Gf.Vec2i(1, 1)) ) def test_Properties(self): r = Gf.Rect2i() r.max = Gf.Vec2i() r.min = Gf.Vec2i(1, 1) r.GetNormalized() r.max = Gf.Vec2i(1, 1) r.min = Gf.Vec2i() r.GetNormalized() r.min = Gf.Vec2i(3, 1) self.assertEqual(r.min, Gf.Vec2i(3, 1)) r.max = Gf.Vec2i(4, 5) self.assertEqual(r.max, Gf.Vec2i(4, 5)) r.minX = 10 self.assertEqual(r.minX, 10) r.maxX = 20 self.assertEqual(r.maxX, 20) r.minY = 30 self.assertEqual(r.minY, 30) r.maxY = 40 self.assertEqual(r.maxY, 40) r = Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i(10, 10)) self.assertEqual(r.GetCenter(), Gf.Vec2i(5, 5)) self.assertEqual(r.GetArea(), 121) self.assertEqual(r.GetHeight(), 11) self.assertEqual(r.GetWidth(), 11) self.assertEqual(r.GetSize(), Gf.Vec2i(11, 11)) r.Translate(Gf.Vec2i(10, 10)) self.assertEqual(r, Gf.Rect2i(Gf.Vec2i(10, 10), Gf.Vec2i(20, 20))) r1 = Gf.Rect2i() r2 = Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i(1, 1)) r1.GetIntersection(r2) r2.GetIntersection(r1) r1.GetIntersection(r1) r1.GetUnion(r2) r2.GetUnion(r1) r1.GetUnion(r1) r1 = Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(10, 10)) r2 = Gf.Rect2i(Gf.Vec2i(5, 5), Gf.Vec2i(15, 15)) self.assertEqual(r1.GetIntersection(r2), Gf.Rect2i(Gf.Vec2i(5, 5), Gf.Vec2i(10, 10))) self.assertEqual(r1.GetUnion(r2), Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(15, 15))) tmp = Gf.Rect2i(r1) tmp += r2 self.assertEqual(tmp, Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(15, 15))) self.assertTrue(r1.Contains(Gf.Vec2i(3, 3)) and not r1.Contains(Gf.Vec2i(11, 11))) self.assertEqual(r1, Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(10, 10))) self.assertTrue(r1 != r2) self.assertEqual(r1, eval(repr(r1))) self.assertTrue(len(str(Gf.Rect2i()))) if __name__ == "__main__": unittest.main()
4,475
Python
29.657534
116
0.631732
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/test_gf_quat_extras.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.kit.test import copy import math import os import platform import sys import time import unittest from . import TestRtScenegraph, tc_logger, update_path_and_load_usd def setUpModule(): # pre-load USD before anything else to prevent crash # from weird carb conflict # FIXME ^^^ update_path_and_load_usd() def get_quat_info(): """Return list of tuples of class, scalar size, and format string""" from usdrt import Gf quat_info = [ (Gf.Quatd, 8, "d"), (Gf.Quatf, 4, "f"), (Gf.Quath, 2, "e"), ] return quat_info def get_quat_numpy_types(): import numpy import usdrt equivalent_types = { usdrt.Gf.Quatd: numpy.double, usdrt.Gf.Quatf: numpy.single, usdrt.Gf.Quath: numpy.half, } return equivalent_types class TestGfQuatBuffer(TestRtScenegraph): """Test buffer protocol for usdrt.Gf.Quat* classes""" @tc_logger def test_buffer_inspect(self): """Use memoryview to validate that buffer protocol is implemented""" quat_info = get_quat_info() test_values = [9, 8, 7, 1] for Quat, size, fmt in quat_info: q = Quat(test_values[3], test_values[0], test_values[1], test_values[2]) view = memoryview(q) self.assertEquals(view.itemsize, size) self.assertEquals(view.ndim, 1) self.assertEquals(view.shape, (4,)) self.assertEquals(view.format, fmt) self.assertEquals(view.obj, Quat(test_values[3], test_values[0], test_values[1], test_values[2])) @tc_logger def test_buffer_init(self): """Validate initialization from an array using buffer protocol""" import array quat_info = get_quat_info() test_values = [9, 8, 7, 1] for Quat, size, fmt in quat_info: if fmt == "e": # GfHalf not supported with array.array continue test_array = array.array(fmt, test_values) test_quat = Quat(test_array) self.assertEquals(test_quat, Quat(test_values[3], test_values[0], test_values[1], test_values[2])) @tc_logger def test_buffer_init_from_numpy_type(self): """Test initialization from numpy types""" import numpy quat_info = get_quat_info() equivalent_types = get_quat_numpy_types() test_values = [9, 8, 7, 1] for Quat, size, fmt in quat_info: test_numpy_type = numpy.array(test_values, dtype=equivalent_types[Quat]) test_quat = Quat(test_numpy_type) self.assertEquals(test_quat, Quat(test_values[3], test_values[0], test_values[1], test_values[2])) @tc_logger def test_buffer_init_wrong_type(self): """Verify that an exception is raised with initializing via buffer with different data type""" import array quat_info = get_quat_info() test_values = [9, 8, 7, 1] for Quat, size, fmt in quat_info: test_array = array.array("h", test_values) with self.assertRaises(ValueError): test_quat = Quat(test_array) @tc_logger def test_buffer_init_wrong_size(self): """Verify that an exception is raised with initializing via buffer with different data array length""" import array quat_info = get_quat_info() test_values = [9, 8, 7, 6, 1] for Quat, size, fmt in quat_info: if fmt == "e": # GfHalf not supported with array.array continue test_array = array.array(fmt, test_values) with self.assertRaises(ValueError): test_vec = Quat(test_array) @tc_logger def test_buffer_init_wrong_dimension(self): """Verify that an exception is raised with initializing via buffer with different data dimensions""" import numpy quat_info = get_quat_info() equivalent_types = get_quat_numpy_types() test_values = [9, 8, 7, 1] for Quat, size, fmt in quat_info: test_array = numpy.array([test_values, test_values], dtype=equivalent_types[Quat]) with self.assertRaises(ValueError): test_quat = Quat(test_array) class TestGfQuatGetSetItem(TestRtScenegraph): """Test item accessors for usdrt.Gf.Quat* classes""" @tc_logger def test_get_item(self): """Validate __getitem__ on GfQuat""" from usdrt import Gf for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]: q = Quat(0.5, 1, 2, 3) # Note that these are in memory layout order, # which is different from constructor order self.assertEqual(q[0], 1) self.assertEqual(q[1], 2) self.assertEqual(q[2], 3) self.assertEqual(q[3], 0.5) self.assertEqual(q[-4], 1) self.assertEqual(q[-3], 2) self.assertEqual(q[-2], 3) self.assertEqual(q[-1], 0.5) @tc_logger def test_set_item(self): """Validate __setitem__ on GfQuat""" from usdrt import Gf for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]: q = Quat() self.assertEqual(q.imaginary[0], 0) self.assertEqual(q.imaginary[1], 0) self.assertEqual(q.imaginary[2], 0) self.assertEqual(q.real, 0) q[0] = 1 q[1] = 2 q[2] = 3 q[3] = 0.5 self.assertEqual(q.imaginary[0], 1) self.assertEqual(q.imaginary[1], 2) self.assertEqual(q.imaginary[2], 3) self.assertEqual(q.real, 0.5) @tc_logger def test_get_item_slice(self): """Validate __getitem__ with a slice on GfQuat""" from usdrt import Gf for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]: q = Quat(0.5, 1, 2, 3) self.assertEqual(q[1:], [2, 3, 0.5]) @tc_logger def test_set_item_slice(self): """Validate __setitem__ with a slice on GfQuat""" from usdrt import Gf for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]: q = Quat(0.5, 1, 2, 3) self.assertEqual(q.imaginary[0], 1) self.assertEqual(q.imaginary[1], 2) self.assertEqual(q.imaginary[2], 3) self.assertEqual(q.real, 0.5) q[1:] = [5, 6, 7] self.assertEqual(q.imaginary[0], 1) self.assertEqual(q.imaginary[1], 5) self.assertEqual(q.imaginary[2], 6) self.assertEqual(q.real, 7) class TestGfQuatCopy(TestRtScenegraph): """Test copy and deepcopy support for Gf.Quat* classes""" @tc_logger def test_copy(self): """Test __copy__""" quat_info = get_quat_info() for Quat, size, fmt in quat_info: x = Quat() y = x self.assertTrue(y is x) y[0] = 10 self.assertEqual(x[0], 10) z = copy.copy(y) self.assertFalse(z is y) y[0] = 100 self.assertEqual(z[0], 10) @tc_logger def test_deepcopy(self): """Test __deepcopy__""" quat_info = get_quat_info() for Quat, size, fmt in quat_info: x = Quat() y = x self.assertTrue(y is x) y[0] = 10 self.assertEqual(x[0], 10) z = copy.deepcopy(y) self.assertFalse(z is y) y[0] = 100 self.assertEqual(z[0], 10) class TestGfQuatDebugging(TestRtScenegraph): """Test human readable output functions for debugging""" @tc_logger def test_repr_representation(self): """Test __repr__""" from usdrt import Gf test_quat = Gf.Quatf(0.5, 1, 2, 3) expected = "Gf.Quatf(0.5, Gf.Vec3f(1.0, 2.0, 3.0))" self.assertEqual(repr(test_quat), expected)
8,350
Python
27.796552
110
0.572455
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/testGfVec.py
# Copyright 2016 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. # # Note: This is just pulled directly from USD and lightly modified # https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfVec.py from __future__ import division __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 platform import sys import time import unittest ##### Uncomment for better assert messages # if 'unittest.util' in __import__('sys').modules: # # Show full diff in self.assertEqual. # __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999 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 except ImportError: TestClass = unittest.TestCase import math import sys import unittest def floatTypeRank(vec): from usdrt import Gf vecIntTypes = [Gf.Vec2i, Gf.Vec3i, Gf.Vec4i] vecDoubleTypes = [Gf.Vec2d, Gf.Vec3d, Gf.Vec4d] vecFloatTypes = [Gf.Vec2f, Gf.Vec3f, Gf.Vec4f] vecHalfTypes = [Gf.Vec2h, Gf.Vec3h, Gf.Vec4h] if vec in vecDoubleTypes: return 3 elif vec in vecFloatTypes: return 2 elif vec in vecHalfTypes: return 1 def isFloatingPoint(vec): from usdrt import Gf vecIntTypes = [Gf.Vec2i, Gf.Vec3i, Gf.Vec4i] vecDoubleTypes = [Gf.Vec2d, Gf.Vec3d, Gf.Vec4d] vecFloatTypes = [Gf.Vec2f, Gf.Vec3f, Gf.Vec4f] vecHalfTypes = [Gf.Vec2h, Gf.Vec3h, Gf.Vec4h] return (vec in vecDoubleTypes) or (vec in vecFloatTypes) or (vec in vecHalfTypes) def getEps(vec): rank = floatTypeRank(vec) if rank == 1: return 1e-2 elif rank == 2: return 1e-3 elif rank == 3: return 1e-4 def vecWithType(vecType, type): from usdrt import Gf if vecType.dimension == 2: if type == "d": return Gf.Vec2d elif type == "f": return Gf.Vec2f elif type == "h": return Gf.Vec2h elif type == "i": return Gf.Vec2i elif vecType.dimension == 3: if type == "d": return Gf.Vec3d elif type == "f": return Gf.Vec3f elif type == "h": return Gf.Vec3h elif type == "i": return Gf.Vec3i elif vecType.dimension == 4: if type == "d": return Gf.Vec4d elif type == "f": return Gf.Vec4f elif type == "h": return Gf.Vec4h elif type == "i": return Gf.Vec4i assert False, "No valid conversion for " + vecType + " to type " + type return None def checkVec(vec, values): for i in range(len(vec)): if vec[i] != values[i]: return False return True def checkVecDot(v1, v2, dp): if len(v1) != len(v2): return False checkdp = 0 for i in range(len(v1)): checkdp += v1[i] * v2[i] return checkdp == dp def SetVec(vec, values): for i in range(len(vec)): vec[i] = values[i] class TestGfVec(TestClass): def ConstructorsTest(self, Vec): # no arg constructor self.assertIsInstance(Vec(), Vec) # default constructor v = Vec() for x in v: self.assertEqual(0, x) # copy constructor v = Vec() for i in range(len(v)): v[i] = i v2 = Vec(v) for i in range(len(v2)): self.assertEqual(v[i], v2[i]) # explicit constructor values = [3, 1, 4, 1] if Vec.dimension == 2: v = Vec(3, 1) self.assertTrue(checkVec(v, values)) elif Vec.dimension == 3: v = Vec(3, 1, 4) self.assertTrue(checkVec(v, values)) elif Vec.dimension == 4: v = Vec(3, 1, 4, 1) self.assertTrue(checkVec(v, values)) else: self.assertTrue(False, "No explicit constructor check for " + Vec) # constructor taking single scalar value. v = Vec(0) self.assertTrue(all([x == 0 for x in v])) v = Vec(1) self.assertTrue(all([x == 1 for x in v])) v = Vec(2) self.assertTrue(all([x == 2 for x in v])) # conversion from other types to this float type. if isFloatingPoint(Vec): for t in "dfih": V = vecWithType(Vec, t) self.assertTrue(Vec(V())) # comparison to int type Veci = vecWithType(Vec, "i") vi = Veci() SetVec(vi, (3, 1, 4, 1)) self.assertEqual(Vec(vi), vi) if isFloatingPoint(Vec): # Comparison to float type for t in "dfh": V = vecWithType(Vec, t) v = V() SetVec(v, (0.3, 0.1, 0.4, 0.1)) if floatTypeRank(Vec) >= floatTypeRank(V): self.assertEqual(Vec(v), v) else: self.assertNotEqual(Vec(v), v) def OperatorsTest(self, Vec): from usdrt import Gf v1 = Vec() v2 = Vec() # equality SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [3, 1, 4, 1]) self.assertEqual(v1, v2) # inequality SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [5, 9, 2, 6]) self.assertNotEqual(v1, v2) # component-wise addition SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [5, 9, 2, 6]) v3 = v1 + v2 v1 += v2 self.assertTrue(checkVec(v1, [8, 10, 6, 7])) self.assertTrue(checkVec(v3, [8, 10, 6, 7])) # component-wise subtraction SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [5, 9, 2, 6]) v3 = v1 - v2 v1 -= v2 self.assertTrue(checkVec(v1, [-2, -8, 2, -5])) self.assertTrue(checkVec(v3, [-2, -8, 2, -5])) # component-wise multiplication SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [5, 9, 2, 6]) v4 = v1 * 10 v5 = 10 * v1 v1 *= 10 self.assertTrue(checkVec(v1, [30, 10, 40, 10])) self.assertTrue(checkVec(v4, [30, 10, 40, 10])) self.assertTrue(checkVec(v5, [30, 10, 40, 10])) # component-wise division SetVec(v1, [3, 6, 9, 12]) v3 = v1 / 3 v1 /= 3 self.assertTrue(checkVec(v1, [1, 2, 3, 4])) self.assertTrue(checkVec(v3, [1, 2, 3, 4])) # dot product SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [5, 9, 2, 6]) dp = v1 * v2 dp2 = Gf.Dot(v1, v2) dp3 = v1.GetDot(v2) # 2x compatibility self.assertTrue(checkVecDot(v1, v2, dp)) self.assertTrue(checkVecDot(v1, v2, dp2)) self.assertTrue(checkVecDot(v1, v2, dp3)) # unary minus (negation) SetVec(v1, [3, 1, 4, 1]) self.assertTrue(checkVec(-v1, [-3, -1, -4, -1])) # repr self.assertEqual(v1, eval(repr(v1))) # string self.assertTrue(len(str(Vec())) > 0) # indexing v = Vec() for i in range(Vec.dimension): v[i] = i + 1 self.assertEqual(v[-1], v[v.dimension - 1]) self.assertEqual(v[0], 1) self.assertIn(v.dimension, v) self.assertNotIn(v.dimension + 1, v) with self.assertRaises(IndexError): v[v.dimension + 1] = v.dimension + 1 # slicing v = Vec() value = [3, 1, 4, 1] SetVec(v, value) value = v[0 : v.dimension] self.assertEqual(v[:], value) self.assertEqual(v[:2], value[:2]) self.assertEqual(v[0:2], value[0:2]) self.assertEqual(v[-2:], value[-2:]) self.assertEqual(v[1:1], []) if v.dimension > 2: self.assertEqual(v[0:3:2], [3, 4]) v[:2] = (8, 9) checkVec(v, [8, 9, 4, 1]) if v.dimension > 2: v[:3:2] = [0, 1] checkVec(v, [0, 9, 1, 1]) with self.assertRaises(ValueError): # This should fail. Wrong length sequence # v[:2] = [1, 2, 3] with self.assertRaises(TypeError): # This should fail. Cannot use floats for indices v[0.0:2.0] = [7, 7] with self.assertRaises(TypeError): # This should fail. Cannot convert None to vector data # v[:2] = [None, None] def MethodsTest(self, Vec): from usdrt import Gf v1 = Vec() v2 = Vec() if isFloatingPoint(Vec): eps = getEps(Vec) # length SetVec(v1, [3, 1, 4, 1]) l = Gf.GetLength(v1) l2 = v1.GetLength() self.assertTrue(Gf.IsClose(l, l2, eps), repr(l) + " " + repr(l2)) self.assertTrue( Gf.IsClose(l, math.sqrt(Gf.Dot(v1, v1)), eps), " ".join([repr(x) for x in [l, v1, math.sqrt(Gf.Dot(v1, v1))]]), ) # Normalize... SetVec(v1, [3, 1, 4, 1]) v2 = Vec(v1) v2.Normalize() nv = Gf.GetNormalized(v1) nv2 = v1.GetNormalized() nvcheck = v1 / Gf.GetLength(v1) self.assertTrue(Gf.IsClose(nv, nvcheck, eps)) self.assertTrue(Gf.IsClose(nv2, nvcheck, eps)) self.assertTrue(Gf.IsClose(v2, nvcheck, eps)) SetVec(v1, [3, 1, 4, 1]) nv = v1.GetNormalized() nvcheck = v1 / Gf.GetLength(v1) self.assertTrue(Gf.IsClose(nv, nvcheck, eps)) # nv edit - linalg implementation not exactly equal SetVec(v1, [0, 0, 0, 0]) v1.Normalize() self.assertTrue(checkVec(v1, [0, 0, 0, 0])) SetVec(v1, [2, 0, 0, 0]) Gf.Normalize(v1) self.assertTrue(checkVec(v1, [1, 0, 0, 0])) # projection SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [5, 9, 2, 6]) p1 = Gf.GetProjection(v1, v2) p2 = v1.GetProjection(v2) check = (v1 * v2) * v2 self.assertEqual(p1, check) self.assertEqual(p2, check) # complement SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [5, 9, 2, 6]) p1 = Gf.GetComplement(v1, v2) p2 = v1.GetComplement(v2) check = v1 - (v1 * v2) * v2 self.assertTrue((p1 == check) and (p2 == check)) # component-wise multiplication SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [5, 9, 2, 6]) v3 = Gf.CompMult(v1, v2) self.assertTrue(checkVec(v3, [15, 9, 8, 6])) # component-wise division SetVec(v1, [3, 9, 18, 21]) SetVec(v2, [3, 3, 9, 7]) v3 = Gf.CompDiv(v1, v2) self.assertTrue(checkVec(v3, [1, 3, 2, 3])) # is close SetVec(v1, [3, 1, 4, 1]) SetVec(v2, [5, 9, 2, 6]) self.assertTrue(Gf.IsClose(v1, v1, 0.1)) self.assertFalse(Gf.IsClose(v1, v2, 0.1)) # static Axis methods for i in range(Vec.dimension): v1 = Vec.Axis(i) v2 = Vec() v2[i] = 1 self.assertEqual(v1, v2) v1 = Vec.XAxis() self.assertTrue(checkVec(v1, [1, 0, 0, 0])) v1 = Vec.YAxis() self.assertTrue(checkVec(v1, [0, 1, 0, 0])) if Vec.dimension != 2: v1 = Vec.ZAxis() self.assertTrue(checkVec(v1, [0, 0, 1, 0])) if Vec.dimension == 3: # cross product SetVec(v1, [3, 1, 4, 0]) SetVec(v2, [5, 9, 2, 0]) v3 = Vec(Gf.Cross(v1, v2)) v4 = v1 ^ v2 v5 = v1.GetCross(v2) # 2x compatibility check = Vec() SetVec(check, [1 * 2 - 4 * 9, 4 * 5 - 3 * 2, 3 * 9 - 1 * 5, 0]) self.assertTrue(v3 == check and v4 == check and v5 == check) # orthogonalize basis # case 1: close to orthogonal, don't normalize SetVec(v1, [1, 0, 0.1]) SetVec(v2, [0.1, 1, 0]) SetVec(v3, [0, 0.1, 1]) self.assertTrue(Vec.OrthogonalizeBasis(v1, v2, v3, False)) self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps)) # case 2: far from orthogonal, normalize SetVec(v1, [1, 2, 3]) SetVec(v2, [-1, 2, 3]) SetVec(v3, [-1, -2, 3]) self.assertTrue(Vec.OrthogonalizeBasis(v1, v2, v3, True)) self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps)) self.assertTrue(Gf.IsClose(v1.GetLength(), 1, eps)) self.assertTrue(Gf.IsClose(v2.GetLength(), 1, eps)) self.assertTrue(Gf.IsClose(v3.GetLength(), 1, eps)) # case 3: already orthogonal - shouldn't change, even with large # tolerance SetVec(v1, [1, 0, 0]) SetVec(v2, [0, 1, 0]) SetVec(v3, [0, 0, 1]) vt1 = v1 vt2 = v2 vt3 = v3 self.assertTrue(Vec.OrthogonalizeBasis(v1, v2, v3, False)) # nv edit - no epsilon parameter self.assertTrue(v1 == vt1) self.assertTrue(v2 == vt2) self.assertTrue(v3 == vt3) # case 4: co-linear input vectors - should do nothing SetVec(v1, [1, 0, 0]) SetVec(v2, [1, 0, 0]) SetVec(v3, [0, 0, 1]) vt1 = v1 vt2 = v2 vt3 = v3 self.assertFalse(Vec.OrthogonalizeBasis(v1, v2, v3, False)) # nv edit - no epsilon parameter self.assertEqual(v1, vt1) self.assertEqual(v2, vt2) self.assertEqual(v3, vt3) # build orthonormal frame SetVec(v1, [1, 1, 1, 1]) (v2, v3) = v1.BuildOrthonormalFrame() self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps)) SetVec(v1, [0, 0, 0, 0]) (v2, v3) = v1.BuildOrthonormalFrame() self.assertTrue(Gf.IsClose(v2, Vec(), eps)) self.assertTrue(Gf.IsClose(v3, Vec(), eps)) SetVec(v1, [1, 0, 0, 0]) (v2, v3) = v1.BuildOrthonormalFrame() self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps)) SetVec(v1, [1, 0, 0, 0]) (v2, v3) = v1.BuildOrthonormalFrame() self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps)) SetVec(v1, [1, 0, 0, 0]) (v2, v3) = v1.BuildOrthonormalFrame(2) self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps)) self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps)) # test Slerp w/ orthogonal vectors SetVec(v1, [1, 0, 0]) SetVec(v2, [0, 1, 0]) v3 = Gf.Slerp(0, v1, v2) self.assertTrue(Gf.IsClose(v3, v1, eps)) v3 = Gf.Slerp(1, v1, v2) self.assertTrue(Gf.IsClose(v3, v3, eps)) v3 = Gf.Slerp(0.5, v1, v2) self.assertTrue(Gf.IsClose(v3, Vec(0.7071, 0.7071, 0), eps)) # test Slerp w/ nearly parallel vectors SetVec(v1, [1, 0, 0]) SetVec(v2, [1.001, 0.0001, 0]) v2.Normalize() v3 = Gf.Slerp(0, v1, v2) self.assertTrue(Gf.IsClose(v3, v1, eps)) v3 = Gf.Slerp(1, v1, v2) self.assertTrue(Gf.IsClose(v3, v3, eps)) v3 = Gf.Slerp(0.5, v1, v2) self.assertTrue(Gf.IsClose(v3, v1, eps), [v3, v1, eps]) self.assertTrue(Gf.IsClose(v3, v2, eps)) # test Slerp w/ opposing vectors SetVec(v1, [1, 0, 0]) SetVec(v2, [-1, 0, 0]) v3 = Gf.Slerp(0, v1, v2) self.assertTrue(Gf.IsClose(v3, v1, eps)) v3 = Gf.Slerp(0.25, v1, v2) self.assertTrue(Gf.IsClose(v3, Vec(0.70711, 0, -0.70711), eps)) v3 = Gf.Slerp(0.5, v1, v2) self.assertTrue(Gf.IsClose(v3, Vec(0, 0, -1), eps)) v3 = Gf.Slerp(0.75, v1, v2) self.assertTrue(Gf.IsClose(v3, Vec(-0.70711, 0, -0.70711), eps)) v3 = Gf.Slerp(1, v1, v2) self.assertTrue(Gf.IsClose(v3, v3, eps)) # test Slerp w/ opposing vectors SetVec(v1, [0, 1, 0]) SetVec(v2, [0, -1, 0]) v3 = Gf.Slerp(0, v1, v2) self.assertTrue(Gf.IsClose(v3, v1, eps)) v3 = Gf.Slerp(0.25, v1, v2) self.assertTrue(Gf.IsClose(v3, Vec(0, 0.70711, 0.70711), eps)) v3 = Gf.Slerp(0.5, v1, v2) self.assertTrue(Gf.IsClose(v3, Vec(0, 0, 1), eps)) v3 = Gf.Slerp(0.75, v1, v2) self.assertTrue(Gf.IsClose(v3, Vec(0, -0.70711, 0.70711), eps)) v3 = Gf.Slerp(1, v1, v2) self.assertTrue(Gf.IsClose(v3, v3, eps)) def test_Types(self): from usdrt import Gf vecTypes = [ Gf.Vec2d, Gf.Vec2f, Gf.Vec2h, Gf.Vec2i, Gf.Vec3d, Gf.Vec3f, Gf.Vec3h, Gf.Vec3i, Gf.Vec4d, Gf.Vec4f, Gf.Vec4h, Gf.Vec4i, ] for Vec in vecTypes: self.ConstructorsTest(Vec) self.OperatorsTest(Vec) self.MethodsTest(Vec) def test_TupleToVec(self): from usdrt import Gf # Test passing tuples for vecs. self.assertEqual(Gf.Dot((1, 1), (1, 1)), 2) self.assertEqual(Gf.Dot((1, 1, 1), (1, 1, 1)), 3) self.assertEqual(Gf.Dot((1, 1, 1, 1), (1, 1, 1, 1)), 4) self.assertEqual(Gf.Dot((1.0,1.0), (1.0,1.0)), 2.0) self.assertEqual(Gf.Dot((1.0,1.0,1.0), (1.0,1.0,1.0)), 3.0) self.assertEqual(Gf.Dot((1.0,1.0,1.0,1.0), (1.0,1.0,1.0,1.0)), 4.0) self.assertEqual(Gf.Vec2f((1, 1)), Gf.Vec2f(1, 1)) self.assertEqual(Gf.Vec3f((1, 1, 1)), Gf.Vec3f(1, 1, 1)) self.assertEqual(Gf.Vec4f((1, 1, 1, 1)), Gf.Vec4f(1, 1, 1, 1)) # Test passing lists for vecs. self.assertEqual(Gf.Dot([1, 1], [1, 1]), 2) self.assertEqual(Gf.Dot([1, 1, 1], [1, 1, 1]), 3) self.assertEqual(Gf.Dot([1, 1, 1, 1], [1, 1, 1, 1]), 4) self.assertEqual(Gf.Dot([1.0, 1.0], [1.0, 1.0]), 2.0) self.assertEqual(Gf.Dot([1.0, 1.0, 1.0], [1.0, 1.0, 1.0]), 3.0) self.assertEqual(Gf.Dot([1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]), 4.0) self.assertEqual(Gf.Vec2f([1, 1]), Gf.Vec2f(1, 1)) self.assertEqual(Gf.Vec3f([1, 1, 1]), Gf.Vec3f(1, 1, 1)) self.assertEqual(Gf.Vec4f([1, 1, 1, 1]), Gf.Vec4f(1, 1, 1, 1)) # Test passing both for vecs. self.assertEqual(Gf.Dot((1,1), [1,1]), 2) self.assertEqual(Gf.Dot((1, 1, 1), (1, 1, 1)), 3) self.assertEqual(Gf.Dot((1,1,1,1), [1,1,1,1]), 4) self.assertEqual(Gf.Dot((1.0,1.0), [1.0,1.0]), 2.0) self.assertEqual(Gf.Dot((1.0,1.0,1.0), [1.0,1.0,1.0]), 3.0) self.assertEqual(Gf.Dot((1.0,1.0,1.0,1.0), [1.0,1.0,1.0,1.0]), 4.0) self.assertEqual(Gf.Vec2f([1,1]), Gf.Vec2f(1,1)) self.assertEqual(Gf.Vec3f([1,1,1]), Gf.Vec3f(1,1,1)) self.assertEqual(Gf.Vec4f([1,1,1,1]), Gf.Vec4f(1,1,1,1)) def test_Exceptions(self): from usdrt import Gf with self.assertRaises(TypeError): Gf.Dot("monkey", (1, 1)) with self.assertRaises(TypeError): Gf.Dot("monkey", (1, 1, 1)) with self.assertRaises(TypeError): Gf.Dot("monkey", (1, 1, 1, 1)) with self.assertRaises(TypeError): Gf.Dot("monkey", (1.0, 1.0)) with self.assertRaises(TypeError): Gf.Dot("monkey", (1.0, 1.0, 1.0)) with self.assertRaises(TypeError): Gf.Dot("monkey", (1.0, 1.0, 1.0, 1.0)) with self.assertRaises(TypeError): Gf.Dot((1, 1, 1, 1, 1, 1), (1, 1)) with self.assertRaises(TypeError): Gf.Dot((1, 1, 1, 1, 1, 1), (1, 1, 1)) with self.assertRaises(TypeError): Gf.Dot((1, 1, 1, 1, 1, 1), (1, 1, 1, 1)) with self.assertRaises(TypeError): Gf.Dot((1.0, 1.0, 1.0, 1.0, 1.0, 1.0), (1.0, 1.0)) with self.assertRaises(TypeError): Gf.Dot((1.0, 1.0, 1.0, 1.0, 1.0, 1.0), (1.0, 1.0, 1.0)) with self.assertRaises(TypeError): Gf.Dot((1.0, 1.0, 1.0, 1.0, 1.0, 1.0), (1.0, 1.0, 1.0, 1.0)) with self.assertRaises(TypeError): Gf.Dot(("a", "b"), (1, 1)) with self.assertRaises(TypeError): Gf.Dot(("a", "b", "c"), (1, 1, 1)) with self.assertRaises(TypeError): Gf.Dot(("a", "b", "c", "d"), (1, 1, 1, 1)) with self.assertRaises(TypeError): Gf.Dot(("a", "b"), (1.0, 1.0)) with self.assertRaises(TypeError): Gf.Dot(("a", "b", "c"), (1.0, 1.0, 1.0)) with self.assertRaises(TypeError): Gf.Dot(("a", "b", "c", "d"), (1.0, 1.0, 1.0, 1.0))
23,665
Python
33.002874
110
0.503697
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/test_gf_vec_extras.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.kit.test import copy import math import os import platform import sys import time import unittest from . import TestRtScenegraph, tc_logger, update_path_and_load_usd def setUpModule(): # pre-load USD before anything else to prevent crash # from weird carb conflict # FIXME ^^^ update_path_and_load_usd() def get_vec_info(): """Return list of tuples of class, scalar size, item count, and format string""" from usdrt import Gf vec_info = [ (Gf.Vec2d, 8, 2, "d"), (Gf.Vec2f, 4, 2, "f"), (Gf.Vec2h, 2, 2, "e"), (Gf.Vec2i, 4, 2, "i"), (Gf.Vec3d, 8, 3, "d"), (Gf.Vec3f, 4, 3, "f"), (Gf.Vec3h, 2, 3, "e"), (Gf.Vec3i, 4, 3, "i"), (Gf.Vec4d, 8, 4, "d"), (Gf.Vec4f, 4, 4, "f"), (Gf.Vec4h, 2, 4, "e"), (Gf.Vec4i, 4, 4, "i"), ] return vec_info def get_vec_numpy_types(): import numpy import usdrt equivalent_types = { usdrt.Gf.Vec2d: numpy.double, usdrt.Gf.Vec2f: numpy.single, usdrt.Gf.Vec2h: numpy.half, usdrt.Gf.Vec2i: numpy.int, usdrt.Gf.Vec3d: numpy.double, usdrt.Gf.Vec3f: numpy.single, usdrt.Gf.Vec3h: numpy.half, usdrt.Gf.Vec3i: numpy.int, usdrt.Gf.Vec4d: numpy.double, usdrt.Gf.Vec4f: numpy.single, usdrt.Gf.Vec4h: numpy.half, usdrt.Gf.Vec4i: numpy.int, } return equivalent_types class TestGfVecBuffer(TestRtScenegraph): """Test buffer protocol for usdrt.Gf.Vec* classes""" @tc_logger def test_buffer_inspect(self): """Use memoryview to validate that buffer protocol is implemented""" vec_info = get_vec_info() test_values = [9, 8, 7, 6] for Vec, size, count, fmt in vec_info: v = Vec(*test_values[:count]) view = memoryview(v) self.assertEquals(view.itemsize, size) self.assertEquals(view.ndim, 1) self.assertEquals(view.shape, (count,)) self.assertEquals(view.format, fmt) self.assertEquals(view.obj, Vec(*test_values[:count])) @tc_logger def test_buffer_init(self): """Validate initialization from an array using buffer protocol""" import array vec_info = get_vec_info() test_values = [9, 8, 7, 6] for Vec, size, count, fmt in vec_info: if fmt == "e": # GfHalf not supported with array.array continue test_array = array.array(fmt, test_values[:count]) test_vec = Vec(test_array) self.assertEquals(test_vec, Vec(*test_values[:count])) @tc_logger def test_buffer_init_from_pxr_type(self): """Validate initialization from equivalent Pixar types""" import pxr.Gf import usdrt vec_info = get_vec_info() equivalent_types = { usdrt.Gf.Vec2d: pxr.Gf.Vec2d, usdrt.Gf.Vec2f: pxr.Gf.Vec2f, usdrt.Gf.Vec2h: pxr.Gf.Vec2h, usdrt.Gf.Vec2i: pxr.Gf.Vec2i, usdrt.Gf.Vec3d: pxr.Gf.Vec3d, usdrt.Gf.Vec3f: pxr.Gf.Vec3f, usdrt.Gf.Vec3h: pxr.Gf.Vec3h, usdrt.Gf.Vec3i: pxr.Gf.Vec3i, usdrt.Gf.Vec4d: pxr.Gf.Vec4d, usdrt.Gf.Vec4f: pxr.Gf.Vec4f, usdrt.Gf.Vec4h: pxr.Gf.Vec4h, usdrt.Gf.Vec4i: pxr.Gf.Vec4i, } test_values = [9, 8, 7, 6] for Vec, size, count, fmt in vec_info: test_pxr_type = equivalent_types[Vec](test_values[:count]) # Note that in all cases pybind choses the tuple initializer and # not the buffer initializer. Oh well. test_vec = Vec(test_pxr_type) self.assertEquals(test_vec, Vec(*test_values[:count])) @tc_logger def test_buffer_init_from_numpy_type(self): """Test initialization from numpy types""" import numpy vec_info = get_vec_info() equivalent_types = get_vec_numpy_types() test_values = [9, 8, 7, 6] for Vec, size, count, fmt in vec_info: test_numpy_type = numpy.array(test_values[:count], dtype=equivalent_types[Vec]) # Note that in all cases except half pybind choses the tuple initializer and # not the buffer initializer. Oh well. test_vec = Vec(test_numpy_type) self.assertEquals(test_vec, Vec(*test_values[:count])) @tc_logger def test_buffer_init_wrong_type(self): """Verify that an exception is raised with initializing via buffer with different data type""" import array vec_info = get_vec_info() test_values = [9, 8, 7, 6] for Vec, size, count, fmt in vec_info: if fmt in ["e"]: # GfHalf is tricky because it will cast from any # numeric type, which pybind too-helpfully interprets # into a tuple of GfHalf continue # Here, pybind will convert arrays of similar types to tuples # which is fine I guess but makes testing harder to validate # type correctness with buffer support test_array = array.array("d" if fmt == "i" else "h", test_values[:count]) with self.assertRaises(ValueError): test_vec = Vec(test_array) @tc_logger def test_buffer_init_wrong_size(self): """Verify that an exception is raised with initializing via buffer with different data array length""" import array vec_info = get_vec_info() test_values = [9, 8, 7, 6, 5] for Vec, size, count, fmt in vec_info: if fmt in ["e"]: # GfHalf not supported with array.array continue # Here, pybind will convert arrays of similar types to tuples # which is fine I guess but makes testing harder to validate # type correctness with buffer support test_array = array.array(fmt, test_values) with self.assertRaises(ValueError): test_vec = Vec(test_array) @tc_logger def test_buffer_init_wrong_dimension(self): """Verify that an exception is raised with initializing via buffer with different data dimensions""" import numpy vec_info = get_vec_info() equivalent_types = get_vec_numpy_types() test_values = [9, 8, 7, 6] for Vec, size, count, fmt in vec_info: test_array = numpy.array([test_values[:count], test_values[:count]], dtype=equivalent_types[Vec]) with self.assertRaises(ValueError): test_vec = Vec(test_array) class TestGfVecCopy(TestRtScenegraph): """Test copy and deepcopy support for Gf.Vec* classes""" @tc_logger def test_copy(self): """Test __copy__""" vec_info = get_vec_info() for Vec, size, count, fmt in vec_info: x = Vec() y = x self.assertTrue(y is x) y[0] = 10 self.assertEqual(x[0], 10) z = copy.copy(y) self.assertFalse(z is y) y[0] = 100 self.assertEqual(z[0], 10) @tc_logger def test_deepcopy(self): """Test __deepcopy__""" vec_info = get_vec_info() for Vec, size, count, fmt in vec_info: x = Vec() y = x self.assertTrue(y is x) y[0] = 10 self.assertEqual(x[0], 10) z = copy.deepcopy(y) self.assertFalse(z is y) y[0] = 100 self.assertEqual(z[0], 10) class TestGfVecDebugging(TestRtScenegraph): """Test human readable output functions for debugging""" @tc_logger def test_repr_representation(self): """Test __repr__""" from usdrt import Gf test_values = [9, 8, 7, 6] test_vec = Gf.Vec4d(test_values) expected = "Gf.Vec4d(9.0, 8.0, 7.0, 6.0)" self.assertEqual(repr(test_vec), expected)
8,512
Python
28.975352
110
0.574836
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/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 omni.kit.test TestRtScenegraph = omni.kit.test.AsyncTestCase def tc_logger(func): """ Print TC macros about the test when running on TC (unneeded in kit) """ return func def update_path_and_load_usd(): """ Stub to help load USD before USDRT (unneeded in kit) """ pass from .test_gf_matrix_extras import * from .test_gf_quat_extras import * from .test_gf_range_extras import * from .test_gf_vec_extras import * from .testGfMath import * from .testGfMatrix import * from .testGfQuat import * from .testGfRange import * from .testGfRect import * from .testGfVec import *
1,075
Python
24.023255
78
0.737674
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/testGfMath.py
#!/pxrpythonsubst # # Copyright 2016 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. # from __future__ import division # Note: This is just pulled directly from USD and lightly modified # https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfMath.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 sys import unittest # In python 3 there is no type called "long", but a regular int is backed by # a long. Fake it here so we can keep test coverage working for the types # available in python 2, where there are separate int and long types if sys.version_info.major >= 3: long = int def err(msg): return "ERROR: " + msg + " failed" 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 except ImportError: TestClass = unittest.TestCase class TestGfMath(TestClass): def _AssertListIsClose(self, first, second, delta=1e-6): self.assertTrue(len(first) == len(second)) for (f, s) in zip(first, second): self.assertAlmostEqual(f, s, delta=delta) """ nv edit - no _HalfRoundTrip def test_HalfRoundTrip(self): from pxr.Gf import _HalfRoundTrip self.assertEqual(1.0, _HalfRoundTrip(1.0)) self.assertEqual(1.0, _HalfRoundTrip(1)) self.assertEqual(2.0, _HalfRoundTrip(2)) self.assertEqual(3.0, _HalfRoundTrip(long(3))) with self.assertRaises(TypeError): _HalfRoundTrip([]) """ def test_RadiansDegrees(self): from usdrt.Gf import DegreesToRadians, RadiansToDegrees self.assertEqual(0, RadiansToDegrees(0)) self.assertEqual(180, RadiansToDegrees(math.pi)) self.assertEqual(720, RadiansToDegrees(4 * math.pi)) self.assertEqual(0, DegreesToRadians(0)) self.assertEqual(math.pi, DegreesToRadians(180)) self.assertEqual(8 * math.pi, DegreesToRadians(4 * 360)) """ nv edit - not supporting some basic math stuff for now def test_Sqr(self): self.assertEqual(9, Sqr(3)) self.assertAlmostEqual(Sqr(math.sqrt(2)), 2, delta=1e-7) self.assertEqual(5, Sqr(Vec2i(1,2))) self.assertEqual(14, Sqr(Vec3i(1,2,3))) self.assertEqual(5, Sqr(Vec2d(1,2))) self.assertEqual(14, Sqr(Vec3d(1,2,3))) self.assertEqual(30, Sqr(Vec4d(1,2,3,4))) self.assertEqual(5, Sqr(Vec2f(1,2))) self.assertEqual(14, Sqr(Vec3f(1,2,3))) self.assertEqual(30, Sqr(Vec4f(1,2,3,4))) def test_Sgn(self): self.assertEqual(-1, Sgn(-3)) self.assertEqual(1, Sgn(3)) self.assertEqual(0, Sgn(0)) self.assertEqual(-1, Sgn(-3.3)) self.assertEqual(1, Sgn(3.3)) self.assertEqual(0, Sgn(0.0)) def test_Sqrt(self): self.assertAlmostEqual( Sqrt(2), math.sqrt(2), delta=1e-5 ) self.assertAlmostEqual( Sqrtf(2), math.sqrt(2), delta=1e-5 ) def test_Exp(self): self.assertAlmostEqual( Sqr(math.e), Exp(2), delta=1e-5 ) self.assertAlmostEqual( Sqr(math.e), Expf(2), delta=1e-5 ) def test_Log(self): self.assertEqual(1, Log(math.e)) self.assertAlmostEqual(Log(Exp(math.e)), math.e, delta=1e-5) self.assertAlmostEqual(Logf(math.e), 1, delta=1e-5) self.assertAlmostEqual(Logf(Expf(math.e)), math.e, delta=1e-5) def test_Floor(self): self.assertEqual(3, Floor(3.141)) self.assertEqual(-4, Floor(-3.141)) self.assertEqual(3, Floorf(3.141)) self.assertEqual(-4, Floorf(-3.141)) def test_Ceil(self): self.assertEqual(4, Ceil(3.141)) self.assertEqual(-3, Ceil(-3.141)) self.assertEqual(4, Ceilf(3.141)) self.assertEqual(-3, Ceilf(-3.141)) def test_Abs(self): self.assertAlmostEqual(Abs(-3.141), 3.141, delta=1e-6) self.assertAlmostEqual(Abs(3.141), 3.141, delta=1e-6) self.assertAlmostEqual(Absf(-3.141), 3.141, delta=1e-6) self.assertAlmostEqual(Absf(3.141), 3.141, delta=1e-6) def test_Round(self): self.assertEqual(3, Round(3.1)) self.assertEqual(4, Round(3.5)) self.assertEqual(-3, Round(-3.1)) self.assertEqual(-4, Round(-3.6)) self.assertEqual(3, Roundf(3.1)) self.assertEqual(4, Roundf(3.5)) self.assertEqual(-3, Roundf(-3.1)) self.assertEqual(-4, Roundf(-3.6)) def test_Pow(self): self.assertEqual(16, Pow(2, 4)) self.assertEqual(16, Powf(2, 4)) def test_Clamp(self): self.assertAlmostEqual(Clamp(3.141, 3.1, 3.2), 3.141, delta=1e-5) self.assertAlmostEqual(Clamp(2.141, 3.1, 3.2), 3.1, delta=1e-5) self.assertAlmostEqual(Clamp(4.141, 3.1, 3.2), 3.2, delta=1e-5) self.assertAlmostEqual(Clampf(3.141, 3.1, 3.2), 3.141, delta=1e-5) self.assertAlmostEqual(Clampf(2.141, 3.1, 3.2), 3.1, delta=1e-5) self.assertAlmostEqual(Clampf(4.141, 3.1, 3.2), 3.2, delta=1e-5) def test_Mod(self): self.assertEqual(2, Mod(5, 3)) self.assertEqual(1, Mod(-5, 3)) self.assertEqual(2, Modf(5, 3)) self.assertEqual(1, Modf(-5, 3)) """ """ nv edit - not supporting these for scalars def test_Dot(self): from usdrt.Gf import Dot self.assertEqual(Dot(2.0, 3.0), 6.0) self.assertEqual(Dot(-2.0, 3.0), -6.0) def test_CompMult(self): from usdrt.Gf import CompMult self.assertEqual(CompMult(2.0, 3.0), 6.0) self.assertEqual(CompMult(-2.0, 3.0), -6.0) def test_CompDiv(self): from usdrt.Gf import CompDiv self.assertEqual(CompDiv(6.0, 3.0), 2.0) self.assertEqual(CompDiv(-6.0, 3.0), -2.0) """ if __name__ == "__main__": unittest.main()
7,375
Python
34.805825
93
0.650847
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/test_gf_matrix_extras.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.kit.test import copy import math import os import platform import sys import time import unittest from . import TestRtScenegraph, tc_logger, update_path_and_load_usd def setUpModule(): # pre-load USD before anything else to prevent crash # from weird carb conflict # FIXME ^^^ update_path_and_load_usd() def get_mat_info(): """Return list of tuples of class, scalar size, item count, and format string""" from usdrt import Gf mat_info = [ (Gf.Matrix3d, 8, 9, "d"), (Gf.Matrix3f, 4, 9, "f"), (Gf.Matrix4d, 8, 16, "d"), (Gf.Matrix4f, 4, 16, "f"), ] return mat_info def get_mat_numpy_types(): import numpy import usdrt equivalent_types = { usdrt.Gf.Matrix3d: numpy.double, usdrt.Gf.Matrix3f: numpy.single, usdrt.Gf.Matrix4d: numpy.double, usdrt.Gf.Matrix4f: numpy.single, } return equivalent_types class TestGfMatBuffer(TestRtScenegraph): """Test buffer protocol for usdrt.Gf.Matrix* classes""" @tc_logger def test_buffer_inspect(self): """Use memoryview to validate that buffer protocol is implemented""" mat_info = get_mat_info() test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] for Mat, size, count, fmt in mat_info: v = Mat(*test_values[:count]) view = memoryview(v) self.assertEquals(view.itemsize, size) self.assertEquals(view.ndim, 2) self.assertEquals(view.shape, (math.sqrt(count), math.sqrt(count))) self.assertEquals(view.format, fmt) self.assertEquals(view.obj, Mat(*test_values[:count])) @tc_logger def test_buffer_init_from_pxr_type(self): """Validate initialization from equivalent Pixar types""" import pxr.Gf import usdrt mat_info = get_mat_info() equivalent_types = { usdrt.Gf.Matrix3d: pxr.Gf.Matrix3d, usdrt.Gf.Matrix3f: pxr.Gf.Matrix3f, usdrt.Gf.Matrix4d: pxr.Gf.Matrix4d, usdrt.Gf.Matrix4f: pxr.Gf.Matrix4f, } test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] for Mat, size, count, fmt in mat_info: test_pxr_type = equivalent_types[Mat](*test_values[:count]) test_mat = Mat(test_pxr_type) self.assertEquals(test_mat, Mat(*test_values[:count])) @tc_logger def test_buffer_init_from_numpy_type(self): """Test initialization from numpy types""" import numpy mat_info = get_mat_info() equivalent_types = get_mat_numpy_types() test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] for Mat, size, count, fmt in mat_info: py_mat = [] stride = int(math.sqrt(count)) for i in range(stride): py_mat.append(test_values[i * stride : i * stride + stride]) test_numpy_type = numpy.array(py_mat, dtype=equivalent_types[Mat]) test_mat = Mat(test_numpy_type) self.assertEquals(test_mat, Mat(*test_values[:count])) @tc_logger def test_buffer_init_wrong_type(self): """Verify that an exception is raised with initializing via buffer with different data type""" import numpy mat_info = get_mat_info() equivalent_types = get_mat_numpy_types() test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] for Mat, size, count, fmt in mat_info: py_mat = [] stride = int(math.sqrt(count)) for i in range(stride): py_mat.append(test_values[i * stride : i * stride + stride]) test_numpy_type = numpy.array(py_mat, dtype=numpy.int_) with self.assertRaises(ValueError): test_mat = Mat(test_numpy_type) @tc_logger def test_buffer_init_wrong_size(self): """Verify that an exception is raised with initializing via buffer with different data array length""" import numpy mat_info = get_mat_info() equivalent_types = get_mat_numpy_types() test_values = [[0, 1], [2, 3]] for Mat, size, count, fmt in mat_info: test_numpy_type = numpy.array(test_values, dtype=equivalent_types[Mat]) with self.assertRaises(ValueError): test_mat = Mat(test_numpy_type) @tc_logger def test_buffer_init_wrong_dimension(self): """Verify that an exception is raised with initializing via buffer with different data dimensions""" import numpy mat_info = get_mat_info() equivalent_types = get_mat_numpy_types() test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] for Mat, size, count, fmt in mat_info: test_array = numpy.array(test_values[:count], dtype=equivalent_types[Mat]) with self.assertRaises(ValueError): test_mat = Mat(test_array) class TestGfMatrixGetSetItem(TestRtScenegraph): """Test single-item accessors for usdrt.Gf.Matrix* classes""" @tc_logger def test_get_item(self): """Validate GetArrayItem on GfMatrix""" from usdrt import Gf for Mat in [Gf.Matrix3d, Gf.Matrix3f, Gf.Matrix4d, Gf.Matrix4f]: items = Mat.dimension[0] * Mat.dimension[1] m = Mat(*[i for i in range(items)]) for i in range(items): self.assertTrue(m.GetArrayItem(i) == i) @tc_logger def test_set_item(self): """Validate SetArrayItem on GfMatrix""" from usdrt import Gf for Mat in [Gf.Matrix3d, Gf.Matrix3f, Gf.Matrix4d, Gf.Matrix4f]: m = Mat() self.assertEqual(m, Mat(1)) items = Mat.dimension[0] * Mat.dimension[1] expected = Mat(*[i for i in range(items)]) for i in range(items): m.SetArrayItem(i, i) self.assertNotEqual(m, Mat(1)) self.assertEqual(m, expected) class TestGfMatrixCopy(TestRtScenegraph): """Test copy and deepcopy support for Gf.Mat* classes""" @tc_logger def test_copy(self): """Test __copy__""" mat_info = get_mat_info() for Mat, size, count, fmt in mat_info: x = Mat() y = x self.assertTrue(y is x) y[0, 0] = 10 self.assertEqual(x[0, 0], 10) z = copy.copy(y) self.assertFalse(z is y) y[0, 0] = 100 self.assertEqual(z[0, 0], 10) @tc_logger def test_deepcopy(self): """Test __deepcopy__""" mat_info = get_mat_info() for Mat, size, count, fmt in mat_info: x = Mat() y = x self.assertTrue(y is x) y[0, 0] = 10 self.assertEqual(x[0, 0], 10) z = copy.deepcopy(y) self.assertFalse(z is y) y[0, 0] = 100 self.assertEqual(z[0, 0], 10) class TestGfMatrixDebugging(TestRtScenegraph): """Test human readable output functions for debugging""" @tc_logger def test_repr_representation(self): """Test __repr__""" from usdrt import Gf test_vec = Gf.Vec4d(9, 8, 7, 6) test_matrix = Gf.Matrix4d(test_vec) # Sets matrix to diagonal form (ith element on the diagonal set to vec[i]) expected = "Gf.Matrix4d(9.0, 0.0, 0.0, 0.0, 0.0, 8.0, 0.0, 0.0, 0.0, 0.0, 7.0, 0.0, 0.0, 0.0, 0.0, 6.0)" self.assertEqual(repr(test_matrix), expected) class TestGfMatrixSetLookAtExtras(TestRtScenegraph): """More tests to validate SetLookAt""" @tc_logger def test_set_look_at_extras(self): """Test more points to ensure behavior match to Pixar implementation""" from pxr import Gf from usdrt import Gf as RtGf target = [(0, 0, -20), (0, 0, -30), (0, 0, -40), (-10, 0, -40), (-20, 0, -40), (-30, 0, -40)] eye = [(0, 0, 0), (0, 1, 0), (0, 2, 0), (0, 3, 0), (1, 3, 0), (2, 3, 0), (3, 3, 0)] for eye_pos in eye: for target_pos in target: pxr_result = Gf.Matrix4d(1).SetLookAt(Gf.Vec3d(*eye_pos), Gf.Vec3d(*target_pos), Gf.Vec3d(0, 1, 0)) rt_result = RtGf.Matrix4d(1).SetLookAt( RtGf.Vec3d(*eye_pos), RtGf.Vec3d(*target_pos), RtGf.Vec3d(0, 1, 0) ) self.assertTrue(RtGf.IsClose(RtGf.Matrix4d(pxr_result), rt_result, 0.0001))
8,982
Python
29.763699
119
0.575707
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/testGfMatrix.py
# Copyright 2016 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. # # Note: This is just pulled directly from USD and lightly modified # https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfMatrix.py from __future__ import division, print_function __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 sys import unittest ##### Uncomment for better assert messages # if 'unittest.util' in __import__('sys').modules: # # Show full diff in self.assertEqual. # __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999 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 except ImportError: TestClass = unittest.TestCase try: import numpy hasNumpy = True except ImportError: print("numpy not available, skipping buffer protocol tests") hasNumpy = False def makeValue(Value, vals): if Value == float: return Value(vals[0]) else: v = Value() for i in range(v.dimension): v[i] = vals[i] return v class TestGfMatrix(TestClass): def test_Basic(self): from usdrt import Gf Matrices = [ # (Gf.Matrix2d, Gf.Vec2d), # (Gf.Matrix2f, Gf.Vec2f), (Gf.Matrix3d, Gf.Vec3d), (Gf.Matrix3f, Gf.Vec3f), (Gf.Matrix4d, Gf.Vec4d), (Gf.Matrix4f, Gf.Vec4f), ] for (Matrix, Vec) in Matrices: # constructors self.assertIsInstance(Matrix(), Matrix) self.assertIsInstance(Matrix(1), Matrix) self.assertIsInstance(Matrix(Vec()), Matrix) # python default constructor produces identity. self.assertEqual(Matrix(), Matrix(1)) if hasNumpy: # Verify population of numpy arrays. emptyNumpyArray = numpy.empty((1, Matrix.dimension[0], Matrix.dimension[1]), dtype="float32") emptyNumpyArray[0] = Matrix(1) if Matrix.dimension == (2, 2): self.assertIsInstance(Matrix(1, 2, 3, 4), Matrix) self.assertEqual(Matrix().Set(1, 2, 3, 4), Matrix(1, 2, 3, 4)) array = numpy.array(Matrix(1, 2, 3, 4)) self.assertEqual(array.shape, (2, 2)) # XXX: Currently cannot round-trip Gf.Matrix*f through # numpy.array if Matrix != Gf.Matrix2f: self.assertEqual(Matrix(array), Matrix(1, 2, 3, 4)) elif Matrix.dimension == (3, 3): self.assertIsInstance(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9), Matrix) self.assertEqual(Matrix().Set(1, 2, 3, 4, 5, 6, 7, 8, 9), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9)) array = numpy.array(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9)) self.assertEqual(array.shape, (3, 3)) # XXX: Currently cannot round-trip Gf.Matrix*f through # numpy.array if Matrix != Gf.Matrix3f: self.assertEqual(Matrix(array), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9)) elif Matrix.dimension == (4, 4): self.assertIsInstance(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), Matrix) self.assertEqual( Matrix().Set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), ) array = numpy.array(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)) self.assertEqual(array.shape, (4, 4)) # XXX: Currently cannot round-trip Gf.Matrix*f through # numpy.array if Matrix != Gf.Matrix4f: self.assertEqual(Matrix(array), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)) else: self.fail() self.assertEqual(Matrix().SetIdentity(), Matrix(1)) self.assertEqual(Matrix().SetZero(), Matrix(0)) self.assertEqual(Matrix().SetDiagonal(0), Matrix().SetZero()) self.assertEqual(Matrix().SetDiagonal(1), Matrix().SetIdentity()) def test_Comparisons(self): from usdrt import Gf Matrices = [(Gf.Matrix3d, Gf.Matrix3f), (Gf.Matrix4d, Gf.Matrix4f)] # (Gf.Matrix2d, Gf.Matrix2f), for (Matrix, Matrixf) in Matrices: # Test comparison of Matrix and Matrixf # size = Matrix.dimension[0] * Matrix.dimension[1] contents = list(range(1, size + 1)) md = Matrix(*contents) mf = Matrixf(*contents) self.assertEqual(md, mf) contents.reverse() md.Set(*contents) mf.Set(*contents) self.assertEqual(md, mf) # Convert to double precision floating point values contents = [1.0 / x for x in contents] mf.Set(*contents) md.Set(*contents) # These should *NOT* be equal due to roundoff errors in the floats. self.assertNotEqual(md, mf) def test_Other(self): from usdrt import Gf Matrices = [ # (Gf.Matrix2d, Gf.Vec2d), # (Gf.Matrix2f, Gf.Vec2f), (Gf.Matrix3d, Gf.Vec3d), (Gf.Matrix3f, Gf.Vec3f), (Gf.Matrix4d, Gf.Vec4d), (Gf.Matrix4f, Gf.Vec4f), ] for (Matrix, Vec) in Matrices: v = Vec() for i in range(v.dimension): v[i] = i m1 = Matrix().SetDiagonal(v) m2 = Matrix(0) for i in range(m2.dimension[0]): m2[i, i] = i self.assertEqual(m1, m2) v = Vec() for i in range(v.dimension): v[i] = 10 self.assertEqual(Matrix().SetDiagonal(v), Matrix().SetDiagonal(10)) self.assertEqual(type(Matrix()[0]), Vec) m = Matrix() m[0] = makeValue(Vec, (3, 1, 4, 1)) self.assertEqual(m[0], makeValue(Vec, (3, 1, 4, 1))) m = Matrix() m[-1] = makeValue(Vec, (3, 1, 4, 1)) self.assertEqual(m[-1], makeValue(Vec, (3, 1, 4, 1))) m = Matrix() m[0, 0] = 1 m[1, 0] = 2 m[0, 1] = 3 m[1, 1] = 4 self.assertTrue(m[0, 0] == 1 and m[1, 0] == 2 and m[0, 1] == 3 and m[1, 1] == 4) m = Matrix() m[-1, -1] = 1 m[-2, -1] = 2 m[-1, -2] = 3 m[-2, -2] = 4 self.assertTrue(m[-1, -1] == 1 and m[-2, -1] == 2 and m[-1, -2] == 3 and m[-2, -2] == 4) m = Matrix() for i in range(m.dimension[0]): for j in range(m.dimension[1]): m[i, j] = i * m.dimension[1] + j m = m.GetTranspose() for i in range(m.dimension[0]): for j in range(m.dimension[1]): self.assertEqual(m[j, i], i * m.dimension[1] + j) self.assertEqual(Matrix(1).GetInverse(), Matrix(1)) self.assertEqual(Matrix(4).GetInverse() * Matrix(4), Matrix(1)) # nv edit - intentionally diverge from pixar's implementation # GetInverse for zero matrix returns zero matrix instead of max float scale matrix # "so that multiplying by this is less likely to be catastrophic." self.assertEqual(Matrix(0).GetInverse(), Matrix(0)) self.assertEqual(Matrix(3).GetDeterminant(), 3 ** Matrix.dimension[0]) self.assertEqual(len(Matrix()), Matrix.dimension[0]) # Test GetRow, GetRow3, GetColumn m = Matrix(1) for i in range(m.dimension[0]): for j in range(m.dimension[1]): m[i, j] = i * m.dimension[1] + j for i in range(m.dimension[0]): j0 = i * m.dimension[1] self.assertEqual(m.GetRow(i), makeValue(Vec, tuple(range(j0, j0 + m.dimension[1])))) if Matrix == Gf.Matrix4d: self.assertEqual(m.GetRow3(i), Gf.Vec3d(j0, j0 + 1, j0 + 2)) for j in range(m.dimension[1]): self.assertEqual( m.GetColumn(j), makeValue(Vec, tuple(j + x * m.dimension[0] for x in range(m.dimension[0]))) ) # Test SetRow, SetRow3, SetColumn m = Matrix(1) for i in range(m.dimension[0]): j0 = i * m.dimension[1] v = makeValue(Vec, tuple(range(j0, j0 + m.dimension[1]))) m.SetRow(i, v) self.assertEqual(v, m.GetRow(i)) m = Matrix(1) if Matrix == Gf.Matrix4d: for i in range(m.dimension[0]): j0 = i * m.dimension[1] v = Gf.Vec3d(j0, j0 + 1, j0 + 2) m.SetRow3(i, v) self.assertEqual(v, m.GetRow3(i)) m = Matrix(1) for j in range(m.dimension[0]): v = makeValue(Vec, tuple(j + x * m.dimension[0] for x in range(m.dimension[0]))) m.SetColumn(i, v) self.assertEqual(v, m.GetColumn(i)) m = Matrix(4) m *= Matrix(1.0 / 4) self.assertEqual(m, Matrix(1)) m = Matrix(4) self.assertEqual(m * Matrix(1.0 / 4), Matrix(1)) self.assertEqual(Matrix(4) * 2, Matrix(8)) self.assertEqual(2 * Matrix(4), Matrix(8)) m = Matrix(4) m *= 2 self.assertEqual(m, Matrix(8)) m = Matrix(3) m += Matrix(2) self.assertEqual(m, Matrix(5)) m = Matrix(3) m -= Matrix(2) self.assertEqual(m, Matrix(1)) self.assertEqual(Matrix(2) + Matrix(3), Matrix(5)) self.assertEqual(Matrix(4) - Matrix(4), Matrix(0)) self.assertEqual(-Matrix(-1), Matrix(1)) self.assertEqual(Matrix(3) / Matrix(2), Matrix(3) * Matrix(2).GetInverse()) self.assertEqual(Matrix(2) * makeValue(Vec, (3, 1, 4, 1)), makeValue(Vec, (6, 2, 8, 2))) self.assertEqual(makeValue(Vec, (3, 1, 4, 1)) * Matrix(2), makeValue(Vec, (6, 2, 8, 2))) Vecf = {Gf.Vec2d: Gf.Vec2f, Gf.Vec3d: Gf.Vec3f, Gf.Vec4d: Gf.Vec4f}.get(Vec) if Vecf is not None: self.assertEqual(Matrix(2) * makeValue(Vecf, (3, 1, 4, 1)), makeValue(Vecf, (6, 2, 8, 2))) self.assertEqual(makeValue(Vecf, (3, 1, 4, 1)) * Matrix(2), makeValue(Vecf, (6, 2, 8, 2))) self.assertTrue(2 in Matrix(2) and not 4 in Matrix(2)) m = Matrix(1) try: m[m.dimension[0] + 1] = Vec() except: pass else: self.fail() m = Matrix(1) try: m[m.dimension[0] + 1, m.dimension[1] + 1] = 10 except: pass else: self.fail() m = Matrix(1) try: m[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] = 3 self.fail() except: pass try: x = m[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] self.fail() except: pass m = Matrix(1) try: m["foo"] = 3 except: pass else: self.fail() self.assertEqual(m, eval(repr(m))) self.assertTrue(len(str(Matrix()))) def test_Matrix3Transforms(self): from usdrt import Gf # TODO - Gf.Rotation not supported, # so this test is currently a noop Matrices = [ # (Gf.Matrix3d, Gf.Vec3d, Gf.Quatd), # (Gf.Matrix3f, Gf.Vec3f, Gf.Quatf) ] for (Matrix, Vec, Quat) in Matrices: def _VerifyOrthonormVecs(mat): v0 = Vec(mat[0][0], mat[0][1], mat[0][2]) v1 = Vec(mat[1][0], mat[1][1], mat[1][2]) v2 = Vec(mat[2][0], mat[2][1], mat[2][2]) self.assertTrue( Gf.IsClose(Gf.Dot(v0, v1), 0, 0.0001) and Gf.IsClose(Gf.Dot(v0, v2), 0, 0.0001) and Gf.IsClose(Gf.Dot(v1, v2), 0, 0.0001) ) m = Matrix() m.SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)) m2 = Matrix(m) m_o = m.GetOrthonormalized() self.assertEqual(m_o, m2) m.Orthonormalize() self.assertEqual(m, m2) m = Matrix(3) m_o = m.GetOrthonormalized() # GetOrthonormalized() should not mutate m self.assertNotEqual(m, m_o) self.assertEqual(m_o, Matrix(1)) m.Orthonormalize() self.assertEqual(m, Matrix(1)) m = Matrix(1, 0, 0, 1, 0, 0, 1, 0, 0) # should print a warning print("expect a warning about failed convergence in OrthogonalizeBasis:") m.Orthonormalize() m = Matrix(1, 0, 0, 1, 0, 0.0001, 0, 1, 0) m_o = m.GetOrthonormalized() _VerifyOrthonormVecs(m_o) m.Orthonormalize() _VerifyOrthonormVecs(m) r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)).ExtractRotation() r2 = Gf.Rotation(Gf.Vec3d(1, 0, 0), 30) self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001)) r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 1, 1), 60)).ExtractRotation() r2 = Gf.Rotation(Gf.Vec3d(1, 1, 1), 60) self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001)) r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 1, 1), 90)).ExtractRotation() r2 = Gf.Rotation(Gf.Vec3d(1, 1, 1), 90) self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001)) r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 1, 1), 120)).ExtractRotation() r2 = Gf.Rotation(Gf.Vec3d(1, 1, 1), 120) self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001)) # Setting rotation using a quaternion should give the same results # as setting a GfRotation. rot = Gf.Rotation(Gf.Vec3d(1, 1, 1), 120) quat = Quat(rot.GetQuaternion().GetReal(), Vec(rot.GetQuaternion().GetImaginary())) r = Matrix().SetRotate(rot).ExtractRotation() r2 = Matrix().SetRotate(quat).ExtractRotation() self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001)) self.assertEqual(Matrix().SetScale(10), Matrix(10)) m = Matrix().SetScale(Vec(1, 2, 3)) self.assertTrue(m[0, 0] == 1 and m[1, 1] == 2 and m[2, 2] == 3) # Initializing with GfRotation should give same results as SetRotate. r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)).ExtractRotation() r2 = Matrix(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)).ExtractRotation() self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001)) # Initializing with a quaternion should give same results as SetRotate. rot = Gf.Rotation(Gf.Vec3d(1, 1, 1), 120) quat = Quat(rot.GetQuaternion().GetReal(), Vec(rot.GetQuaternion().GetImaginary())) r = Matrix().SetRotate(quat).ExtractRotation() r2 = Matrix(quat).ExtractRotation() self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001)) self.assertEqual(Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1).GetHandedness(), 1.0) self.assertEqual(Matrix(-1, 0, 0, 0, 1, 0, 0, 0, 1).GetHandedness(), -1.0) self.assertEqual(Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0).GetHandedness(), 0.0) self.assertTrue(Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1).IsRightHanded()) self.assertTrue(Matrix(-1, 0, 0, 0, 1, 0, 0, 0, 1).IsLeftHanded()) # Test that this does not generate a nan in the angle (bug #12744) mx = Gf.Matrix3d( 0.999999999982236, -5.00662622471027e-06, 2.07636574601397e-06, 5.00666175191934e-06, 1.0000000000332, -2.19113616402155e-07, -2.07635686422463e-06, 2.19131379884019e-07, 1, ) r = mx.ExtractRotation() # math.isnan won't be available until python 2.6 if sys.version_info[0] >= 2 and sys.version_info[1] >= 6: self.assertFalse(math.isnan(r.angle)) else: # If this fails, then r.angle is Nan. Works on linux, may not be portable. self.assertEqual(r.angle, r.angle) def test_Matrix4Transforms(self): from usdrt import Gf # nv edit - TODO support Quatd and Quatf Matrices = [ (Gf.Matrix4d, Gf.Vec4d, Gf.Matrix3d, Gf.Vec3d), # , Gf.Quatd), (Gf.Matrix4f, Gf.Vec4f, Gf.Matrix3f, Gf.Vec3f), ] # , Gf.Quatf)] # for (Matrix, Vec, Matrix3, Vec3, Quat) in Matrices: for (Matrix, Vec, Matrix3, Vec3) in Matrices: def _VerifyOrthonormVecs(mat): v0 = Vec3(mat[0][0], mat[0][1], mat[0][2]) v1 = Vec3(mat[1][0], mat[1][1], mat[1][2]) v2 = Vec3(mat[2][0], mat[2][1], mat[2][2]) self.assertTrue( Gf.IsClose(Gf.Dot(v0, v1), 0, 0.0001) and Gf.IsClose(Gf.Dot(v0, v2), 0, 0.0001) and Gf.IsClose(Gf.Dot(v1, v2), 0, 0.0001) ) m = Matrix() m.SetLookAt(Vec3(1, 0, 0), Vec3(0, 0, 1), Vec3(0, 1, 0)) # nv edit - break this across multiple statements self.assertTrue(Gf.IsClose(m[0], Vec(-0.707107, 0, 0.707107, 0), 0.0001)) self.assertTrue(Gf.IsClose(m[1], Vec(0, 1, 0, 0), 0.0001)) self.assertTrue(Gf.IsClose(m[2], Vec(-0.707107, 0, -0.707107, 0), 0.0001)) self.assertTrue(Gf.IsClose(m[3], Vec(0.707107, 0, -0.707107, 1), 0.0001)) # Transform v = Gf.Vec3f(1, 1, 1) v2 = Matrix(3).Transform(v) self.assertEqual(v2, Gf.Vec3f(1, 1, 1)) self.assertEqual(type(v2), Gf.Vec3f) v = Gf.Vec3d(1, 1, 1) v2 = Matrix(3).Transform(v) self.assertEqual(v2, Gf.Vec3d(1, 1, 1)) self.assertEqual(type(v2), Gf.Vec3d) # TransformDir v = Gf.Vec3f(1, 1, 1) v2 = Matrix(3).TransformDir(v) self.assertEqual(v2, Gf.Vec3f(3, 3, 3)) self.assertEqual(type(v2), Gf.Vec3f) v = Gf.Vec3d(1, 1, 1) v2 = Matrix(3).TransformDir(v) self.assertEqual(v2, Gf.Vec3d(3, 3, 3)) self.assertEqual(type(v2), Gf.Vec3d) # TransformAffine v = Gf.Vec3f(1, 1, 1) # nv edit - no implict conversion from tuple yet v2 = Matrix(3).SetTranslateOnly(Vec3(1, 2, 3)).TransformAffine(v) self.assertEqual(v2, Gf.Vec3f(4, 5, 6)) self.assertEqual(type(v2), Gf.Vec3f) v = Gf.Vec3d(1, 1, 1) # nv edit - no implict conversion from tuple yet v2 = Matrix(3).SetTranslateOnly(Vec3(1, 2, 3)).TransformAffine(v) self.assertEqual(v2, Gf.Vec3d(4, 5, 6)) self.assertEqual(type(v2), Gf.Vec3d) # Constructor, SetRotate, and SetRotateOnly w/GfQuaternion """ nv edit Gf.Rotation not supported m = Matrix() r = Gf.Rotation(Gf.Vec3d(1,0,0), 30) quat = r.GetQuaternion() m.SetRotate(Quat(quat.GetReal(), Vec3(quat.GetImaginary()))) m2 = Matrix(r, Vec3(0,0,0)) m_o = m.GetOrthonormalized() self.assertEqual(m_o, m2) m.Orthonormalize() self.assertEqual(m, m2) m3 = Matrix(1) m3.SetRotateOnly(Quat(quat.GetReal(), Vec3(quat.GetImaginary()))) self.assertEqual(m2, m3) # Constructor, SetRotate, and SetRotateOnly w/GfRotation m = Matrix() r = Gf.Rotation(Gf.Vec3d(1,0,0), 30) m.SetRotate(r) m2 = Matrix(r, Vec3(0,0,0)) m_o = m.GetOrthonormalized() self.assertEqual(m_o, m2) m.Orthonormalize() self.assertEqual(m, m2) m3 = Matrix(1) m3.SetRotateOnly(r) self.assertEqual(m2, m3) # Constructor, SetRotate, and SetRotateOnly w/mx m3d = Matrix3() m3d.SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), 30)) m = Matrix(m3d, Vec3(0,0,0)) m2 = Matrix() m2 = m2.SetRotate(m3d) m3 = Matrix() m3 = m2.SetRotateOnly(m3d) self.assertEqual(m, m2) self.assertEqual(m2, m3) """ m = Matrix().SetTranslate(Vec3(12, 13, 14)) * Matrix(3) m.Orthonormalize() t = Matrix().SetTranslate(m.ExtractTranslation()) mnot = m * t.GetInverse() self.assertEqual(mnot, Matrix(1)) m = Matrix() m.SetTranslate(Vec3(1, 2, 3)) m2 = Matrix(m) m3 = Matrix(1) m3.SetTranslateOnly(Vec3(1, 2, 3)) m_o = m.GetOrthonormalized() self.assertEqual(m_o, m2) self.assertEqual(m_o, m3) m.Orthonormalize() self.assertEqual(m, m2) self.assertEqual(m, m3) v = Vec3(11, 22, 33) m = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16).SetTranslateOnly(v) self.assertEqual(m.ExtractTranslation(), v) # Initializing with GfRotation should give same results as SetRotate # and SetTransform """ nv edit TODO r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0),30)).ExtractRotation() r2 = Matrix(Gf.Rotation(Gf.Vec3d(1,0,0),30), Vec3(1,2,3)).ExtractRotation() r3 = Matrix().SetTransform(Gf.Rotation(Gf.Vec3d(1,0,0),30), Vec3(1,2,3)).ExtractRotation() self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and \ Gf.IsClose(r.angle, r2.angle, 0.0001)) self.assertTrue(Gf.IsClose(r3.axis, r2.axis, 0.0001) and \ Gf.IsClose(r3.angle, r2.angle, 0.0001)) # Initializing with GfRotation should give same results as # SetRotate(quaternion) and SetTransform rot = Gf.Rotation(Gf.Vec3d(1,0,0),30) quat = Quat(rot.GetQuaternion().GetReal(), Vec3(rot.GetQuaternion().GetImaginary())) r = Matrix().SetRotate(quat).ExtractRotation() r2 = Matrix(rot, Vec3(1,2,3)).ExtractRotation() r3 = Matrix().SetTransform(rot, Vec3(1,2,3)).ExtractRotation() self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and \ Gf.IsClose(r.angle, r2.angle, 0.0001)) self.assertTrue(Gf.IsClose(r3.axis, r2.axis, 0.0001) and \ Gf.IsClose(r3.angle, r2.angle, 0.0001)) # Same test w/mx instead of GfRotation mx3d = Matrix3(Gf.Rotation(Gf.Vec3d(1,0,0),30)) r4 = Matrix().SetTransform(mx3d, Vec3(1,2,3)).ExtractRotation() r5 = Matrix(mx3d, Vec3(1,2,3)).ExtractRotation() self.assertTrue(Gf.IsClose(r4.axis, r2.axis, 0.0001) and \ Gf.IsClose(r4.angle, r2.angle, 0.0001)) self.assertTrue(Gf.IsClose(r4.axis, r5.axis, 0.0001) and \ Gf.IsClose(r4.angle, r5.angle, 0.0001)) # ExtractQuat() and ExtractRotation() should yield # equivalent rotations. m = Matrix(mx3d, Vec3(1,2,3)) r1 = m.ExtractRotation() r2 = Gf.Rotation(m.ExtractRotationQuat()) self.assertTrue(Gf.IsClose(r1.axis, r2.axis, 0.0001) and \ Gf.IsClose(r2.angle, r2.angle, 0.0001)) m4 = Matrix(mx3d, Vec3(1,2,3)).ExtractRotationMatrix() self.assertEqual(m4, mx3d) """ # Initializing with GfMatrix3d # nv edit - dumb, not supported # m = Matrix(1,2,3,0,4,5,6,0,7,8,9,0,10,11,12,1) # m2 = Matrix(Matrix3(1,2,3,4,5,6,7,8,9), Vec3(10, 11, 12)) # assert(m == m2) m = Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1) # should print a warning - nv edit - our implementation doesn't # print("expect a warning about failed convergence in OrthogonalizeBasis:") m.Orthonormalize() m = Matrix(1, 0, 0, 0, 1, 0, 0.0001, 0, 0, 1, 0, 0, 0, 0, 0, 1) m_o = m.GetOrthonormalized() _VerifyOrthonormVecs(m_o) m.Orthonormalize() _VerifyOrthonormVecs(m) m = Matrix() m[3, 0] = 4 m[3, 1] = 5 m[3, 2] = 6 self.assertEqual(m.ExtractTranslation(), Vec3(4, 5, 6)) self.assertEqual(Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).GetHandedness(), 1.0) self.assertEqual(Matrix(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).GetHandedness(), -1.0) self.assertEqual(Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).GetHandedness(), 0.0) self.assertTrue(Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).IsRightHanded()) self.assertTrue(Matrix(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).IsLeftHanded()) # RemoveScaleShear """ nv edit Gf.Rotation not supported m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), 45)) m = Matrix().SetScale(Vec3(3,4,2)) * m m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), -30)) * m r = m.RemoveScaleShear() ro = r ro.Orthonormalize() self.assertEqual(ro, r) shear = Matrix(1,0,1,0, 0,1,0,0, 0,0,1,0, 0,0,0,1) r = shear.RemoveScaleShear() ro = r ro.Orthonormalize() self.assertEqual(ro, r) m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), 45)) m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), -30)) * m m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,1,0), 59)) * m r = m.RemoveScaleShear() maxEltErr = 0 for i in range(4): for j in range(4): maxEltErr = max(maxEltErr, abs(r[i][j] - m[i][j])) self.assertTrue(Gf.IsClose(maxEltErr, 0.0, 1e-5)) # IsClose self.assertFalse(Gf.IsClose(Matrix(1), Matrix(1.0001), 1e-5)) self.assertTrue(Gf.IsClose(Matrix(1), Matrix(1.000001), 1e-5)) """ def test_Matrix4Factoring(self): from usdrt import Gf """ nv edit Gf.Rotation not supported Matrices = [(Gf.Matrix4d, Gf.Vec3d), (Gf.Matrix4f, Gf.Vec3f)] for (Matrix, Vec3) in Matrices: def testFactor(m, expectSuccess, eps=None): factor = lambda m : m.Factor() if eps is not None: factor = lambda m : m.Factor(eps) (success, scaleOrientation, scale, rotation, \ translation, projection) = factor(m) self.assertEqual(success, expectSuccess) factorProduct = scaleOrientation * \ Matrix().SetScale(scale) * \ scaleOrientation.GetInverse() * \ rotation * \ Matrix().SetTranslate(translation) * \ projection maxEltErr = 0 for i in range(4): for j in range(4): maxEltErr = max(maxEltErr, abs(factorProduct[i][j] - m[i][j])) self.assertTrue(Gf.IsClose(maxEltErr, 0.0, 1e-5), maxEltErr) # A rotate m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), 45)) testFactor(m,True) # A couple of rotates m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), -45)) m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), 45)) * m testFactor(m,True) # A scale m = Matrix().SetScale(Vec3(3,1,4)) testFactor(m,True) # A scale in a rotated space m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), 45)) m = Matrix().SetScale(Vec3(3,4,2)) * m m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), -45)) * m testFactor(m,True) # A nearly degenerate scale if Matrix == Gf.Matrix4d: eps = 1e-10 elif Matrix == Gf.Matrix4f: eps = 1e-5 m = Matrix().SetScale((eps*2, 1, 1)) testFactor(m,True) # Test with epsilon. m = Matrix().SetScale((eps*2, 1, 1)) testFactor(m,False,eps*3) # A singular (1) scale in a rotated space m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,1,1), Gf.Vec3d(1,0,0) )) m = m * Matrix().SetScale(Vec3(0,1,1)) m = m * Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), Gf.Vec3d(1,1,1) )) testFactor(m,False) # A singular (2) scale in a rotated space m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,1,1), Gf.Vec3d(1,0,0) )) m = m * Matrix().SetScale(Vec3(0,0,1)) m = m * Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), Gf.Vec3d(1,1,1) )) testFactor(m,False) # A scale in a sheared space shear = Matrix(1) shear.SetRow3(0, Vec3(1, 1, 1).GetNormalized()) m = shear.GetInverse() * Matrix().SetScale(Vec3(2,3,4)) * shear testFactor(m,True) # A singular (1) scale in a sheared space shear = Matrix(1) shear.SetRow3(0, Vec3(1, 1, 1).GetNormalized()) m = shear.GetInverse() * Matrix().SetScale(Vec3(2,0,4)) * shear testFactor(m,False) # A singular (2) scale in a sheared space shear = Matrix(1) shear.SetRow3(0, Vec3(1, 1, 1).GetNormalized()) m = shear.GetInverse() * Matrix().SetScale(Vec3(0,3,0)) * shear testFactor(m,False) # A scale and a rotate m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) )) m = Matrix().SetScale(Vec3(1,2,3)) * m testFactor(m,True) # A singular (1) scale and a rotate m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) )) m = Matrix().SetScale(Vec3(0,2,3)) * m testFactor(m,False) # A singular (2) scale and a rotate m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) )) m = Matrix().SetScale(Vec3(0,0,3)) * m testFactor(m,False) # A singular scale (1), rotate, translate m = Matrix().SetTranslate(Vec3(3,1,4)) m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) )) * m m = Matrix().SetScale(Vec3(0,2,3)) * m testFactor(m,False) # A translate, rotate, singular scale (1), translate m = Matrix().SetTranslate(Vec3(3,1,4)) m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) )) * m m = Matrix().SetScale(Vec3(0,2,3)) * m m = Matrix().SetTranslate(Vec3(-10,-20,-30)) * m testFactor(m,False) """ def test_Matrix4Determinant(self): from usdrt import Gf Matrices = [Gf.Matrix4d, Gf.Matrix4f] for Matrix in Matrices: # Test GetDeterminant and GetInverse on Matrix4 def AssertDeterminant(m, det): # Unfortunately, we don't have an override of Gf.IsClose # for Gf.Matrix4* for row1, row2 in zip(m * m.GetInverse(), Matrix()): self.assertTrue(Gf.IsClose(row1, row2, 1e-5)) self.assertTrue(Gf.IsClose(m.GetDeterminant(), det, 1e-5)) m1 = Matrix(0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0) det1 = -1.0 m2 = Matrix(0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) det2 = -1.0 m3 = Matrix(0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0) det3 = -1.0 m4 = Matrix(1.0, 2.0, -1.0, 3.0, 2.0, 1.0, 4.0, 5.1, 2.0, 3.0, 1.0, 6.0, 3.0, 2.0, 1.0, 1.0) det4 = 16.8 AssertDeterminant(m1, det1) AssertDeterminant(m2, det2) AssertDeterminant(m3, det3) AssertDeterminant(m4, det4) AssertDeterminant(m1 * m1, det1 * det1) AssertDeterminant(m1 * m4, det1 * det4) AssertDeterminant(m1 * m3 * m4, det1 * det3 * det4) AssertDeterminant(m1 * m3 * m4 * m2, det1 * det3 * det4 * det2) AssertDeterminant(m2 * m3 * m4 * m2, det2 * det3 * det4 * det2)
35,494
Python
40.369464
118
0.514509
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/test_gf_range_extras.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.kit.test import copy import math import os import platform import sys import time import unittest from . import TestRtScenegraph, tc_logger, update_path_and_load_usd def setUpModule(): # pre-load USD before anything else to prevent crash # from weird carb conflict # FIXME ^^^ update_path_and_load_usd() class TestGfRangeCopy(TestRtScenegraph): """Test copy and deepcopy support for Gf.Range* classes""" @tc_logger def test_copy(self): """Test __copy__""" from usdrt import Gf x = Gf.Range3d() y = x self.assertTrue(y is x) y.min[0] = 10 self.assertEqual(x.min[0], 10) z = copy.copy(y) self.assertFalse(z is y) y.min[0] = 100 self.assertEqual(z.min[0], 10) x = Gf.Range2d() y = x self.assertTrue(y is x) y.min[0] = 20 self.assertEqual(x.min[0], 20) z = copy.copy(y) self.assertFalse(z is y) y.min[0] = 200 self.assertEqual(z.min[0], 20) x = Gf.Range1d() y = x self.assertTrue(y is x) y.min = 30 self.assertEqual(x.min, 30) z = copy.copy(y) self.assertFalse(z is y) y.min = 300 self.assertEqual(z.min, 30) @tc_logger def test_deepcopy(self): """Test __deepcopy__""" from usdrt import Gf x = Gf.Range3d() y = x self.assertTrue(y is x) y.min[0] = 10 self.assertEqual(x.min[0], 10) z = copy.deepcopy(y) self.assertFalse(z is y) y.min[0] = 100 self.assertEqual(z.min[0], 10) x = Gf.Range2d() y = x self.assertTrue(y is x) y.min[0] = 20 self.assertEqual(x.min[0], 20) z = copy.deepcopy(y) self.assertFalse(z is y) y.min[0] = 200 self.assertEqual(z.min[0], 20) x = Gf.Range1d() y = x self.assertTrue(y is x) y.min = 30 self.assertEqual(x.min, 30) z = copy.deepcopy(y) self.assertFalse(z is y) y.min = 300 self.assertEqual(z.min, 30) class TestGfRangeDebugging(TestRtScenegraph): """Test human readable output functions for debugging""" @tc_logger def test_repr_representation(self): """Test __repr__""" from usdrt import Gf test_min = Gf.Vec3d(1, 2, 3) test_max = Gf.Vec3d(4, 5, 6) test_range = Gf.Range3d(test_min, test_max) expected = "Gf.Range3d(Gf.Vec3d(1.0, 2.0, 3.0), Gf.Vec3d(4.0, 5.0, 6.0))" self.assertEqual(repr(test_range), expected)
3,099
Python
23.031008
81
0.579864
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/testGfRange.py
#!/pxrpythonsubst # # Copyright 2016 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. # # Note: This is just pulled directly from USD and modified # (we only support Gf.Range3d classes, but not Gf.Range3f, so # these tests are updated to reflect that) # https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfRange.py import math import sys import unittest ##### Uncomment for better assert messages # if 'unittest.util' in __import__('sys').modules: # # Show full diff in self.assertEqual. # __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999 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 except ImportError: TestClass = unittest.TestCase from usdrt import Gf def makeValue(Value, vals): if Value == float: return Value(vals[0]) else: v = Value() for i in range(v.dimension): v[i] = vals[i] return v class TestGfRange(TestClass): Ranges = [ (Gf.Range1d, float), (Gf.Range2d, Gf.Vec2d), (Gf.Range3d, Gf.Vec3d), (Gf.Range1f, float), (Gf.Range2f, Gf.Vec2f), (Gf.Range3f, Gf.Vec3f), ] def runTest(self): for Range, Value in self.Ranges: # constructors self.assertIsInstance(Range(), Range) self.assertIsInstance(Range(Value(), Value()), Range) v = makeValue(Value, [1, 2, 3, 4]) r = Range() r.min = v self.assertEqual(r.min, v) r.max = v self.assertEqual(r.max, v) r = Range() self.assertTrue(r.IsEmpty()) r = Range(-1) self.assertTrue(r.IsEmpty()) v1 = makeValue(Value, [-1, -2, -3, -4]) v2 = makeValue(Value, [1, 2, 3, 4]) r = Range(v2, v1) self.assertTrue(r.IsEmpty()) r = Range(v1, v2) self.assertFalse(r.IsEmpty()) r.SetEmpty() self.assertTrue(r.IsEmpty()) r = Range(v1, v2) self.assertEqual(r.GetSize(), v2 - v1) v1 = makeValue(Value, [-1, 1, -11, 2]) v2 = makeValue(Value, [1, 3, -10, 2]) v3 = makeValue(Value, [0, 2, -10.5, 2]) v4 = makeValue(Value, [0, 0, 0, 0]) r1 = Range(v1, v2) self.assertEqual(r1.GetMidpoint(), v3) r1.SetEmpty() r2 = Range() self.assertEqual(r1.GetMidpoint(), v4) self.assertEqual(r2.GetMidpoint(), v4) v1 = makeValue(Value, [-1, -2, -3, -4]) v2 = makeValue(Value, [1, 2, 3, 4]) r = Range(v1, v2) v1 = makeValue(Value, [0, 0, 0, 0]) v2 = makeValue(Value, [2, 3, 4, 5]) self.assertTrue(r.Contains(v1)) self.assertFalse(r.Contains(v2)) v1 = makeValue(Value, [-2, -4, -6, -8]) v2 = makeValue(Value, [2, 4, 6, 8]) r1 = Range(v1, v2) v1 = makeValue(Value, [-1, -2, -3, -4]) v2 = makeValue(Value, [1, 2, 3, 4]) r2 = Range(v1, v2) self.assertTrue(r1.Contains(r2)) self.assertFalse(r2.Contains(r1)) v1 = makeValue(Value, [-1, -2, -3, -4]) v2 = makeValue(Value, [2, 4, 6, 8]) v3 = makeValue(Value, [-2, -4, -6, -8]) v4 = makeValue(Value, [1, 2, 3, 4]) r1 = Range(v1, v2) r2 = Range(v3, v4) self.assertEqual(Range.GetUnion(r1, r2), Range(v3, v2)) self.assertEqual(Range.GetIntersection(r1, r2), Range(v1, v4)) r1 = Range(v1, v2) self.assertEqual(r1.UnionWith(r2), Range(v3, v2)) r1 = Range(v1, v2) self.assertEqual(r1.UnionWith(v3), Range(v3, v2)) r1 = Range(v1, v2) self.assertEqual(r1.IntersectWith(r2), Range(v1, v4)) r1 = Range(v1, v2) v5 = makeValue(Value, [100, 100, 100, 100]) dsqr = r1.GetDistanceSquared(v5) if Value == float: self.assertEqual(dsqr, 9604) elif Value.dimension == 2: self.assertEqual(dsqr, 18820) elif Value.dimension == 3: self.assertEqual(dsqr, 27656) else: self.fail() r1 = Range(v1, v2) v5 = makeValue(Value, [-100, -100, -100, -100]) dsqr = r1.GetDistanceSquared(v5) if Value == float: self.assertEqual(dsqr, 9801) elif Value.dimension == 2: self.assertEqual(dsqr, 19405) elif Value.dimension == 3: self.assertEqual(dsqr, 28814) else: self.fail() v1 = makeValue(Value, [1, 2, 3, 4]) v2 = makeValue(Value, [2, 3, 4, 5]) v3 = makeValue(Value, [3, 4, 5, 6]) v4 = makeValue(Value, [4, 5, 6, 7]) r1 = Range(v1, v2) r2 = Range(v2, v3) r3 = Range(v3, v4) r4 = Range(v4, v5) self.assertEqual(r1 + r2, Range(makeValue(Value, [3, 5, 7, 9]), makeValue(Value, [5, 7, 9, 11]))) self.assertEqual(r1 - r2, Range(makeValue(Value, [-2, -2, -2, -2]), makeValue(Value, [0, 0, 0, 0]))) self.assertEqual(r1 * 10, Range(makeValue(Value, [10, 20, 30, 40]), makeValue(Value, [20, 30, 40, 50]))) self.assertEqual(10 * r1, Range(makeValue(Value, [10, 20, 30, 40]), makeValue(Value, [20, 30, 40, 50]))) tmp = r1 / 10 self.assertTrue( Gf.IsClose(tmp.min, makeValue(Value, [0.1, 0.2, 0.3, 0.4]), 0.00001) and Gf.IsClose(tmp.max, makeValue(Value, [0.2, 0.3, 0.4, 0.5]), 0.00001) ) self.assertEqual(r1, Range(makeValue(Value, [1, 2, 3, 4]), makeValue(Value, [2, 3, 4, 5]))) self.assertFalse(r1 != Range(makeValue(Value, [1, 2, 3, 4]), makeValue(Value, [2, 3, 4, 5]))) r1 = Range(v1, v2) r2 = Range(v2, v3) r1 += r2 self.assertEqual(r1, Range(makeValue(Value, [3, 5, 7, 9]), makeValue(Value, [5, 7, 9, 11]))) r1 = Range(v1, v2) r1 -= r2 self.assertEqual(r1, Range(makeValue(Value, [-2, -2, -2, -2]), makeValue(Value, [0, 0, 0, 0]))) r1 = Range(v1, v2) r1 *= 10 self.assertEqual(r1, Range(makeValue(Value, [10, 20, 30, 40]), makeValue(Value, [20, 30, 40, 50]))) r1 = Range(v1, v2) r1 *= -10 self.assertEqual(r1, Range(makeValue(Value, [-20, -30, -40, -50]), makeValue(Value, [-10, -20, -30, -40]))) r1 = Range(v1, v2) r1 /= 10 self.assertTrue( Gf.IsClose(r1.min, makeValue(Value, [0.1, 0.2, 0.3, 0.4]), 0.00001) and Gf.IsClose(r1.max, makeValue(Value, [0.2, 0.3, 0.4, 0.5]), 0.00001) ) self.assertEqual(r1, eval(repr(r1))) self.assertTrue(len(str(Range()))) # now test GetCorner and GetOctant for Gf.Range2f and Gf.Range2d Ranges = [(Gf.Range2d, Gf.Vec2d), (Gf.Range2f, Gf.Vec2f)] for Range, Value in Ranges: rf = Range.unitSquare() self.assertTrue( rf.GetCorner(0) == Value(0, 0) and rf.GetCorner(1) == Value(1, 0) and rf.GetCorner(2) == Value(0, 1) and rf.GetCorner(3) == Value(1, 1) ) self.assertTrue( rf.GetQuadrant(0) == Range(Value(0, 0), Value(0.5, 0.5)) and rf.GetQuadrant(1) == Range(Value(0.5, 0), Value(1, 0.5)) and rf.GetQuadrant(2) == Range(Value(0, 0.5), Value(0.5, 1)) and rf.GetQuadrant(3) == Range(Value(0.5, 0.5), Value(1, 1)) ) # now test GetCorner and GetOctant for Gf.Range3f and Gf.Range3d Ranges = [(Gf.Range3d, Gf.Vec3d), (Gf.Range3f, Gf.Vec3f)] for Range, Value in Ranges: rf = Range.unitCube() self.assertTrue( rf.GetCorner(0) == Value(0, 0, 0) and rf.GetCorner(1) == Value(1, 0, 0) and rf.GetCorner(2) == Value(0, 1, 0) and rf.GetCorner(3) == Value(1, 1, 0) and rf.GetCorner(4) == Value(0, 0, 1) and rf.GetCorner(5) == Value(1, 0, 1) and rf.GetCorner(6) == Value(0, 1, 1) and rf.GetCorner(7) == Value(1, 1, 1) and rf.GetCorner(8) == Value(0, 0, 0) ) vals = [ [(0.0, 0.0, 0.0), (0.5, 0.5, 0.5)], [(0.5, 0.0, 0.0), (1.0, 0.5, 0.5)], [(0.0, 0.5, 0.0), (0.5, 1.0, 0.5)], [(0.5, 0.5, 0.0), (1.0, 1.0, 0.5)], [(0.0, 0.0, 0.5), (0.5, 0.5, 1.0)], [(0.5, 0.0, 0.5), (1.0, 0.5, 1.0)], [(0.0, 0.5, 0.5), (0.5, 1.0, 1.0)], [(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)], ] ranges = [Range(Value(v[0]), Value(v[1])) for v in vals] for i in range(8): self.assertEqual(rf.GetOctant(i), ranges[i]) if __name__ == "__main__": unittest.main()
10,526
Python
34.564189
119
0.51197
omniverse-code/kit/exts/usdrt.gf/python/usdrt/Gf/tests/testGfQuat.py
# Copyright 2016 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. # # Note: This is just pulled directly from USD and modified # (we only support Gf.Quat classes, but not Gf.Quaternion, so # these tests are updated to reflect that) # https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfQuaternion.py from __future__ import division __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 sys import unittest ##### Uncomment for better assert messages # if 'unittest.util' in __import__('sys').modules: # # Show full diff in self.assertEqual. # __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999 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 except ImportError: TestClass = unittest.TestCase class TestGfQuaternion(TestClass): def test_Constructors(self): from usdrt import Gf # self.assertIsInstance(Gf.Quaternion(), Gf.Quaternion) # self.assertIsInstance(Gf.Quaternion(0), Gf.Quaternion) # self.assertIsInstance(Gf.Quaternion(1, Gf.Vec3d(1,1,1)), Gf.Quaternion) self.assertIsInstance(Gf.Quath(Gf.Quath()), Gf.Quath) self.assertIsInstance(Gf.Quatf(Gf.Quatf()), Gf.Quatf) self.assertIsInstance(Gf.Quatd(Gf.Quatd()), Gf.Quatd) # Testing conversions between Quat[h,f,d] self.assertIsInstance(Gf.Quath(Gf.Quatf()), Gf.Quath) self.assertIsInstance(Gf.Quath(Gf.Quatd()), Gf.Quath) self.assertIsInstance(Gf.Quatf(Gf.Quath()), Gf.Quatf) self.assertIsInstance(Gf.Quatf(Gf.Quatd()), Gf.Quatf) self.assertIsInstance(Gf.Quatd(Gf.Quath()), Gf.Quatd) self.assertIsInstance(Gf.Quatd(Gf.Quatf()), Gf.Quatd) def test_Properties(self): from usdrt import Gf # nv edit - use Quat classses instead of Quaternion for Quat, Vec in ((Gf.Quatd, Gf.Vec3d), (Gf.Quatf, Gf.Vec3f), (Gf.Quath, Gf.Vec3h)): q = Quat() q.real = 10 self.assertEqual(q.real, 10) q.imaginary = Vec(1, 2, 3) self.assertEqual(q.imaginary, Vec(1, 2, 3)) def test_Methods(self): from usdrt import Gf # nv edit - use Quat classses instead of Quaternion for Quat, Vec in ((Gf.Quatd, Gf.Vec3d), (Gf.Quatf, Gf.Vec3f), (Gf.Quath, Gf.Vec3h)): q = Quat() self.assertEqual(Quat.GetIdentity(), Quat(1, Vec())) self.assertTrue( Quat.GetIdentity().GetLength() == 1 and Gf.IsClose(Quat(1, Vec(2, 3, 4)).GetLength(), 5.4772255750516612, 0.00001) ) q = Quat(1, Vec(2, 3, 4)).GetNormalized() self.assertTrue( Gf.IsClose(q.real, 0.182574, 0.0001) and Gf.IsClose(q.imaginary, Vec(0.365148, 0.547723, 0.730297), 0.00001) ) # nv edit - linalg does not support arbitrary epsilon here # q = Quat(1,Vec(2,3,4)).GetNormalized(10) # self.assertEqual(q, Quat.GetIdentity()) q = Quat(1, Vec(2, 3, 4)) q.Normalize() self.assertTrue( Gf.IsClose(q.real, 0.182574, 0.0001) and Gf.IsClose(q.imaginary, Vec(0.365148, 0.547723, 0.730297), 0.00001) ) # nv edit - linalg does not support arbitrary epsilon here # q = Quat(1,Vec(2,3,4)).Normalize(10) # self.assertEqual(q, Quat.GetIdentity()) if Quat == Gf.Quath: # FIXME - below test does not pass for Quath: # AssertionError: Gf.Quath(1.0, Gf.Vec3h(0.0, 0.0, 0.0)) != Gf.Quath(1.0, Gf.Vec3h(-0.0, -0.0, -0.0)) continue q = Quat.GetIdentity() self.assertEqual(q, q.GetInverse()) q = Quat(1, Vec(1, 2, 3)) q.Normalize() (re, im) = (q.real, q.imaginary) self.assertTrue( Gf.IsClose(q.GetInverse().real, re, 0.00001) and Gf.IsClose(q.GetInverse().imaginary, -im, 0.00001) ) def test_Operators(self): from usdrt import Gf # nv edit - use Quat classses instead of Quaternion for Quat, Vec in ((Gf.Quatd, Gf.Vec3d), (Gf.Quatf, Gf.Vec3f), (Gf.Quath, Gf.Vec3h)): q1 = Quat(1, Vec(2, 3, 4)) q2 = Quat(1, Vec(2, 3, 4)) self.assertEqual(q1, q2) self.assertFalse(q1 != q2) q2.real = 2 self.assertTrue(q1 != q2) q = Quat(1, Vec(2, 3, 4)) * Quat.GetIdentity() self.assertEqual(q, Quat(1, Vec(2, 3, 4))) q = Quat(1, Vec(2, 3, 4)) q *= Quat.GetIdentity() self.assertEqual(q, Quat(1, Vec(2, 3, 4))) q *= 10 self.assertEqual(q, Quat(10, Vec(20, 30, 40))) q = q * 10 self.assertEqual(q, Quat(100, Vec(200, 300, 400))) q = 10 * q self.assertEqual(q, Quat(1000, Vec(2000, 3000, 4000))) q /= 100 self.assertEqual(q, Quat(10, Vec(20, 30, 40))) q = q / 10 self.assertEqual(q, Quat(1, Vec(2, 3, 4))) q += q self.assertEqual(q, Quat(2, Vec(4, 6, 8))) q -= Quat(1, Vec(2, 3, 4)) self.assertEqual(q, Quat(1, Vec(2, 3, 4))) q = q + q self.assertEqual(q, Quat(2, Vec(4, 6, 8))) q = q - Quat(1, Vec(2, 3, 4)) self.assertEqual(q, Quat(1, Vec(2, 3, 4))) q = q * q self.assertEqual(q, Quat(-28, Vec(4, 6, 8))) q1 = Quat(1, Vec(2, 3, 4)).GetNormalized() q2 = Quat(4, Vec(3, 2, 1)).GetNormalized() self.assertEqual(Gf.Slerp(0, q1, q2), q1) # nv edit - these are close but not exact with our implementation eps = 0.00001 if Quat in [Gf.Quatd, Gf.Quatf] else 0.001 # self.assertEqual(Gf.Slerp(1, q1, q2), q2) self.assertTrue(Gf.IsClose(Gf.Slerp(1, q1, q2), q2, eps)) # self.assertEqual(Gf.Slerp(0.5, q1, q2), Quat(0.5, Vec(0.5, 0.5, 0.5))) self.assertTrue(Gf.IsClose(Gf.Slerp(0.5, q1, q2), Quat(0.5, Vec(0.5, 0.5, 0.5)), eps)) # code coverage goodness q1 = Quat(0, Vec(1, 1, 1)) q2 = Quat(0, Vec(-1, -1, -1)) q = Gf.Slerp(0.5, q1, q2) self.assertTrue(Gf.IsClose(q.real, 0, 0.00001) and Gf.IsClose(q.imaginary, Vec(1, 1, 1), 0.00001)) q1 = Quat(0, Vec(1, 1, 1)) q2 = Quat(0, Vec(1, 1, 1)) q = Gf.Slerp(0.5, q1, q2) self.assertTrue(Gf.IsClose(q.real, 0, 0.00001) and Gf.IsClose(q.imaginary, Vec(1, 1, 1), 0.00001)) self.assertEqual(q, eval(repr(q))) self.assertTrue(len(str(Quat()))) for quatType in (Gf.Quatd, Gf.Quatf, Gf.Quath): q1 = quatType(1, [2, 3, 4]) q2 = quatType(2, [3, 4, 5]) self.assertTrue(Gf.IsClose(Gf.Dot(q1, q2), 40, 0.00001)) if __name__ == "__main__": unittest.main()
8,699
Python
37.157895
117
0.583975
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/extension.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportExtension'] import omni.ext import omni.kit.menu.utils from omni.ui import Workspace from omni.kit.menu.utils import MenuItemDescription from .window import ViewportWindow from .dragdrop.usd_file_drop_delegate import UsdFileDropDelegate from .dragdrop.usd_prim_drop_delegate import UsdShadeDropDelegate from .dragdrop.material_file_drop_delegate import MaterialFileDropDelegate from .dragdrop.audio_file_drop_delegate import AudioFileDropDelegate from .viewport_actions import register_actions, deregister_actions import carb from typing import Dict, List, Optional DEFAULT_VIEWPORT_NAME = '/exts/omni.kit.viewport.window/startup/windowName' DEFAULT_VIEWPORT_NO_OPEN = '/exts/omni.kit.viewport.window/startup/disableWindowOnLoad' DEFAULT_VIEWPORT_HIDE_TAB = '/exts/omni.kit.viewport.window/startup/dockTabInvisible' class _MenuEntry: def __init__(self, window_name: str, open_window: bool = False, index: int = 0): menu_label = f'{window_name} {index + 1}' # if index else window_name self.__window_name = menu_label if index else window_name self.__window = None self.__menu_entry = None self.__action_name = None Workspace.set_show_window_fn(self.__window_name, lambda b: self.__show_window(None, b)) if open_window: Workspace.show_window(self.__window_name) # add actions self.__action_name = register_actions("omni.kit.viewport.window", index, self.__show_window, self.__is_window_visible) # add menu if self.__action_name: self.__menu_entry = [ MenuItemDescription(name="Viewport", sub_menu= [MenuItemDescription( name=f"{menu_label}", ticked=True, ticked_fn=self.__is_window_visible, onclick_action=("omni.kit.viewport.window", self.__action_name), )] ) ] omni.kit.menu.utils.add_menu_items(self.__menu_entry, name="Window") def __del__(self): self.destroy() def destroy(self): if self.__window: Workspace.set_show_window_fn(self.__window_name, None) self.__window.set_visibility_changed_fn(None) self.__window.destroy() self.__window = None # remove menu if self.__menu_entry: omni.kit.menu.utils.remove_menu_items(self.__menu_entry, name="Window") # remove actions if self.__action_name: deregister_actions("omni.kit.viewport.window", self.__action_name) def __dock_window(self): if not self.__window: return settings = carb.settings.get_settings() if bool(settings.get("/app/docks/disabled")): return async def wait_for_window(window_name: str, dock_name: str, position: omni.ui.DockPosition, ratio: float = 1): dockspace = Workspace.get_window(dock_name) window = Workspace.get_window(window_name) if (window is None) or (dockspace is None): frames = 3 while ((window is None) or (dockspace is None)) and frames: await omni.kit.app.get_app().next_update_async() dockspace = Workspace.get_window(dock_name) window = Workspace.get_window(window_name) frames = frames - 1 if window and dockspace: # When docking to existing Viewport, preserve tab-visibility for both, otherwise defer to setting if position == omni.ui.DockPosition.SAME: dock_tab_bar_visible = not bool(settings.get(DEFAULT_VIEWPORT_HIDE_TAB)) else: dock_tab_bar_visible = dockspace.dock_tab_bar_visible window.deferred_dock_in(dock_name) # Split the tab to the right if position != omni.ui.DockPosition.SAME: await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() window.dock_in(dockspace, position, ratio) # This genrally works in a variety of cases from load, re-load, and save extesnion .py file reload # But it depends on a call order in omni.ui and registered selected_in_dock and dock_changed callbacks. await omni.kit.app.get_app().next_update_async() updates_enabled = window.selected_in_dock if window.docked else window.visible window.viewport_api.updates_enabled = updates_enabled # Set the dock-tab visible to the state of the default Viewport window.dock_tab_bar_visible = dock_tab_bar_visible dockspace.dock_tab_bar_visible = dock_tab_bar_visible import asyncio if self.__window_name == 'Viewport': asyncio.ensure_future(wait_for_window(self.__window_name, 'Viewport', omni.ui.DockPosition.SAME)) else: asyncio.ensure_future(wait_for_window(self.__window_name, 'Viewport', omni.ui.DockPosition.RIGHT, 0.5)) def __show_window(self, menu, visible): if visible: if not self.__window: def visiblity_changed(visible): if not visible: self.__show_window(None, False) self.__window = ViewportWindow(self.__window_name) self.__window.set_visibility_changed_fn(visiblity_changed) self.__dock_window() self.__window.visible = True elif self.__window: # For now just hide the Window. May want to add a setting for a full destroy-rebuild cycle, but now # that won't work well with the get_frame API. if True: self.__window.visible = False else: self.__window.set_visibility_changed_fn(None) self.__window.destroy() self.__window = None omni.kit.menu.utils.refresh_menu_items("Window") def __is_window_visible(self) -> bool: return False if self.__window is None else self.__window.visible class ViewportWindowExtension(omni.ext.IExt): """The Entry Point for Viewport Window """ def __init__(self): self.__registered = None self.__vp_items = None super().__init__() self.__extension_enabled_hooks = [] self.__extension_dependent_scenes = {} def on_startup(self, extension_id: str): settings = carb.settings.get_settings() default_name = settings.get(DEFAULT_VIEWPORT_NAME) or 'Viewport' self.__vp_items = ( _MenuEntry(default_name, not bool(settings.get(DEFAULT_VIEWPORT_NO_OPEN)), 0), ) if True: self.__vp_items = ( self.__vp_items[0], _MenuEntry(f'{default_name}', False, 1), ) self.__registered = self.__register_scenes() self.__default_drag_handlers = ( UsdFileDropDelegate('/persistent/app/viewport/previewOnPeek'), UsdShadeDropDelegate(), MaterialFileDropDelegate(), AudioFileDropDelegate() ) def on_shutdown(self): self.__extension_enabled_hooks = [] for vp_entry in (self.__vp_items or ()): vp_entry.destroy() self.__vp_items = None self.__default_drag_handlers = None if self.__extension_dependent_scenes: self.__unregister_scenes(self.__extension_dependent_scenes.values()) self.__extension_dependent_scenes = None if self.__registered: self.__unregister_scenes(self.__registered) self.__registered = None from .events import set_ui_delegate set_ui_delegate(None) def __register_ext_dependent_scene(self, ext_name: str, loaded_exts: List[Dict], ext_manager: omni.ext.ExtensionManager, factory_dict: Dict, other_factories: Optional[Dict] = None): def is_extension_loaded(ext_name: str) -> bool: for ext in loaded_exts: if ext_name == omni.ext.get_extension_name(ext['id']): return ext['enabled'] def extension_loaded(ext_id: str, log_msg_str: str = "Removing"): nonlocal ext_name # UnRegister existing first if other_factories: carb.log_info(f'{log_msg_str} embedded ui.scenes fallbacks for "{ext_name}"') for factory_id, factory in other_factories.items(): self.__extension_dependent_scenes[factory_id] = None # Register new scene types second carb.log_info(f'Adding ui.scenes dependent on "{ext_name}"') from omni.kit.viewport.registry import RegisterScene self.__extension_dependent_scenes[ext_name] = [ RegisterScene(factory, factory_id) for factory_id, factory in factory_dict.items() ] def extension_unloaded(ext_id: str): nonlocal ext_name # UnRegister scenes dependeing on extension first if self.__extension_dependent_scenes.get(ext_name): carb.log_info(f'Removing ui.scenes dependent on "{ext_name}"') self.__extension_dependent_scenes[ext_name] = None # Register replacement scene types second if other_factories: carb.log_info(f'Adding embedded ui.scenes fallbacks for "{ext_name}"') from omni.kit.viewport.registry import RegisterScene for factory_id, factory in other_factories.items(): self.__extension_dependent_scenes[factory_id] = RegisterScene(factory, factory_id) if not is_extension_loaded(ext_name): carb.log_info(f'{ext_name} is not loaded, adding extension enabled hooks') self.__extension_enabled_hooks += [ ext_manager.subscribe_to_extension_enable( extension_loaded, extension_unloaded, ext_name=ext_name, hook_name="omni.kit.viewport.window-ext_name" ) ] if other_factories: extension_unloaded(ext_name) else: extension_loaded(ext_name, "Ignoring") def __register_scenes(self): # Register all of the items that use omni.ui.scene to add functionality from omni.kit.viewport.registry import RegisterScene, RegisterViewportLayer app = omni.kit.app.get_app_interface() ext_mgr = app.get_extension_manager() exts_loaded = ext_mgr.get_extensions() registered = [] # Register the Camera manipulator (if available) def delay_load_cam_manip(*args, **kwargs): from .manipulator.camera import ViewportCameraManiulatorFactory return ViewportCameraManiulatorFactory(*args, **kwargs) self.__register_ext_dependent_scene('omni.kit.manipulator.camera', exts_loaded, ext_mgr, { 'omni.kit.viewport.window.manipulator.Camera': delay_load_cam_manip, }) # Register the Selection manipulator (if available) def delay_load_selection_manip(*args, **kwargs): from .manipulator.selection import SelectionManipulatorItem return SelectionManipulatorItem(*args, **kwargs) self.__register_ext_dependent_scene('omni.kit.manipulator.selection', exts_loaded, ext_mgr, { 'omni.kit.viewport.window.manipulator.Selection': delay_load_selection_manip, }) # Register the legacy Gizmo drawing (if available) or the omni.ui.scene version when not from .scene.legacy import LegacyGridScene, LegacyLightScene, LegacyAudioScene from .scene.scenes import SimpleGrid self.__register_ext_dependent_scene("omni.kit.viewport.legacy_gizmos", exts_loaded, ext_mgr, { 'omni.kit.viewport.window.scene.LegacyGrid': LegacyGridScene, 'omni.kit.viewport.window.scene.LegacyLight': LegacyLightScene, 'omni.kit.viewport.window.scene.LegacyAudio': LegacyAudioScene, }, { 'omni.kit.viewport.window.scene.SimpleGrid': SimpleGrid }) # Register other omni.scene.ui elements from .scene.scenes import SimpleGrid, SimpleOrigin, CameraAxisLayer registered = [ RegisterScene(SimpleOrigin, 'omni.kit.viewport.window.scene.SimpleOrigin'), RegisterViewportLayer(CameraAxisLayer, 'omni.kit.viewport.window.CameraAxisLayer') ] # Register the context click menu from .manipulator.context_menu import ViewportClickFactory registered += [ RegisterScene(ViewportClickFactory, 'omni.kit.viewport.window.manipulator.ContextMenu') ] # Register the Object click manipulator from .manipulator.object_click import ObjectClickFactory registered += [ RegisterScene(ObjectClickFactory, 'omni.kit.viewport.window.manipulator.ObjectClick') ] # Register the HUD stats from .stats import ViewportStatsLayer registered.append(RegisterViewportLayer(ViewportStatsLayer, 'omni.kit.viewport.window.ViewportStats')) # Finally register the ViewportSceneLayer from .scene.layer import ViewportSceneLayer registered.append(RegisterViewportLayer(ViewportSceneLayer, 'omni.kit.viewport.window.SceneLayer')) return registered def __unregister_scenes(self, registered): for item in registered: try: item.destroy() except Exception: pass
14,266
Python
42.898461
126
0.614678
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/__init__.py
from .extension import ViewportWindowExtension # Expose our public classes for from omni.kit.viewport.window import ViewportWindow __all__ = ['ViewportWindow'] from .window import ViewportWindow get_viewport_window_instances = ViewportWindow.get_instances set_viewport_window_default_style = ViewportWindow.set_default_style
327
Python
35.444441
83
0.82263
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/legacy.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = [] import carb from functools import partial from typing import Any, Optional def _resolve_viewport_setting(viewport_id: str, setting_name: str, isettings: carb.settings.ISettings, legacy_key: Optional[str] = None, set_per_vp_value: bool = False, default_if_not_found: Any = None, usd_context_name: Optional[str] = None): # Resolve a default Viewport setting from the most specific to the most general # /app/viewport/usd_context_name/setting => Global signal that overrides any other (for state dependent on stage) # /persistent/app/viewport/Viewport/Viewport0/setting => Saved setting for this specific Viewport # /app/viewport/Viewport/Viewport0/setting => Startup value for this specific Viewport # /app/viewport/defaults/setting => Startup value targetting all Viewports setting_key = f"/app/viewport/{viewport_id}/{setting_name}" persistent_key = "/persistent" + setting_key # Return values may push the setting to persistent storage if not there already def maybe_set_persistent_and_return(value): # Set to persitent storage if requested if set_per_vp_value: isettings.set(persistent_key, value) # Set to global storage if requested if usd_context_name is not None: isettings.set(f"/app/viewport/usdcontext-{usd_context_name}/{setting_name}", value) return value # Initial check if the setting is actually global to all Viewports on a UsdContext if usd_context_name is not None: value = isettings.get(f"/app/viewport/usdcontext-{usd_context_name}/{setting_name}") if value is not None: usd_context_name = None # No need to set back to the setting that was just read return maybe_set_persistent_and_return(value) # First check if there is a persistent value stored in the preferences value = isettings.get(persistent_key) if value is not None: return maybe_set_persistent_and_return(value) # Next check if a non-persitent viewport-specific default exists via toml / start-up settings value = isettings.get(setting_key) if value is not None: return maybe_set_persistent_and_return(value) # Next check if a non-persitent global default exists via toml / start-up settings value = isettings.get(f"/app/viewport/defaults/{setting_name}") if value is not None: return maybe_set_persistent_and_return(value) # Finally check if there exists a legacy key to specify the startup value if legacy_key: value = isettings.get(legacy_key) if value is not None: return maybe_set_persistent_and_return(value) if default_if_not_found is not None: value = maybe_set_persistent_and_return(default_if_not_found) return value def _setup_viewport_options(viewport_id: str, usd_context_name: str, isettings: carb.settings.ISettings): legacy_display_options_key: str = "/persistent/app/viewport/displayOptions" force_hide_fps_key: str = "/app/viewport/forceHideFps" show_layer_menu_key: str = "/app/viewport/showLayerMenu" # Map legacy bitmask values to new per-viewport keys: new_key: (bitmask, legacy_setting, is_usd_global) persitent_to_legacy_map = { "hud/renderFPS/visible": (1 << 0, None, False), "guide/axis/visible": (1 << 1, None, False), "hud/renderResolution/visible": (1 << 3, None, False), "scene/cameras/visible": (1 << 5, "/app/viewport/show/camera", True), "guide/grid/visible": (1 << 6, "/app/viewport/grid/enabled", False), "guide/selection/visible": (1 << 7, "/app/viewport/outline/enabled", False), "scene/lights/visible": (1 << 8, "/app/viewport/show/lights", True), "scene/skeletons/visible": (1 << 9, None, True), "scene/meshes/visible": (1 << 10, None, True), "hud/renderProgress/visible": (1 << 11, None, False), "scene/audio/visible": (1 << 12, "/app/viewport/show/audio", True), "hud/deviceMemory/visible": (1 << 13, None, False), "hud/hostMemory/visible": (1 << 14, None, False), } # Build some handlers to keep legacy displayOptions in sync with the new per-viewport settings # Used as nonlocal/global in legacy_display_options_changed to check for bits toggled # When no legacy displayOptions exists, we do not want to create it as set_default would do legacy_display_options: int = isettings.get(legacy_display_options_key) if legacy_display_options is None: legacy_display_options = 32255 # Handles changes to legacy displayOptions (which are global to all viewports) and push them to our single Viewport def legacy_display_options_changed(item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type != carb.settings.ChangeEventType.CHANGED: return nonlocal legacy_display_options isettings = carb.settings.get_settings() # Get the previous and current displayOptions prev_display_options, current_display_options = legacy_display_options, isettings.get(legacy_display_options_key) or 0 # If they match, nothing has changed so just exit if prev_display_options == current_display_options: return # Save the current state for comparison on next change legacy_display_options = current_display_options # Check for any bit changes to toggle/store into the per-viepwort key def check_bit_toggled(legacy_bitmask: int): cur_vis = bool(current_display_options & legacy_bitmask) return bool(prev_display_options & legacy_bitmask) != cur_vis, cur_vis # Check if a legacy bit was flipped, and if so store it's current state into per-viewport and stage-global # state if they are not already set to the same value. def toggle_per_viewport_setting(legacy_bitmask: int, setting_key: str, secondary_key: Optional[str] = None): toggled, visible = check_bit_toggled(legacy_bitmask) if toggled: # legacy displayOption was toggled, if it is not already matching the viewport push it there vp_key = f"/persistent/app/viewport/{viewport_id}/{setting_key}" if visible != bool(isettings.get(vp_key)): isettings.set(vp_key, visible) if secondary_key: if visible != bool(isettings.get(secondary_key)): isettings.set(secondary_key, visible) return visible for setting_key, legacy_obj in persitent_to_legacy_map.items(): # Settings may have had a displayOptions bit that was serialzed, but controlled via another setting legacy_bitmask, secondary_key, is_usd_state = legacy_obj visible = toggle_per_viewport_setting(legacy_bitmask, setting_key, secondary_key) # Store to global are if the setting represent UsdStage that must be communicated across Viewports if is_usd_state: usd_key = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}" if visible != bool(isettings.get(usd_key)): isettings.set(usd_key, visible) def legacy_value_changed(setting_key: str, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type != carb.settings.ChangeEventType.CHANGED: return legacy_obj = persitent_to_legacy_map.get(setting_key) if not legacy_obj: carb.log_error("No mapping for '{setting_key}' into legacy setting") return None isettings = carb.settings.get_settings() legacy_key, is_stage_global = legacy_obj[1], legacy_obj[2] per_viewport_key = f"/persistent/app/viewport/{viewport_id}/{setting_key}" viewport_show = bool(isettings.get(per_viewport_key)) legacy_show = bool(isettings.get(legacy_key)) if legacy_show != viewport_show: isettings.set(per_viewport_key, legacy_show) if is_stage_global: usd_key = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}" if legacy_show != bool(isettings.get(usd_key)): isettings.set(usd_key, legacy_show) def subscribe_to_legacy_obj(setting_key: str, isettings): legacy_obj = persitent_to_legacy_map.get(setting_key) if legacy_obj and legacy_obj[1]: return isettings.subscribe_to_node_change_events(legacy_obj[1], partial(legacy_value_changed, setting_key)) carb.log_error("No mapping for '{setting_key}' into legacy setting") return None def global_value_changed(setting_key: str, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type != carb.settings.ChangeEventType.CHANGED: return legacy_obj = persitent_to_legacy_map.get(setting_key) if not legacy_obj: carb.log_error("No mapping for '{setting_key}' into legacy setting") return None # Simply forwards the global setting to all Viewport instances attached to this UsdContext isettings = carb.settings.get_settings() global_visible = isettings.get(f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}") per_viewport_key = f"/persistent/app/viewport/{viewport_id}/{setting_key}" legacy_key = legacy_obj[1] # Push global stage state into legacy global key state (that may be watched by other consumers) if legacy_key: legacy_show = bool(isettings.get(legacy_key)) if legacy_show != global_visible: isettings.set(legacy_key, global_visible) # Push global stage state into per-viewport state if global_visible != bool(isettings.get(per_viewport_key)): isettings.set(per_viewport_key, global_visible) # XXX: Special case skeletons because that is handled externally and still tied to displayOptions # if setting_key == "scene/skeletons/visible": # display_options = isettings.get(legacy_display_options_key) # # If legacy display options is None, then it is not set at all: assume application doesnt want them at all # if display_options is not None: # legacy_bitmask = (1 << 9) # Avoid persitent_to_legacy_map.get(setting_key)[0], already know the bitmask # if global_visible != bool(display_options & legacy_bitmask): # display_options = display_options | (1 << 9) # isettings.set(legacy_display_options_key, display_options) # else: # carb.log_warn(f"{legacy_display_options_key} is unset, assuming application does not want it") def subscribe_to_global_obj(setting_key: str, isettings): legacy_obj = persitent_to_legacy_map.get(setting_key) if legacy_obj and legacy_obj[2]: global_key = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}" return isettings.subscribe_to_node_change_events(global_key, partial(global_value_changed, setting_key)) carb.log_error("No mapping for '{setting_key}' into global stage setting") return None for setting_key, legacy_obj in persitent_to_legacy_map.items(): legacy_bitmask, legacy_key, is_usd_state = legacy_obj legacy_visible = bool(legacy_display_options & legacy_bitmask) visible = _resolve_viewport_setting(viewport_id, setting_key, isettings, legacy_key, True, legacy_visible, usd_context_name=usd_context_name if is_usd_state else None) if legacy_key: legacy_value = isettings.get(legacy_key) if (legacy_value is None) or (legacy_value != visible): isettings.set(legacy_key, visible) # Now take the full resolved 'visible' value and push back into the cached legacy_display_options bitmask. # This is so that any errant extension that still sets to displayOptions will trigger a global toggle # of the setting for all Viewports if legacy_visible != visible: if visible: legacy_display_options = legacy_display_options | legacy_bitmask else: legacy_display_options = legacy_display_options & ~legacy_bitmask # Global HUD visibility: first resolve to based on new persitent per-viewport and its defaults _resolve_viewport_setting(viewport_id, "hud/visible", isettings, None, True, True) return ( isettings.subscribe_to_node_change_events(legacy_display_options_key, legacy_display_options_changed), # Subscriptions to manage legacy drawing state across all Viewports subscribe_to_legacy_obj("guide/grid/visible", isettings), subscribe_to_legacy_obj("guide/selection/visible", isettings), subscribe_to_legacy_obj("scene/cameras/visible", isettings), subscribe_to_legacy_obj("scene/lights/visible", isettings), subscribe_to_legacy_obj("scene/audio/visible", isettings), # Subscriptions to manage UsdStage state across Viewports sharing a UsdContext subscribe_to_global_obj("scene/cameras/visible", isettings), subscribe_to_global_obj("scene/lights/visible", isettings), subscribe_to_global_obj("scene/skeletons/visible", isettings), subscribe_to_global_obj("scene/meshes/visible", isettings), subscribe_to_global_obj("scene/audio/visible", isettings), )
14,075
Python
53.138461
126
0.665506
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/raycast.py
# Copyright (c) 2021-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 typing import Sequence, Callable import carb USE_RAYCAST_SETTING = "/exts/omni.kit.viewport.window/useRaycastQuery" def perform_raycast_query( viewport_api: "ViewportAPI", mouse_ndc: Sequence[float], mouse_pixel: Sequence[float], on_complete_fn: Callable, query_name: str = "" ): raycast_success = False if ( viewport_api.hydra_engine == "rtx" and carb.settings.get_settings().get(USE_RAYCAST_SETTING) ): try: import omni.kit.raycast.query as rq def rtx_query_complete(ray, result: "RayQueryResult", *args, **kwargs): prim_path = result.get_target_usd_path() if result.valid: world_space_pos = result.hit_position else: world_space_pos = (0, 0, 0) on_complete_fn(prim_path, world_space_pos, *args, **kwargs) rq.utils.raycast_from_mouse_ndc( mouse_ndc, viewport_api, rtx_query_complete ) raycast_success = True except: pass if not raycast_success: viewport_api.request_query( mouse_pixel, on_complete_fn, query_name=query_name )
1,718
Python
30.254545
83
0.61234
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/layers.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportLayers'] from .legacy import _resolve_viewport_setting from omni.kit.viewport.registry import RegisterViewportLayer from omni.kit.widget.viewport import ViewportWidget from omni.kit.widget.viewport.api import ViewportAPI import omni.ui as ui import omni.timeline import omni.usd import carb from pxr import Usd, Sdf import traceback from typing import Callable, Optional import weakref kLayerOrder = [ 'omni.kit.viewport.window.ViewportLayer', 'omni.kit.viewport.window.SceneLayer', 'omni.kit.viewport.menubar.MenuBarLayer' ] # Class to wrap the underlying omni.kit.widget.viewport.ViewportWidget into the layer-system class _ViewportLayerItem: def __init__(self, viewport): self.__viewport = viewport @property def visible(self): return self.__viewport.visible @visible.setter def visible(self, value): self.__viewport.visible = bool(value) # TODO: Would be nice to express AOV's as more controllable items @property def name(self): return 'Render (color)' @property def layers(self): return tuple() @property def categories(self): return ('viewport',) def destroy(self): # Respond to destroy, but since this doesn't own the underlying viewport, don't forward to it pass # Since we're exposing ourself in the 'viewport' category expose the .viewport_api getter @property def viewport_api(self): return self.__viewport.viewport_api class ViewportLayers: """The Viewport Layers Widget Holds a single viewport and manages the order of layers within a ui.ZStack """ # For convenience and access, promote the underlying viewport api to this widget @property def viewport_api(self): return self.__viewport.viewport_api if self.__viewport else None @property def viewport_widget(self): return weakref.proxy(self.__viewport) @property def layers(self): for layer in self.__viewport_layers.values(): yield layer def get_frame(self, name: str): carb.log_error("ViewportLayers.get_frame called but parent has not provided an implementation.") def __init__(self, viewport_id: str, usd_context_name: str = '', get_frame_parent: Optional[Callable] = None, hydra_engine_options: Optional[dict] = None, *ui_args, **ui_kwargs): self.__viewport_layers = {} self.__ui_frame = None self.__viewport = None self.__zstack = None self.__timeline = omni.timeline.get_timeline_interface() self.__timeline_sub = self.__timeline.get_timeline_event_stream().create_subscription_to_pop(self.__on_timeline_event) if get_frame_parent: self.get_frame = get_frame_parent isettings = carb.settings.get_settings() # If no resolution specified, see if a knnown setting exists to use as an initial value # This is a little complicated due to serialization but also preservation of legacy global defaults resolution = _resolve_viewport_setting(viewport_id, 'resolution', isettings) # If no -new- resolution setting was resolved, check against legacy setting if resolution is None: width = isettings.get('/app/renderer/resolution/width') height = isettings.get('/app/renderer/resolution/height') # Both need to be set and valid to be used if (width is not None) and (height is not None): # When either width or height is 0 or less, Viewport will be set to use UI size if (width > 0) and (height > 0): resolution = (width, height) else: resolution = 'fill_frame' # Also resolve any resolution scaling to use for the Viewport res_scale = _resolve_viewport_setting(viewport_id, 'resolutionScale', isettings, '/app/renderer/resolution/multiplier') # Our 'frame' is really a Z-Stack so that we can push another z-stack on top of the render self.__ui_frame = ui.ZStack(*ui_args, **ui_kwargs) with self.__ui_frame: ui.Rectangle(style_type_name_override='ViewportBackgroundColor') self.__viewport = ViewportWidget(usd_context_name, resolution=resolution, viewport_api=ViewportAPI(usd_context_name, viewport_id, self.__viewport_updated), hydra_engine_options=hydra_engine_options) # Apply the resolution scaling now that the Viewport exists if res_scale is not None: self.__viewport.viewport_api.resolution_scale = res_scale # Expose the viewport itself into the layer system (factory is the key, so use the contructor) self.__viewport_layers[_ViewportLayerItem] = _ViewportLayerItem(weakref.proxy(self.__viewport)) # Now add the notification which will be called for all layers already registered and any future ones. RegisterViewportLayer.add_notifier(self.__viewport_layer_event) def __viewport_updated(self, camera_path: Sdf.Path, stage: Usd.Stage): if not self.__viewport: return # Get the current time-line time and push that to the Viewport if stage: time = self.__timeline.get_current_time() time = Usd.TimeCode(omni.usd.get_frame_time_code(time, stage.GetTimeCodesPerSecond())) else: time = Usd.TimeCode.Default() # Push the time, and let the Viewport handle any view-changed notifications self.__viewport._viewport_changed(camera_path, stage, time) def __on_timeline_event(self, e: carb.events.IEvent): if self.__viewport: event_type = e.type if (event_type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED)): viewport_api = self.__viewport.viewport_api self.__viewport_updated(viewport_api.camera_path, viewport_api.stage) def __viewport_layer_event(self, factory, loading): if loading: # A layer was registered # Preserve the 'ViewportLayer' in our dictionary vp_layer = self.__viewport_layers[_ViewportLayerItem] del self.__viewport_layers[_ViewportLayerItem] for instance in self.__viewport_layers.values(): instance.destroy() self.__viewport_layers = {_ViewportLayerItem: vp_layer} # Create the factory argument factory_args = { 'usd_context_name': self.viewport_api.usd_context_name, 'layer_provider': weakref.proxy(self), 'viewport_api': self.viewport_api } # Clear out the old stack if self.__zstack: self.__zstack.destroy() self.__zstack.clear() with self.__ui_frame: self.__zstack = ui.ZStack() # Rebuild all the other layers according to our order for factory_id, factory in RegisterViewportLayer.ordered_factories(kLayerOrder): # Skip over things that weren't found (they may have not been registered or enabled yet) if not factory: continue with self.__zstack: try: self.__viewport_layers[factory] = factory(factory_args.copy()) except Exception: carb.log_error(f"Error creating layer {factory}. Traceback:\n{traceback.format_exc()}") else: if factory in self.__viewport_layers: self.__viewport_layers[factory].destroy() del self.__viewport_layers[factory] else: carb.log_error(f'Removing {factory} which was never instantiated') def __del__(self): self.destroy() def destroy(self): self.__timeline_sub = None RegisterViewportLayer.remove_notifier(self.__viewport_layer_event) for factory, instance in self.__viewport_layers.items(): instance.destroy() self.__viewport_layers = {} if self.__zstack: self.__zstack.destroy() self.__zstack = None if self.__viewport: self.__viewport.destroy() self.__viewport = None if self.__ui_frame: self.__ui_frame.destroy() self.__ui_frame = None self.get_frame = None self.__timeline = None
9,230
Python
39.845133
126
0.613759
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/viewport_actions.py
import omni.kit.actions.core from typing import Callable, Optional def register_actions(extension_id: str, index: int, show_fn: Callable, visible_fn: Callable) -> Optional[str]: action_registry = omni.kit.actions.core.get_action_registry() if not action_registry: return None action_name = f"show_viewport_window_{index + 1}" action_registry.register_action( extension_id, action_name, lambda: show_fn(None, not visible_fn()), display_name="Viewport show/hide window", description="Viewport show/hide window", tag="Viewport Actions", ) return action_name def deregister_actions(extension_id: str, action_name: str) -> None: action_registry = omni.kit.actions.core.get_action_registry() if action_registry: action_registry.deregister_action(extension_id, action_name)
868
Python
32.423076
110
0.685484
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/window.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportWindow'] import weakref import omni.ui as ui import carb.settings from typing import Callable, Optional, Sequence import contextlib class ViewportWindow(ui.Window): __APP_WINDOW_HIDE_UI = "/app/window/hideUi" __GAMEPAD_CONTROL = "/persistent/app/omniverse/gamepadCameraControl" __OBJECT_CENTRIC = "/persistent/app/viewport/objectCentricNavigation" __DOUBLE_CLICK_COI = "/persistent/app/viewport/coiDoubleClick" active_window: Optional[weakref.ProxyType] = None """The Viewport Window, simple window holding a ViewportLayers widget""" def __init__(self, name: str | None = None, usd_context_name: str = '', width: int = None, height: int = None, flags: int = None, style: dict = None, usd_drop_support: bool = True, hydra_engine_options: Optional[dict] = None, *ui_args, **ui_kw_args): """ViewportWindow contructor Args: name (str): The name of the Window. usd_context_name (str): The name of a UsdContext this Viewport will be viewing. width(int): The width of the Window. height(int): The height of the Window. flags(int): ui.WINDOW flags to use for the Window. style (dict): Optional style overrides to apply to the Window's frame. *args, **kwargs: Additional arguments to pass to omni.ui.Window """ resolved_args = ViewportWindow.__resolve_window_args(width, height, flags) if resolved_args: ui_kw_args.update(resolved_args) settings = carb.settings.get_settings() # Create a default Window name if none is provided # 1. Pull the setting for default-window name # 2. Format with key usd_context_name=usd_context_name # 3. If format leads to the same name as default-window, append ' (usd_context_name)' # if name is None: name = settings.get("/exts/omni.kit.viewport.window/startup/windowName") or "Viewport" if usd_context_name: fmt_name = name.format(usd_context_name=usd_context_name) if fmt_name == name: name += f" ({usd_context_name})" else: name = fmt_name super().__init__(name, *ui_args, **ui_kw_args) self.__name = name self.__external_drop_support = None self.__added_frames = {} self.__setting_subs: Sequence[carb.settings.SubscriptionId] = tuple() self.__hide_ui_state = None self.__minimize_window_sub = None self.set_selected_in_dock_changed_fn(self.__selected_in_dock_changed) self.set_docked_changed_fn(self.__dock_changed) self.set_focused_changed_fn(self.__focused_changed) # Window takes focus on any mouse down self.focus_policy = ui.FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN # Make a simple style and update it with user provided values if provided applied_style = ViewportWindow.__g_default_style if style: applied_style = applied_style.copy() applied_style.update(style) self.set_style(applied_style) legacy_display_subs: Optional[Sequence[carb.settings.SubscriptionId]] = None # Basic Frame for the Viewport from .layers import ViewportLayers from .legacy import _setup_viewport_options with self.frame: self.__z_stack = ui.ZStack() with self.__z_stack: # Currently ViewportWindow only has/supports one embedded ViewportWidget, but give it a unique name # that will co-operate if that ever changes. viewport_id = f"{name}/Viewport0" # Setup the mapping from legacy displayOptions to the persistent viewport settings legacy_display_subs = _setup_viewport_options(viewport_id, usd_context_name, settings) self.__viewport_layers = ViewportLayers(viewport_id=viewport_id, usd_context_name=usd_context_name, get_frame_parent=self.get_frame, hydra_engine_options=hydra_engine_options) # Now Viewport & Layers are completely built, if the VP has a stage attached, force a sync when omni.ui does # layout. This works around an issue where the Viewport frame's computed-size notification may not be pushed. self.frame.set_build_fn(self.__frame_built) if usd_drop_support: self.add_external_drag_drop_support() ViewportWindow.__g_instances.append(weakref.proxy(self, ViewportWindow.__clean_instances)) self.__setting_subs = ( # Watch for hideUi notification to toggle visible items settings.subscribe_to_node_change_events(ViewportWindow.__APP_WINDOW_HIDE_UI, self.__hide_ui), # Watch for global gamepad enabled change settings.subscribe_to_node_change_events(ViewportWindow.__GAMEPAD_CONTROL, self.__set_gamepad_enabled), # Watch for global object centric movement changes settings.subscribe_to_node_change_events(ViewportWindow.__OBJECT_CENTRIC, self.__set_object_centric), # Watch for global double click-to-orbit settings.subscribe_to_node_change_events(ViewportWindow.__DOUBLE_CLICK_COI, self.__set_double_click_coi), ) # Store any additional legacy_disply_sub subscription here if legacy_display_subs: self.__setting_subs = self.__setting_subs + legacy_display_subs self.__minimize_window_sub = self.app_window.get_window_minimize_event_stream().create_subscription_to_push( self.__on_minimized, name=f'omni.kit.viewport.window.minimization_subscription.{self}' ) self.__set_gamepad_enabled() self.__set_object_centric() self.__set_double_click_coi() def __on_minimized(self, event: carb.events.IEvent = None, *args, **kwargs): if carb.settings.get_settings().get('/app/renderer/skipWhileMinimized'): # If minimized, always stop rendering. # If not minimized, restore rendering based on window docked and selected in doock or visibility if event.payload.get('isMinimized', False): self.viewport_api.updates_enabled = False elif self.docked: self.viewport_api.updates_enabled = self.selected_in_dock else: self.viewport_api.updates_enabled = self.visible def __focused_changed(self, focused: bool): if not focused: return prev_active, ViewportWindow.active_window = ViewportWindow.active_window, weakref.proxy(self) with contextlib.suppress(ReferenceError): if prev_active: if prev_active == self: return prev_active.__set_gamepad_enabled(force_off=True) self.__set_gamepad_enabled() @staticmethod def __resolve_window_args(width, height, flags): settings = carb.settings.get_settings() hide_ui = settings.get(ViewportWindow.__APP_WINDOW_HIDE_UI) if width is None and height is None: width = settings.get("/app/window/width") height = settings.get("/app/window/height") # If above settings are not set but using hideUi, set to fill main window if hide_ui and (width is None) and (height is None): width = ui.Workspace.get_main_window_width() height = ui.Workspace.get_main_window_height() # If still none, use some sane default values if width is None and height is None: width, height = (1280, 720 + 20) if flags is None: flags = ui.WINDOW_FLAGS_NO_SCROLLBAR # Additional flags to fill main-window when hideUi is in use if hide_ui: flags |= ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_NO_TITLE_BAR ui_args = { 'width': width, 'height': height, 'flags': flags, # Viewport is changing every frame. We can't raster it. 'raster_policy': ui.RasterPolicy.NEVER, } if hide_ui or settings.get("/persistent/app/viewport/noPadding"): ui_args['padding_x'], ui_args['padding_y'] = (0, 0) return ui_args @property def name(self): return self.__name @property def viewport_api(self): return self.__viewport_layers.viewport_api if self.__viewport_layers else None @property def viewport_widget(self): return self.__viewport_layers.viewport_widget if self.__viewport_layers else None def set_style(self, style): self.frame.set_style(style) @ui.Window.visible.setter def visible(self, visible: bool): ui.Window.visible.fset(self, visible) viewport_api = self.viewport_api if viewport_api: if visible: viewport_api.updates_enabled = True elif carb.settings.get_settings().get("/app/renderer/skipWhileInvisible"): viewport_api.updates_enabled = False def add_external_drag_drop_support(self, callback_fn: Callable = None): # Remove any previously registered support prev_callback = self.remove_external_drag_drop_support() # If no user supplied function, use the default to open a usd file if callback_fn is None: callback_fn = self.__external_drop try: from omni.kit.window.drop_support import ExternalDragDrop self.__external_drop_support = ExternalDragDrop(window_name=self.name, drag_drop_fn=callback_fn) return prev_callback except ImportError: import carb carb.log_info('Enable omni.kit.window.drop_support for external drop support') return False def remove_external_drag_drop_support(self): if self.__external_drop_support: prev_callback = self.__external_drop_support._drag_drop_fn self.__external_drop_support.destroy() self.__external_drop_support = None return prev_callback def get_frame(self, name: str): frame = self.__added_frames.get(name) if frame is None: with self.__z_stack: frame = ui.Frame(horizontal_clipping=True) self.__added_frames[name] = frame return frame def _find_viewport_layer(self, layer_id: str, category: str = None, layers=None): def recurse_layers(layer): if layer_id == getattr(layer, 'name', None): if (category is None) or (category in getattr(layer, 'categories', tuple())): return layer for child_layer in getattr(layer, 'layers', tuple()): found_layer = recurse_layers(child_layer) if found_layer: return found_layer return recurse_layers(layers or self.__viewport_layers) def _post_toast_message(self, message: str, message_id: str = None): msg_layer = self._find_viewport_layer('Toast Message', 'stats') if msg_layer: msg_layer.add_message(message, message_id) def __del__(self): self.destroy() def destroy(self): self.remove_external_drag_drop_support() self.set_selected_in_dock_changed_fn(None) self.set_docked_changed_fn(None) self.set_focused_changed_fn(None) if self.__minimize_window_sub: self.__minimize_window_sub = None settings = carb.settings.get_settings() for setting_sub in self.__setting_subs: if setting_sub: settings.unsubscribe_to_change_events(setting_sub) self.__setting_subs = tuple() if self.__viewport_layers: self.__viewport_layers.destroy() self.__viewport_layers = None ViewportWindow.__clean_instances(None, self) if self.__z_stack: self.__z_stack.clear() self.__z_stack.destroy() self.__z_stack = None if self.__added_frames: for name, frame in self.__added_frames.items(): frame.destroy() self.__added_frames = None super().destroy() # Done last as it is the active ViewportWindow until replaced or fully destroyed with contextlib.suppress(ReferenceError): if ViewportWindow.active_window == self: ViewportWindow.active_window = None def __hide_ui(self, *args, **kwargs): class UiToggle: def __init__(self, window: ViewportWindow): self.__visible_layers = None self.__tab_visible = window.dock_tab_bar_enabled def __log_error(self, visible: bool, *args): import traceback carb.log_error(f"Error {'showing' if visible else 'hiding'} layer {args}. Traceback:\n{traceback.format_exc()}") def __set_visibility(self, window: ViewportWindow, visible: bool, layer_args): layers = set() try: for name, category in layer_args: layer = window._find_viewport_layer(name, category) if layer and getattr(layer, 'visible', visible) != visible: layer.visible = visible layers.add((name, category)) except Exception: self.__log_error(visible, name, category) return layers def hide_ui(self, window: ViewportWindow, hide_ui: bool): if hide_ui: if self.__visible_layers: return self.__visible_layers = self.__set_visibility(window, False, ( ("Axis", "guide"), ("Menubar", "menubar"), )) window.dock_tab_bar_enabled = False elif self.__visible_layers: visible_layers, self.__visible_layers = self.__visible_layers, None self.__set_visibility(window, True, visible_layers) window.dock_tab_bar_enabled = self.__tab_visible hide_ui = carb.settings.get_settings().get(ViewportWindow.__APP_WINDOW_HIDE_UI) if not self.__hide_ui_state: self.__hide_ui_state = UiToggle(self) self.__hide_ui_state.hide_ui(self, hide_ui) def __set_gamepad_enabled(self, *args, force_off: bool = False, **kwargs): if not force_off: # Get current global value enabled = carb.settings.get_settings().get(ViewportWindow.__GAMEPAD_CONTROL) # If gamepad set to on, only enable it for the active ViewportWindow if enabled: with contextlib.suppress(ReferenceError): if ViewportWindow.active_window and ViewportWindow.active_window != self: return else: enabled = False # Dig deep into some implementation details cam_manip_item = self._find_viewport_layer('Camera', 'manipulator') if not cam_manip_item: return cam_manip_layer = getattr(cam_manip_item, 'layer', None) if not cam_manip_layer: return cam_manipulator = getattr(cam_manip_layer, 'manipulator', None) if not cam_manipulator or not hasattr(cam_manipulator, 'gamepad_enabled'): return cam_manipulator.gamepad_enabled = enabled return def __set_object_centric(self, *args, **kwargs): settings = carb.settings.get_settings() value = settings.get(ViewportWindow.__OBJECT_CENTRIC) if value is not None: settings.set("/exts/omni.kit.manipulator.camera/objectCentric/type", value) def __set_double_click_coi(self, *args, **kwargs): settings = carb.settings.get_settings() value = settings.get(ViewportWindow.__DOUBLE_CLICK_COI) if value is not None: settings.set("/exts/omni.kit.viewport.window/coiDoubleClick", value) def __external_drop(self, edd, payload): import re import os import pathlib import omni.usd import omni.kit.undo import omni.kit.commands from pxr import Sdf, Tf default_prim_path = Sdf.Path("/") stage = omni.usd.get_context().get_stage() if stage.HasDefaultPrim(): default_prim_path = stage.GetDefaultPrim().GetPath() re_audio = re.compile(r"^.*\.(wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus)(\?.*)?$", re.IGNORECASE) re_usd = re.compile(r"^.*\.(usd|usda|usdc|usdz)(\?.*)?$", re.IGNORECASE) for source_url in edd.expand_payload(payload): if re_usd.match(source_url): try: import omni.kit.window.file omni.kit.window.file.open_stage(source_url.replace(os.sep, '/')) except ImportError: import carb carb.log_warn(f'Failed to import omni.kit.window.file - Cannot open stage {source_url}') return with omni.kit.undo.group(): for source_url in edd.expand_payload(payload): if re_audio.match(source_url): stem = pathlib.Path(source_url).stem path = default_prim_path.AppendChild(Tf.MakeValidIdentifier(stem)) omni.kit.commands.execute( "CreateAudioPrimFromAssetPath", path_to=path, asset_path=source_url, usd_context=omni.usd.get_context(), ) def __frame_built(self, *args, **kwargs): vp_api = self.__viewport_layers.viewport_api stage = vp_api.stage if vp_api else None if stage: vp_api.viewport_changed(vp_api.camera_path, stage) # ViewportWindow owns the hideUi state, so do it now self.__hide_ui() def __selected_in_dock_changed(self, is_selected): self.viewport_api.updates_enabled = is_selected if self.docked else True def __dock_changed(self, is_docked): self.viewport_api.updates_enabled = self.selected_in_dock if is_docked else True @staticmethod def set_default_style(style, overwrite: bool = False, usd_context_name: str = '', apply: bool = True): if overwrite: ViewportWindow.__g_default_style = style else: ViewportWindow.__g_default_style.update(style) if apply: # Apply the default to all intances of usd_context_name for instance in ViewportWindow.get_instances(usd_context_name): instance.set_style(ViewportWindow.__g_default_style) @staticmethod def get_instances(usd_context_name: str = ''): for instance in ViewportWindow.__g_instances: try: viewport_api = instance.viewport_api if not viewport_api: continue # None is the key for all ViewportWindows for all UsdContexts # Otherwise compare the provided UsdContext matches the Viewports if usd_context_name is None or usd_context_name == viewport_api.usd_context_name: yield instance except ReferenceError: pass @staticmethod def __clean_instances(dead, self=None): active = [] for p in ViewportWindow.__g_instances: try: if p and p != self: active.append(p) except ReferenceError: pass ViewportWindow.__g_instances = active __g_instances = [] __g_default_style = { 'ViewportBackgroundColor': { 'background_color': 0xff000000 }, 'ViewportStats::Root': { 'margin_width': 5, 'margin_height': 3, }, 'ViewportStats::Spacer': { 'margin': 18 }, 'ViewportStats::Group': { 'margin_width': 10, 'margin_height': 5, }, 'ViewportStats::Stack': { }, 'ViewportStats::Background': { 'background_color': ui.color(0.145, 0.157, 0.165, 0.8), 'border_radius': 5, }, 'ViewportStats::Label': { 'margin_height': 1.75, }, 'ViewportStats::LabelError': { 'margin_height': 1.75, 'color': 0xff0000ff }, 'ViewportStats::LabelWarning': { 'margin_height': 1.75, 'color': 0xff00ffff }, 'ViewportStats::LabelDisabled': { 'margin_height': 1.75, 'color': ui.color("#808080") } }
21,554
Python
41.264706
137
0.586712
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/stats/__init__.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportStatsLayer'] import omni.ui as ui from omni.ui import constant as fl from omni.gpu_foundation_factory import get_memory_info import carb import traceback import time from typing import Callable, Optional, Sequence import weakref from ..events.delegate import _limit_camera_velocity LOW_MEMORY_SETTING_PATH = '/persistent/app/viewport/memory/lowFraction' MEMORY_CHECK_FREQUENCY = '/app/viewport/memory/queryFrequency' RTX_SPP = '/rtx/pathtracing/spp' RTX_PT_TOTAL_SPP = '/rtx/pathtracing/totalSpp' RTX_ACCUMULATED_LIMIT = '/rtx/raytracing/accumulationLimit' RTX_ACCUMULATION_ENABLED = '/rtx/raytracing/enableAccumulation' IRAY_MAX_SAMPLES = '/rtx/iray/progressive_rendering_max_samples' TOAST_MESSAGE_KEY = '/app/viewport/toastMessage' CAM_SPEED_MESSAGE_KEY = '/exts/omni.kit.viewport.window/cameraSpeedMessage' HUD_MEM_TYPE_KEY = "/exts/omni.kit.viewport.window/hud/hostMemory/perProcess" HUD_MEM_NAME_KEY = "/exts/omni.kit.viewport.window/hud/hostMemory/label" _get_device_info = None def _human_readable_size(size: int, binary : bool = True, decimal_places: int = 1): def calc_human_readable(size, scale, *units): n_units = len(units) for i in range(n_units): if (size < scale) or (i == n_units): return f'{size:.{decimal_places}f} {units[i]}' size /= scale if binary: return calc_human_readable(size, 1024, 'B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB') return calc_human_readable(size, 1000, 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB') # XXX: Move to omni.kit.viewport.serialization def _resolve_hud_visibility(viewport_api, setting_key: str, isettings: carb.settings.ISettings, dflt_value: bool = True): # Resolve initial visibility based on persitent settings or app defaults visible_key = "/app/viewport/{vp_section}" + (f"/hud/{setting_key}/visible" if setting_key else "/hud/visible") vp_visible = visible_key.format(vp_section=viewport_api.id) setting_key = "/persistent" + vp_visible visible = isettings.get(setting_key) if visible is None: visible = isettings.get(vp_visible) if visible is None: visible = isettings.get(visible_key.format(vp_section="defaults")) if visible is None: visible = dflt_value # XXX: The application defaults need to get pushed into persistent data now (for display-menu) isettings.set_default(setting_key, visible) return (setting_key, visible) def _get_background_alpha(settings): bg_alpha = settings.get("/persistent/app/viewport/ui/background/opacity") return bg_alpha if bg_alpha is not None else 1.0 class ViewportStatistic: def __init__(self, stat_name: str, setting_key: str = None, parent = None, alignment: ui.Alignment=ui.Alignment.RIGHT, viewport_api = None): self.__stat_name = stat_name self.__labels = [] self.__alignment = alignment self.__ui_obj = self._create_ui(alignment) self.__subscription_id: Optional[carb.settings.SubscriptionId] = None self.__setting_key: Optional[str] = None if setting_key: settings = carb.settings.get_settings() self.__setting_key, self.visible = _resolve_hud_visibility(viewport_api, setting_key, settings) # Watch for per-viewport changes to persistent setting to control visibility self.__subscription_id = settings.subscribe_to_node_change_events( self.__setting_key, self._visibility_change ) self._visibility_change(None, carb.settings.ChangeEventType.CHANGED) def __del__(self): self.destroy() def _visibility_change(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: self.visible = bool(carb.settings.get_settings().get(self.__setting_key)) @property def container(self): return self.__ui_obj def _create_ui(self, alignment: ui.Alignment): return ui.VStack(name='Stack', height=0, style_type_name_override='ViewportStats', alignment=alignment) def _create_label(self, text: str = '', alignment: Optional[ui.Alignment] = None): if alignment is None: alignment = self.alignment return ui.Label(text, name='Label', style_type_name_override='ViewportStats', alignment=alignment) def _destroy_labels(self): for label in self.__labels: label.destroy() self.__labels = [] self.__ui_obj.clear() # Workaround an issue where space is left where the stat was if self.__ui_obj.visible: self.__ui_obj.visible = False self.__ui_obj.visible = True def update(self, update_info: dict): if self.skip_update(update_info): return stats = self.update_stats(update_info) # If no stats, clear all the labels now if not stats: self._destroy_labels() return # If the number of stats has gotten less, need to rebuild it all index, n_stats = 0, len(stats) if n_stats < len(self.__labels): self._destroy_labels() for txt in stats: self.set_text(txt, index) index = index + 1 def skip_update(self, update_info: dict): return False def update_stats(self, update_info: dict): return tuple() def set_text(self, txt: str, index: int): # If the number of stats has grown, add a new label if index >= len(self.__labels): with self.container: self.__labels.append(self._create_label()) ui_obj = self.__labels[index] ui_obj.text = txt ui_obj.visible = txt != '' return ui_obj def destroy(self): if self.__labels: self._destroy_labels() self.__labels = None if self.__ui_obj: self.__ui_obj.destroy() self.__ui_obj = None if self.__subscription_id: carb.settings.get_settings().unsubscribe_to_change_events(self.__subscription_id) self.__subscription_id = None self.__setting_key = None @property def empty(self) -> bool: return not bool(self.__labels) @property def alignment(self) -> ui.Alignment: return self.__alignment @property def visible(self) -> bool: return self.__ui_obj.visible @visible.setter def visible(self, value): self.__ui_obj.visible = value @property def categories(self): return ('stats',) @property def name(self): return self.__stat_name class ViewportDeviceStat(ViewportStatistic): def __init__(self, *args, **kwargs): super().__init__('Device Memory', setting_key='deviceMemory', *args, **kwargs) self.__low_memory = [] self.__enabled = [] def skip_update(self, update_info: dict): return update_info[MEMORY_CHECK_FREQUENCY] def update_stats(self, update_info: dict): stat_list = [] global _get_device_info dev_info = _get_device_info() self.__low_memory = [] self.__enabled = [] device_mask = update_info['viewport_api'].frame_info.get('device_mask') for desc_idx, dev_memory in zip(range(len(dev_info)), dev_info): available = 0 budget, usage = dev_memory['budget'], dev_memory['usage'] if budget > usage: available = budget - usage self.__low_memory.append((available / budget) < update_info['low_mem_fraction']) description = dev_memory['description'] or (f'GPU {desc_idx}') if not description: description = 'GPU ' + desc_idx self.__enabled.append(device_mask is not None and (device_mask & (1 << desc_idx))) used = _human_readable_size(usage) available = _human_readable_size(available) stat_list.append(f'{description}: {used} used, {available} available') return stat_list def set_text(self, txt: str, index: int): ui_obj = super().set_text(txt, index) if not ui_obj: return elif not self.__enabled[index]: ui_obj.name = 'LabelDisabled' elif self.__low_memory[index]: ui_obj.name = 'LabelError' else: ui_obj.name = 'Label' class ViewportMemoryStat(ViewportStatistic): def __init__(self, label: str | None = None, *args, **kwargs): settings = carb.settings.get_settings() self.__report_rss = bool(settings.get(HUD_MEM_TYPE_KEY)) self.__low_memory = False self.__settings_subs = ( settings.subscribe_to_node_change_events(HUD_MEM_TYPE_KEY, self.__memory_type_changed), settings.subscribe_to_node_change_events(HUD_MEM_NAME_KEY, self.__memory_type_changed) ) if label == None: label = settings.get(HUD_MEM_NAME_KEY) or "Host" self.__label = label super().__init__(f"{label} Memory", setting_key='hostMemory', *args, **kwargs) def __memory_type_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: settings = carb.settings.get_settings() self.__report_rss = bool(settings.get(HUD_MEM_TYPE_KEY)) self.__label = settings.get(HUD_MEM_NAME_KEY) or self.__label def destroy(self): sub_ids, self.__settings_subs = self.__settings_subs, None if self.__settings_subs: settings = carb.settings.get_settings() for sub in sub_ids: settings.unsubscribe_to_change_events(sub) def skip_update(self, update_info: dict): return update_info[MEMORY_CHECK_FREQUENCY] def __format_memory(self, update_info: dict, total: int | None = None, available: int | None = None, used: int | None = None): if used is None: used = total - available elif available is None: available = total - used elif total is None: total = available + used self.__low_memory = (available / total) < update_info['low_mem_fraction'] return f"{self.__label} Memory: {_human_readable_size(used)} used, {_human_readable_size(available)} available" def update_stats(self, update_info: dict): host_info = get_memory_info(rss=self.__report_rss) if self.__report_rss: return [ self.__format_memory(update_info, available=host_info['available_memory'], used=host_info["rss_memory"]) ] return [ self.__format_memory(update_info, total=host_info['total_memory'], available=host_info["available_memory"]) ] def set_text(self, txt: str, index: int): ui_obj = super().set_text(txt, index) if ui_obj: ui_obj.name = 'LabelError' if self.__low_memory else 'Label' class ViewportFPS(ViewportStatistic): def __init__(self, *args, **kwargs): super().__init__('FPS', setting_key='renderFPS', *args, **kwargs) self.__fps = None self.__multiplier = 1 self.__precision = 2 def skip_update(self, update_info: dict): # FPS update ignores freeze_frame as a signal that rendering is continuing. fps = round(update_info['viewport_api'].fps, self.__precision) multiplier = update_info['viewport_api'].frame_info.get('subframe_count', 1) should_skip_update = True if fps != self.__fps: self.__fps = fps should_skip_update = False if multiplier != self.__multiplier: self.__multiplier = multiplier should_skip_update = False return should_skip_update def update_stats(self, update_info: dict): effective_fps = self.__fps * self.__multiplier multiplier = max(self.__multiplier, 1) ms = 1000/effective_fps if effective_fps else 0 multiplier_str = ',' if multiplier == 1 else (' ' + ('|' * (multiplier - 1))) return [f'FPS: {effective_fps:.{self.__precision}f}{multiplier_str} Frame time: {ms:.{self.__precision}f} ms'] class ViewportResolution(ViewportStatistic): def __init__(self, *args, **kwargs): super().__init__('Resolution', setting_key='renderResolution', *args, **kwargs) self.__resolution = None def skip_update(self, update_info: dict): viewport_api = update_info['viewport_api'] # If Viewport is frozen to a frame, keep reolution displayed for that frame if viewport_api.freeze_frame: return True resolution = viewport_api.resolution if resolution == self.__resolution: return True self.__resolution = resolution return False def update_stats(self, update_info: dict): return [f'{self.__resolution[0]}x{self.__resolution[1]}'] class ViewportProgress(ViewportStatistic): def __init__(self, *args, **kwargs): super().__init__('Progress', setting_key='renderProgress', *args, **kwargs) self.__last_accumulated = 0 self.__total_elapsed = 0 def skip_update(self, update_info: dict): # If Viewport is frozen to a frame, don't update progress, what's displayed should be the last valid progress we have return update_info['viewport_api'].freeze_frame def update_stats(self, update_info: dict): viewport_api = update_info['viewport_api'] total, accumulated = None, viewport_api.frame_info.get('progression', None) if accumulated is None: return label = 'PathTracing' decimal_places = 2 no_limit = None renderer = viewport_api.hydra_engine settings = carb.settings.get_settings() if renderer == 'rtx': render_mode = settings.get('/rtx/rendermode') if render_mode == 'PathTracing': total = settings.get(RTX_PT_TOTAL_SPP) no_limit = 0 elif settings.get(RTX_ACCUMULATION_ENABLED): label = 'Progress' total = settings.get(RTX_ACCUMULATED_LIMIT) elif renderer == 'iray': total = settings.get(IRAY_MAX_SAMPLES) no_limit = -1 if total is None: return None rtx_spp = settings.get(RTX_SPP) if rtx_spp is None: return None # See RenderStatus in HydraRenderResults.h status = viewport_api.frame_info.get('status') if accumulated <= rtx_spp: self.__last_accumulated = 0 self.__total_elapsed = 0 # Update the elapsed time only if the rendering was a success, i.e. status 0. elif (status == 0) and ((self.__last_accumulated < total) or (no_limit is not None and total <= no_limit)): self.__total_elapsed = self.__total_elapsed + update_info['elapsed_time'] self.__last_accumulated = accumulated return [f'{label}: {accumulated}/{total} spp : {self.__total_elapsed:.{decimal_places}f} sec'] class _HudMessageTime: def __init__(self, key: str): self.__message_time: float = 0 self.__message_fade_in: float = 0 self.__message_fade_out: float = 0 self.__settings_subs: Sequence[carb.settings.SubscriptionId] = None self.__init(key) def __init(self, key: str): time_key: str = f"{key}/seconds" fade_in_key: str = f"{key}/fadeIn" fade_out_key: str = f"{key}/fadeOut" settings = carb.settings.get_settings() settings.set_default(time_key, 3) settings.set_default(fade_in_key, 0.5) settings.set_default(fade_out_key, 0.5) def timing_changed(*args, **kwargs): self.__message_time = settings.get(time_key) self.__message_fade_in = settings.get(fade_in_key) self.__message_fade_out = settings.get(fade_out_key) timing_changed() self.__settings_subs = ( settings.subscribe_to_node_change_events(time_key, timing_changed), settings.subscribe_to_node_change_events(fade_in_key, timing_changed), settings.subscribe_to_node_change_events(fade_out_key, timing_changed), ) def __del__(self): self.destroy() def destroy(self): if self.__settings_subs: settings = carb.settings.get_settings() for sub in self.__settings_subs: settings.unsubscribe_to_change_events(sub) self.__settings_subs = None @property def message_time(self) -> float: return self.__message_time @property def message_fade_in(self) -> float: return self.__message_fade_in @property def message_fade_out(self) -> float: return self.__message_fade_out @property def total_up_time(self): return self.message_fade_in + self.message_time class _HudMessageTracker(): """Calculate alpha for _HudMessageTime acounting for possibility of reversing direction mid-fade""" def __init__(self, prev_tckr: Optional["_HudMessageTracker"] = None, message_time: Optional[_HudMessageTime] = None): self.__time: float = 0 if prev_tckr and message_time: # If previous object was fading in, keep alpha if prev_tckr.__time < message_time.message_fade_in: self.__time = prev_tckr.__time return # If previous object was fading out, also keep alpha, but reverse direction total_msg_up_time = message_time.total_up_time if prev_tckr.__time > total_msg_up_time: self.__time = prev_tckr.__time - total_msg_up_time return # If previous object is already being shown at 100%, keep alpha 1 self.__time = message_time.message_fade_in def update(self, message_time: _HudMessageTime, elapsed_time: float): self.__time += elapsed_time if self.__time < message_time.message_fade_in: if message_time.message_fade_in <= 0: return 1 return min(1, self.__time / message_time.message_fade_in) total_msg_up_time = message_time.total_up_time if self.__time > total_msg_up_time: if message_time.message_fade_out <= 0: return 0 return max(0, 1.0 - (self.__time - total_msg_up_time) / message_time.message_fade_out) return 1 class ViewportStatisticFading(ViewportStatistic): def __init__(self, anim_key: str, parent=None, *args, **kwargs): super().__init__(*args, **kwargs) self.__message_time = _HudMessageTime(anim_key) self.__update_sub = None self.__alpha = 0 self.__parent = parent def destroy(self): self.__update_sub = None if self.__message_time: self.__message_time.destroy() self.__message_time = None super().destroy() def _skip_update(self, update_info: dict, check_empty: Optional[Callable] = None): # Skip updates when calld from the render-update, but return the cached alpha if update_info.get('external_update', None) is None: alpha = self.__alpha update_info['alpha'] = alpha if alpha <= 0: self.__update_sub = None return True # Skip any update if no message to display is_empty = check_empty() if check_empty else False if is_empty: update_info['alpha'] = 0 self.__update_sub = None return is_empty def _update_alpha(self, update_info: dict, accumulate_alpha: Callable): alpha = 0 elapsed_time = update_info['elapsed_time'] if elapsed_time: alpha = accumulate_alpha(self.__message_time, elapsed_time, alpha) update_info['alpha'] = alpha if alpha <= 0: self.__update_sub = None self.visible = False else: self.visible = True return alpha def _begin_animation(self): # Add the updtae subscription so that messages / updates are received even when not rendering if self.__update_sub: return bg_alpha = _get_background_alpha(carb.settings.get_settings()) def on_update(event: carb.events.IEvent): # Build a dict close enough to the render-update info update_info = { 'elapsed_time': event.payload['dt'], 'alpha': 1, 'external_update': True, # Internally tells skip_update to not skip this update 'background_alpha': bg_alpha } # Need to call through via parent ViewportStatsGroup to do the alpha adjustment self.__parent._update_stats(update_info) # Cache the updated alpha to be applied later, but kill the subscription if 0 self.__alpha = update_info.get('alpha') import omni.kit.app self.__update_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop( on_update, name=f"omni.kit.viewport.window.stats.ViewportStatisticFading[{self.name}]" ) def _end_animation(self, alpha: float = 0): self.__update_sub = None self.__alpha = alpha @property def message_time(self) -> _HudMessageTime: return self.__message_time class ViewportSpeed(ViewportStatisticFading): __CAM_VELOCITY = "/persistent/app/viewport/camMoveVelocity" __CAMERA_MANIP_MODE = "/exts/omni.kit.manipulator.camera/viewportMode" __COLLAPSE_CAM_SPEED = "/persistent" + f"{CAM_SPEED_MESSAGE_KEY}/collapsed" __FLY_VIEW_LOCK = "/persistent/exts/omni.kit.manipulator.camera/flyViewLock" __FLY_VIEW_LOCK_STAT = "/persistent/exts/omni.kit.viewport.window/cameraSpeedMessage/showFlyViewLock" def __init__(self, viewport_api, *args, **kwargs): self.__carb_subs: Sequence[carb.settings.SubscriptionId] = None self.__cam_speed_entry: Optional[ui.FloatField] = None self.__cam_speed_model_sub: Optional[carb.Subscription] = None self.__viewport_id: str = str(viewport_api.id) self.__root_frame: Optional[ui.Frame] = None self.__tracker: Optional[_HudMessageTracker] = None self.__style: Optional[dict] = None self.__focused_viewport: bool = False self.__fly_lock: Optional[ui.ImageWithProvider] = None super().__init__(anim_key=CAM_SPEED_MESSAGE_KEY, stat_name='Camera Speed', setting_key='cameraSpeed', viewport_api=viewport_api, *args, **kwargs) def update(self, update_info: dict): if self._skip_update(update_info): return def accumulate_alpha(message_time: _HudMessageTime, elapsed_time: float, alpha: float): return self.__tracker.update(message_time, elapsed_time) self._update_alpha(update_info, accumulate_alpha) def _create_ui(self, alignment: ui.Alignment): ui_root = super()._create_ui(alignment=alignment) from pathlib import Path from omni.ui import color as cl, constant as fl extension_path = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.window}")) icons_path = extension_path.joinpath("data").joinpath("icons").absolute() self.__style = { "MouseImage": { "image_url": str(icons_path.joinpath("mouse_wheel_dark.svg")), }, "ExpandCollapseButton": { "background_color": 0, }, "ExpandCollapseButton.Image::ExpandButton": { "image_url": str(icons_path.joinpath("speed_expand.svg")), }, "ExpandCollapseButton.Image::CollapseButton": { "image_url": str(icons_path.joinpath("speed_collapse.svg")), }, "IconSeparator": { "border_width": 45, }, "KeyboardKey": { "background_color": 0, "border_width": 1.5, "border_radius": 3 }, "KeyboardLabel": { }, 'ViewportStats::FloatField': { "background_color": 0, }, "FlyLockButton": { "background_color": 0, 'padding': 15, }, "LockedImage::Locked": { "image_url": str(icons_path.joinpath("ignore_view_direction_on.svg")), }, "LockedImage::UnLocked": { "image_url": str(icons_path.joinpath("ignore_view_direction_off.svg")), }, } with ui_root: self.__root_frame = ui.Frame(build_fn=self.__build_root_ui, style=self.__style) self.__build_root_ui() ui_root.set_mouse_hovered_fn(self.__mouse_hovered) return ui_root def __track_time(self): self.__tracker = _HudMessageTracker(self.__tracker, self.message_time) self._begin_animation() def __toggle_cam_speed_info(self): # Reset the timer tracking on ui interaction self.__track_time() # Toggle the persistan setting settings = carb.settings.get_settings() setting_key = self.__COLLAPSE_CAM_SPEED collapsed = not bool(settings.get(setting_key)) settings.set(setting_key, collapsed) def __add_mouse_item(self, label: str, tooltip: str, key_label: Optional[str] = None): ui.Spacer(width=10) ui.Line(width=2, alignment=ui.Alignment.V_CENTER, style_type_name_override="IconSeparator") ui.Spacer(width=10) with ui.VStack(width=50, alignment=ui.Alignment.CENTER): with ui.ZStack(content_clipping=True): if key_label: ui.Rectangle(width=50, height=25, style_type_name_override="KeyboardKey", tooltip=tooltip) ui.Label(key_label, alignment=ui.Alignment.CENTER, style_type_name_override="KeyboardLabel", tooltip=tooltip) else: # XXX: Odd ui-layout to have the image properly centered with ui.HStack(): ui.Spacer(width=15) self.__fly_lock = ui.ImageWithProvider(width=50, height=30, tooltip=tooltip, name=self.__get_lock_style_name(), style_type_name_override="LockedImage") ui.Spacer() ui.Button(width=50, height=25, style_type_name_override="FlyLockButton", clicked_fn=self.__toggle_fly_view_lock, tooltip=tooltip) ui.Spacer(height=5) ui.Label(label, alignment=ui.Alignment.CENTER, style_type_name_override="ViewportStats", name="Label") def __build_cam_speed_info(self, *args, **kwargs): mouse_tip = "Using Mouse wheel during flight navigation will adjust how fast or slow the camera will travel" ctrl_tip = "Pressing and holding Ctrl button during flight navigation will decrease the speed the camera travels" shft_tip = "Pressing and holding Shift button during flight navigation will increase the speed the camera travels" settings = carb.settings.get_settings() with ui.VStack(): ui.Spacer(height=10) with ui.HStack(): with ui.VStack(width=50, alignment=ui.Alignment.CENTER): with ui.HStack(): ui.Spacer(width=10) ui.ImageWithProvider(width=30, height=30, style_type_name_override="MouseImage", tooltip=mouse_tip) ui.Label('Speed', alignment=ui.Alignment.CENTER, style_type_name_override="ViewportStats", name="Label") self.__add_mouse_item("Slow", ctrl_tip, "ctrl") self.__add_mouse_item("Fast", shft_tip, "shift") if settings.get(self.__FLY_VIEW_LOCK_STAT): tootip = "Whether forward/backward and up/down movements ignore camera-view direction (similar to left/right strafe)" self.__add_mouse_item("Nav Height", tootip, None) def __build_root_ui(self, collapsed: Optional[bool] = None): if collapsed is None: collapsed = bool(carb.settings.get_settings().get(self.__COLLAPSE_CAM_SPEED)) with self.__root_frame: with ui.VStack(): with ui.HStack(alignment=ui.Alignment.LEFT, content_clipping=True): ui.Button(width=20, name="ExpandButton" if collapsed else "CollapseButton", style_type_name_override="ExpandCollapseButton", clicked_fn=self.__toggle_cam_speed_info) ui.Label("Camera Speed:", style_type_name_override="ViewportStats", name="Label") # Additional HStack container to reduce float-field shifting right when expanded with ui.HStack(alignment=ui.Alignment.LEFT): self.__cam_speed_entry = ui.FloatField(width=55, style_type_name_override="ViewportStats", name="FloatField") ui.Spacer() ui.Spacer() def model_changed(model: ui.AbstractValueModel): try: # Compare the values with a precision to avoid possibly excessive recursion settings = carb.settings.get_settings() model_value, carb_value = model.as_float, settings.get(self.__CAM_VELOCITY) if round(model_value, 6) == round(carb_value, 6): return # Short-circuit carb event handling in __cam_vel_changed self.__focused_viewport = False final_value = _limit_camera_velocity(model_value, settings, "text") settings.set(self.__CAM_VELOCITY, final_value) if model_value != final_value: model.set_value(final_value) finally: self.__focused_viewport = True # Reset the animation counter self.__track_time() model = self.__cam_speed_entry.model self.__cam_speed_entry.precision = 3 model.set_value(self.__get_camera_speed_value()) self.__cam_speed_model_sub = model.subscribe_value_changed_fn(model_changed) if not collapsed: self.__build_cam_speed_info() def __get_camera_speed_value(self): return carb.settings.get_settings().get(self.__CAM_VELOCITY) or 0 def __cam_manip_mode_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: manip_mode = carb.settings.get_settings().get(self.__CAMERA_MANIP_MODE) if manip_mode and manip_mode[0] == self.__viewport_id: self.__focused_viewport = True if manip_mode[1] == "fly": self.__track_time() else: self.__focused_viewport = False def __collapse_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if self.__root_frame and event_type == carb.settings.ChangeEventType.CHANGED: self.__root_frame.rebuild() def __cam_vel_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if self.__cam_speed_entry and self.__focused_viewport and event_type == carb.settings.ChangeEventType.CHANGED: self.__cam_speed_entry.model.set_value(self.__get_camera_speed_value()) self.__track_time() def __mouse_hovered(self, hovered: bool, *args): if hovered: self._end_animation(1) else: self._begin_animation() def _visibility_change(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type != carb.settings.ChangeEventType.CHANGED: return settings = carb.settings.get_settings() super()._visibility_change(item, event_type) if self.visible: # Made visible, setup additional subscriptions need now if self.__carb_subs is None: self.__carb_subs = ( settings.subscribe_to_node_change_events(self.__CAM_VELOCITY, self.__cam_vel_changed), settings.subscribe_to_node_change_events(f"{self.__CAMERA_MANIP_MODE}/1", self.__cam_manip_mode_changed), settings.subscribe_to_node_change_events(self.__COLLAPSE_CAM_SPEED, self.__collapse_changed), settings.subscribe_to_node_change_events(self.__FLY_VIEW_LOCK_STAT, self.__show_fly_view_lock), settings.subscribe_to_node_change_events(self.__FLY_VIEW_LOCK, self.__toggled_fly_view_lock), ) # Handle init case from super()__init__, only want the subscritions setup, not to show the dialog if item is not None: self.__focused_viewport = True self.__cam_vel_changed(None, carb.settings.ChangeEventType.CHANGED) elif self.__carb_subs: # Made invisible, remove uneeded subscriptions now self.__remove_camera_subs(settings) self._end_animation() def __remove_camera_subs(self, settings): carb_subs, self.__carb_subs = self.__carb_subs, None if carb_subs: for carb_sub in carb_subs: settings.unsubscribe_to_change_events(carb_sub) def __show_fly_view_lock(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type != carb.settings.ChangeEventType.CHANGED: return root_frame = self.__root_frame if root_frame: root_frame.rebuild() def __get_lock_style_name(self): enabled = carb.settings.get_settings().get(self.__FLY_VIEW_LOCK) return "Locked" if enabled else "UnLocked" def __toggled_fly_view_lock(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type != carb.settings.ChangeEventType.CHANGED: return lock_image = self.__fly_lock if lock_image: lock_image.name = self.__get_lock_style_name() def __toggle_fly_view_lock(self): key = self.__FLY_VIEW_LOCK settings = carb.settings.get_settings() settings.set(key, not bool(settings.get(key))) def destroy(self): self.__remove_camera_subs(carb.settings.get_settings()) self.__tracker = None self.__fly_lock = None if self.__root_frame: self.__root_frame.destroy() self.__root_frame = None if self.__cam_speed_model_sub: self.__cam_speed_model_sub = None if self.__cam_speed_entry: self.__cam_speed_entry.destroy() self.__cam_speed_entry = None super().destroy() @property def empty(self) -> bool: return False class ViewportMessage(ViewportStatisticFading): class _ToastMessage(_HudMessageTracker): """Store a message to fade with _HudMessageTracker""" def __init__(self, message: str, *args, **kwargs): self.__message = message super().__init__(*args, **kwargs) @property def message(self): return self.__message def __init__(self, *args, **kwargs): super().__init__(anim_key=TOAST_MESSAGE_KEY, stat_name='Toast Message', setting_key="toastMessage", *args, **kwargs) self.__messages = {} def skip_update(self, update_info: dict): return self._skip_update(update_info, lambda: not bool(self.__messages)) def update_stats(self, update_info: dict): def accumulate_alpha(message_time: _HudMessageTime, elapsed_time: float, alpha: float): self.__messages, messages = {}, self.__messages for msg_id, msg in messages.items(): cur_alpha = msg.update(message_time, elapsed_time) if cur_alpha: alpha = max(cur_alpha, alpha) self.__messages[msg_id] = msg return alpha self._update_alpha(update_info, accumulate_alpha) return [obj.message for obj in self.__messages.values()] def destroy(self): super().destroy() self.__messages = {} def add_message(self, message: str, message_id: str): self.__messages[message_id] = ViewportMessage._ToastMessage(message, self.__messages.get(message_id), self.message_time) # Add the update subscription so that messages / updates are received even when not rendering self._begin_animation() def remove_message(self, message: str, message_id: str): if message_id in self.__messages: del self.__messages[message_id] class ViewportStatsGroup: def __init__(self, factories, name: str, alignment: ui.Alignment, viewport_api): self.__alpha = 0 self.__stats = [] self.__group_name = name self.__container = ui.ZStack(name='Root', width=0, height=0, style_type_name_override='ViewportStats') proxy_self = weakref.proxy(self) with self.__container: ui.Rectangle(name='Background', style_type_name_override='ViewportStats') with ui.VStack(name='Group', style_type_name_override='ViewportStats'): for stat_obj in factories: self.__stats.append(stat_obj(parent=proxy_self, alignment=alignment, viewport_api=viewport_api)) self.__container.visible = False def __del__(self): self.destroy() def destroy(self): if self.__stats: for stat in self.__stats: stat.destroy() self.__stats = [] if self.__container: self.__container.clear() self.__container.destroy() self.__container = None def __set_alpha(self, alpha: float, background_alpha: float, background_alpha_changed: bool): alpha = min(0.8, alpha) if alpha == self.__alpha and (not background_alpha_changed): return self.__alpha = alpha self.__container.set_style({ 'ViewportStats::Background': { 'background_color': ui.color(0.145, 0.157, 0.165, alpha * background_alpha), }, 'ViewportStats::Label': { 'color': ui.color(1.0, 1.0, 1.0, alpha) }, 'ViewportStats::LabelError': { 'color': ui.color(1.0, 0.0, 0.0, alpha) }, 'ViewportStats::LabelWarning': { 'color': ui.color(1.0, 1.0, 0.0, alpha) }, "MouseImage": { "color": ui.color(1.0, 1.0, 1.0, alpha), }, "IconSeparator": { "color": ui.color(0.431, 0.431, 0.431, alpha), }, "ExpandCollapseButton.Image::ExpandButton": { "color": ui.color(0.102, 0.569, 0.772, alpha), }, "ExpandCollapseButton.Image::CollapseButton": { "color": ui.color(0.102, 0.569, 0.772, alpha), }, "KeyboardKey": { "border_color": ui.color(0.102, 0.569, 0.772, alpha), }, "KeyboardLabel": { "color": ui.color(0.102, 0.569, 0.772, alpha), }, "LockedImage": { "color": ui.color(1.0, 1.0, 1.0, alpha), }, 'ViewportStats::FloatField': { 'color': ui.color(1.0, 1.0, 1.0, alpha), "background_selected_color": ui.color(0.431, 0.431, 0.431, alpha), }, }) self.__container.visible = bool(alpha > 0) def _update_stats(self, update_info: dict): alpha = 0 any_visible = False for stat in self.__stats: try: update_info['alpha'] = 1 stat.update(update_info) any_visible = any_visible or (stat.visible and not stat.empty) alpha = max(alpha, update_info['alpha']) except Exception: import traceback carb.log_error(f"Error updating stats {stat}. Traceback:\n{traceback.format_exc()}") alpha = alpha if any_visible else 0 self.__set_alpha(alpha, update_info.get('background_alpha'), update_info.get('background_alpha_changed')) return alpha @property def visible(self): return self.__container.visible if self.__container else False @visible.setter def visible(self, value): if self.__container: self.__container.visible = value elif value: carb.log_error(f"{self.__group_name} has been destroyed, cannot set visibility to True") @property def categories(self): return ('stats',) @property def name(self): return self.__group_name @property def layers(self): for stats in self.__stats: yield stats class ViewportStatsLayer: # Legacy setting that still need to be honored (transiently) _LEGACY_FORCE_FPS_OFF = "/app/viewport/forceHideFps" _LEGACY_LAYER_MENU_ON = "/app/viewport/showLayerMenu" def __init__(self, desc: dict): settings = carb.settings.get_settings() settings.set_default(LOW_MEMORY_SETTING_PATH, 0.2) settings.set_default(MEMORY_CHECK_FREQUENCY, 1.0) self.__viewport_api = desc.get('viewport_api') self.__frame_changed_sub = None self.__disable_ui_sub: Optional[carb.SubscriptionId] = None self.__setting_key, visible = _resolve_hud_visibility(self.__viewport_api, None, settings) self.__bg_alpha = 0 # Check some legacy settings that control visibility and should be honored destroy_old_key = f"/persistent/app/viewport/{self.__viewport_api.id}/hud/forceVisible" force_vis_tmp = settings.get(destroy_old_key) if force_vis_tmp is not None: # Clear out this key from any further persistance settings.destroy_item(destroy_old_key) if force_vis_tmp: # Store it back to the persitent setting settings.set(self.__setting_key, True) visible = True # Check some legacy settings that control visibility and should be honored if visible: visible = self.__get_transient_visibility(settings) self.__last_time = time.time() self.__frequencies = {} for key in [MEMORY_CHECK_FREQUENCY]: value = settings.get(key) self.__frequencies[key] = [value, value] self.__groups: Sequence[ViewportStatsGroup] = None self.__root:ui.Frame = ui.Frame(horizontal_clipping=True, content_clipping=1, opaque_for_mouse_events=True) self.__disable_ui_sub = ( settings.subscribe_to_node_change_events(self.__setting_key, self.__stats_visiblity_changed), settings.subscribe_to_node_change_events(self._LEGACY_FORCE_FPS_OFF, self.__legacy_transient_changed), settings.subscribe_to_node_change_events(self._LEGACY_LAYER_MENU_ON, self.__legacy_transient_changed) ) self.__stats_visiblity_changed(None, carb.settings.ChangeEventType.CHANGED) # Workaround an issue where camera-speed HUD check should default to on settings.set_default(f"/persistent/app/viewport/{self.__viewport_api.id}/hud/cameraSpeed/visible", True) def __destroy_all_stats(self, value = None): if self.__groups: for group in self.__groups: group.destroy() self.__groups = value def __build_stats_hud(self, viewport_api): if self.__root: self.__root.clear() self.__destroy_all_stats([]) right_stat_factories = [ ViewportFPS, ViewportMemoryStat, ViewportProgress, ViewportResolution ] # Optional omni.hydra.engine.stats dependency global _get_device_info if not _get_device_info: try: from omni.hydra.engine.stats import get_device_info _get_device_info = get_device_info except ImportError: pass if _get_device_info: right_stat_factories.insert(1, ViewportDeviceStat) # XXX: Need menu-bar height hud_top = 20 if hasattr(ui.constant, 'viewport_menubar_height') else 0 with self.__root: with ui.VStack(height=hud_top): ui.Spacer(name='Spacer', style_type_name_override='ViewportStats') with ui.HStack(): with ui.VStack(): self.__groups.append(ViewportStatsGroup([ViewportSpeed], "Viewport Speed", ui.Alignment.LEFT, self.__viewport_api)) self.__groups.append(ViewportStatsGroup([ViewportMessage], "Viewport Message", ui.Alignment.LEFT, self.__viewport_api)) ui.Spacer(name='LeftRightSpacer', style_type_name_override='ViewportStats') self.__groups.append(ViewportStatsGroup(right_stat_factories, "Viewport HUD", ui.Alignment.RIGHT, self.__viewport_api)) def __stats_visiblity_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: self.visible = bool(carb.settings.get_settings().get(self.__setting_key)) @staticmethod def __get_transient_visibility(settings): # Legacy compat, this takes precedence when explitly set to False ll_lm_vis = settings.get(ViewportStatsLayer._LEGACY_LAYER_MENU_ON) if (ll_lm_vis is not None) and (not bool(ll_lm_vis)): return False # Now check the other transient visibility if bool(settings.get(ViewportStatsLayer._LEGACY_FORCE_FPS_OFF)): return False return True def __legacy_transient_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: if self.__get_transient_visibility(carb.settings.get_settings()): self.__stats_visiblity_changed(None, event_type) else: self.visible = False def __set_stats_enabled(self, enabled: bool): if enabled: viewport_api = self.__viewport_api if not self.__groups: self.__build_stats_hud(viewport_api) if self.__frame_changed_sub is None: self.__frame_changed_sub = viewport_api.subscribe_to_frame_change(self.__update_stats) self.__update_stats(viewport_api) else: if self.__frame_changed_sub: self.__frame_changed_sub.destroy() self.__frame_changed_sub = None if self.__root: self.__root.clear() self.__destroy_all_stats([]) self.__root.visible = enabled def __make_update_info(self, viewport_api): now = time.time() elapsed_time, self.__last_time = now - self.__last_time, now settings = carb.settings.get_settings() bg_alpha = _get_background_alpha(settings) update_info = { 'elapsed_time': elapsed_time, 'low_mem_fraction': settings.get(LOW_MEMORY_SETTING_PATH), 'viewport_api': viewport_api, 'alpha': 1, 'background_alpha': bg_alpha } # Signal background alpha changed if self.__bg_alpha != bg_alpha: self.__bg_alpha = bg_alpha update_info['background_alpha_changed'] = True for key, value in self.__frequencies.items(): value[0] += elapsed_time value[1] = settings.get(key) if value[0] >= value[1]: value[0] = 0 update_info[key] = False else: update_info[key] = True return update_info def __update_stats(self, viewport_api): if self.__groups: update_info = self.__make_update_info(viewport_api) for group in self.__groups: group._update_stats(update_info) def destroy(self): ui_subs, self.__disable_ui_sub = self.__disable_ui_sub, None if ui_subs: settings = carb.settings.get_settings() for ui_sub in ui_subs: settings.unsubscribe_to_change_events(ui_sub) self.__set_stats_enabled(False) self.__destroy_all_stats() if self.__root: self.__root.clear() self.__root = None self.__usd_context_name = None @property def layers(self): if self.__groups: for group in self.__groups: yield group @property def visible(self): return self.__root.visible @visible.setter def visible(self, value): value = bool(value) if value: if not self.__get_transient_visibility(carb.settings.get_settings()): return self.__set_stats_enabled(value) @property def categories(self): return ('stats',) @property def name(self): return 'All Stats'
51,014
Python
40.274272
137
0.581115
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/dragdrop/usd_prim_drop_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['UsdPrimDropDelegate', 'UsdShadeDropDelegate'] from .scene_drop_delegate import SceneDropDelegate import omni.ui import omni.kit.commands from pxr import Usd, Sdf, Gf, UsdGeom, UsdShade import carb from functools import partial from typing import List, Callable class UsdPrimDropDelegate(SceneDropDelegate): def __init__(self, preview_setting: str = None, *args, **kwargs): super().__init__(*args, **kwargs) self.reset_state() @property def dragging_prim(self): return self.__usd_prim_dragged @dragging_prim.setter def dragging_prim(self, prim: Usd.Prim): self.__usd_prim_dragged = prim @property def world_space_pos(self): return self.__world_space_pos @world_space_pos.setter def world_space_pos(self, world_space_pos: Gf.Vec3d): self.__world_space_pos = world_space_pos def reset_state(self): self.__usd_prim_dragged = None self.__world_space_pos = None def accepted(self, drop_data: dict): self.reset_state() # XXX: Poor deliniation of file vs Sdf.Path prim_path = drop_data.get('mime_data') if prim_path.find('.') > 0: return False # If there is no Usd.Stage, then it can't be a prim for this stage usd_context, stage = self.get_context_and_stage(drop_data) if stage is None: return False # Check if it's a path to a valid Usd.Prim and save it if so prim = stage.GetPrimAtPath(prim_path) if prim is None or not prim.IsValid(): return False self.dragging_prim = prim return True def add_drop_marker(self, drop_data: dict, world_space_pos: Gf.Vec3d): prim = self.dragging_prim if prim: self.world_space_pos = world_space_pos super().add_drop_marker(drop_data, world_space_pos) # Overide drop behavior, material drop doesn't draw anything def dropped(self, drop_data: dict): usd_context, stage = self.get_context_and_stage(drop_data) if stage is None: return dropped_prim = self.dragging_prim if (dropped_prim is None) or (not dropped_prim.IsValid()): return dropped_onto = drop_data.get('prim_path') if dropped_onto is None: return dropped_onto = stage.GetPrimAtPath(dropped_onto) if (dropped_onto is None) or (not dropped_onto.IsValid()): return dropped_onto_model = drop_data.get('model_path') dropped_onto_model = stage.GetPrimAtPath(dropped_onto_model) if dropped_onto_model else None self.handle_prim_drop(stage, dropped_prim, dropped_onto, dropped_onto_model) def collect_child_paths(self, prim: Usd.Prim, filter: Callable): had_child, children = False, [] for child in prim.GetFilteredChildren(Usd.PrimAllPrimsPredicate): had_child = True if filter(child): children.append(child.GetPath()) return children if had_child else [prim.GetPath()] def handle_prim_drop(self, dropped_prim: Usd.Prim, dropped_onto: Usd.Prim, dropped_onto_model: Usd.Prim): raise RuntimeError(f'UsdPrimDropDelegate.dropped not overidden') class UsdShadeDropDelegate(UsdPrimDropDelegate): @property def binding_strength(self): strength = carb.settings.get_settings().get('/persistent/app/stage/materialStrength') return strength or 'weakerThanDescendants' @property def honor_picking_mode(self): return True def reset_state(self): super().reset_state() self.__menu = None def accepted(self, drop_data: dict): if super().accepted(drop_data): return self.dragging_prim.IsA(UsdShade.Material) return False # Overide draw behavior, material drop doesn't draw anything def add_drop_marker(self, drop_data: dict, world_space_pos: Gf.Vec3d): return def bind_material(self, prim_paths, material_path: Sdf.Path): self.__menu = None omni.kit.commands.execute('BindMaterialCommand', prim_path=prim_paths, material_path=material_path, strength=self.binding_strength ) def show_bind_menu(self, prim_path: Sdf.Path, model_path: Sdf.Path, material_path: Sdf.Path): import omni.kit.material.library def __apply_material(target): if (target): omni.kit.commands.execute('BindMaterialCommand', prim_path=target, material_path=material_path) omni.kit.material.library.drop_material( prim_path.pathString, model_path.pathString, apply_material_fn=__apply_material ) def handle_prim_drop(self, stage: Usd.Stage, dropped_prim: Usd.Prim, dropped_onto: Usd.Prim, dropped_onto_model: Usd.Prim): if dropped_onto_model: prim_path = dropped_onto.GetPath() model_path = dropped_onto_model.GetPath() material_path = dropped_prim.GetPath() self.show_bind_menu(prim_path, model_path, material_path) return else: prim_paths = [dropped_onto.GetPath()] if prim_paths: self.bind_material(prim_paths, dropped_prim.GetPath())
5,717
Python
34.296296
127
0.647717
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/dragdrop/delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['DragDropDelegate'] import weakref class DragDropDelegate: # Use a list to track drag-drop order so that it's deterministic in the event of clashes or cancelation. __g_registered = [] @classmethod def get_instances(cls): remove = [] for wref in DragDropDelegate.__g_registered: obj = wref() if obj: yield obj else: remove.append(wref) for wref in remove: DragDropDelegate.__g_registered.remove(wref) def __init__(self): self.__g_registered.append(weakref.ref(self, lambda r: DragDropDelegate.__g_registered.remove(r))) def __del__(self): self.destroy() def destroy(self): for wref in DragDropDelegate.__g_registered: if wref() == self: DragDropDelegate.__g_registered.remove(wref) break @property def add_outline(self) -> bool: return False def accepted(self, url: str) -> bool: return False def update_drop_position(self, drop_data: dict) -> bool: return True def dropped(self, drop_data: dict) -> None: pass def cancel(self, drop_data: dict) -> None: pass
1,679
Python
27.965517
108
0.633115
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/dragdrop/handler.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['DragDropHandler'] from cmath import isfinite import omni.ui as ui from .delegate import DragDropDelegate import carb import traceback from typing import Sequence from pxr import Usd, UsdGeom, Sdf, Kind from ..raycast import perform_raycast_query class DragDropHandler: @staticmethod def picking_mode(): mode = carb.settings.get_settings().get('/persistent/app/viewport/pickingMode') return mode or 'models' # 'models' is equivalent to 'kind:model.ALL' @staticmethod def drag_drop_colors(): try: # Use the selection-outline color or the color below it for selection differentiation outline_colors = carb.settings.get_settings().get('/persistent/app/viewport/outline/color') if outline_colors and len(outline_colors) >= 4: locator_color = None outline_color = (outline_colors[-4], outline_colors[-3], outline_colors[-2], outline_colors[-1]) if len(outline_colors) >= 8: secondary_lcolor = carb.settings.get_settings().get('/app/viewport/dragdrop/useSecondaryColorLocator') secondary_ocolor = carb.settings.get_settings().get('/app/viewport/dragdrop/useSecondaryColorOutline') if secondary_lcolor: locator_color = (outline_colors[-8], outline_colors[-7], outline_colors[-6], outline_colors[-5]) elif secondary_ocolor: locator_color = outline_color if secondary_ocolor: outline_color = (outline_colors[-8], outline_colors[-7], outline_colors[-6], outline_colors[-5]) return outline_color, locator_color or outline_color except Exception: carb.log_error(f'Traceback:\n{traceback.format_exc()}') return (1.0, 0.6, 0.0, 1.0), (1.0, 0.6, 0.0, 1.0) def get_enclosing_model(self, prim_path: str): stage = self.viewport_api.stage if stage: kind_reg = Kind.Registry() prim = stage.GetPrimAtPath(prim_path) while prim: model = Usd.ModelAPI(prim) kind = model and model.GetKind() if kind and kind_reg.IsA(kind, Kind.Tokens.model): return prim.GetPath() prim = prim.GetParent() return None def __init__(self, payload: dict): self.__valid_drops = None self.__add_outline = False self.__payload = payload or {} self.__payload['mime_data'] = None self.__payload['usd_context_name'] = self.viewport_api.usd_context_name self.__last_prim_path = Sdf.Path() self.__dropped = False colors = self.drag_drop_colors() self.__payload['outline_color'] = colors[0] self.__payload['locator_color'] = colors[1] self.__last_prim_collection = set() self.setup_outline(colors[0]) @property def viewport_api(self): return self.__payload['viewport_api'] def setup_outline(self, outline_color: Sequence[float], shade_color: Sequence[float] = (0, 0, 0, 0), sel_group: int = 254): self.__sel_group = sel_group usd_context = self.viewport_api.usd_context self.__selected_prims = set(usd_context.get_selection().get_selected_prim_paths()) usd_context.set_selection_group_outline_color(sel_group, outline_color) usd_context.set_selection_group_shade_color(sel_group, shade_color) def __set_prim_outline(self, prim_path: Sdf.Path = None): if not self.__add_outline: return # Save the current prim for clering later and save off the previous prim locally last_prim_path, self.__last_prim_path = self.__last_prim_path, prim_path usd_context = self.viewport_api.usd_context new_path = prim_path != last_prim_path # Restore any previous if self.__dropped or new_path: for sdf_path in self.__last_prim_collection: usd_context.set_selection_group(0, sdf_path.pathString) self.__last_prim_collection = set() # If over a prim and not dropped, set the outline if prim_path and new_path: prim = usd_context.get_stage().GetPrimAtPath(prim_path) if prim.IsA(UsdGeom.Gprim): self.__last_prim_collection.add(prim_path) for prim in Usd.PrimRange(prim, Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)): if prim.IsA(UsdGeom.Gprim): self.__last_prim_collection.add(prim.GetPath()) for sdf_path in self.__last_prim_collection: usd_context.set_selection_group(self.__sel_group, sdf_path.pathString) def __query_complete(self, is_drop: bool, prim_path: str, world_space_pos: Sequence[float], *args): if prim_path: if not isfinite(world_space_pos[0]) or not isfinite(world_space_pos[1]) or not isfinite(world_space_pos[2]): # XXX: RTX is passing inf or nan in some cases... prim_path, world_space_pos = Sdf.Path(), (0, 0, 0) else: prim_path = Sdf.Path(prim_path) else: prim_path = Sdf.Path() updated_drop = [] outline_path = prim_path pick_mode = self.picking_mode() model_path = None if prim_path and (pick_mode == 'kind:model.ALL' or pick_mode == 'models'): for drop_obj in self.__valid_drops: instance = drop_obj[0] if hasattr(instance, 'honor_picking_mode') and instance.honor_picking_mode: model_path = self.get_enclosing_model(prim_path) outline_path = model_path or prim_path break self.__set_prim_outline(outline_path) for drop_obj in self.__valid_drops: instance, drop_data = drop_obj drop_data['prim_path'] = prim_path drop_data['model_path'] = model_path drop_data['world_space_pos'] = world_space_pos drop_data['picking_mode'] = pick_mode # Update common ui data changed in _perform_query drop_data['pixel'] = self.__payload.get('pixel') drop_data['mouse_ndc'] = self.__payload.get('mouse_ndc') drop_data['viewport_ndc'] = self.__payload.get('viewport_ndc') try: if is_drop: instance.dropped(drop_data) elif instance.update_drop_position(drop_data): updated_drop.append((instance, drop_data)) except Exception: carb.log_error(f'Traceback:\n{traceback.format_exc()}') # If it is a drop, then the action is done and clear any cached data # otherwise store the updated list of valid drops self.__valid_drops = None if is_drop else updated_drop def _perform_query(self, ui_obj: ui.Widget, mouse: Sequence[float], is_drop: bool = False): if not self.__valid_drops: return viewport_api = self.viewport_api if not viewport_api: return # Move from screen to local space mouse = (mouse[0] - ui_obj.screen_position_x, mouse[1] - ui_obj.screen_position_y) # Move from ui to normalized space (0-1) mouse = (mouse[0] / ui_obj.computed_width, mouse[1] / ui_obj.computed_height) # Move from normalized space to normalized device space (-1, 1) mouse = ((mouse[0] - 0.5) * 2.0, (mouse[1] - 0.5) * -2.0) self.__payload['mouse_ndc'] = mouse mouse, valid = viewport_api.map_ndc_to_texture_pixel(mouse) resolution = viewport_api.resolution vp_ndc = (mouse[0] / resolution[0], mouse[1] / resolution[1]) vp_ndc = ((vp_ndc[0] - 0.5) * 2.0, (vp_ndc[1] - 0.5) * -2.0) self.__payload['pixel'] = mouse self.__payload['viewport_ndc'] = vp_ndc if valid and viewport_api.stage: perform_raycast_query( viewport_api=viewport_api, mouse_ndc=self.__payload['mouse_ndc'], mouse_pixel=mouse, on_complete_fn=lambda *args: self.__query_complete(is_drop, *args), query_name='omni.kit.viewport.dragdrop.DragDropHandler' ) else: self.__query_complete(is_drop, '', (0, 0, 0)) def accepted(self, ui_obj: ui.Widget, url_data: str): self.__dropped = False self.__valid_drops = None add_outline = False drops = [] for instance in DragDropDelegate.get_instances(): for url in url_data.splitlines(): try: # Copy the master payload so no delegates can change it payload = self.__payload.copy() # Push current url into the local payload payload['mime_data'] = url if instance.accepted(payload): drops.append((instance, payload)) add_outline = add_outline or instance.add_outline except Exception: carb.log_error(f'Traceback:\n{traceback.format_exc()}') if drops: self.__valid_drops = drops self.__add_outline = add_outline # Save this for comparison later (mime_data should be constant across the drg-drop event) self.__payload['accepted_mime_data'] = url_data return True return False def dropped(self, ui_obj: ui.Widget, event: ui._ui.WidgetMouseDropEvent): # Save this off now if self.__payload.get('accepted_mime_data') != event.mime_data: carb.log_error( "Mime data changed between accepeted and dropped\n" + f" accepted: {self.__payload.get('accepted_mime_data')}\n" + f" dropped: {event.mime_data}" ) return self.__dropped = True self._perform_query(ui_obj, (event.x, event.y), True) def cancel(self, ui_obj: ui.Widget): prev_drops, self.__valid_drops = self.__valid_drops, [] self.__set_prim_outline() for drop_obj in prev_drops: try: drop_obj[0].cancel(drop_obj[1]) except Exception: carb.log_error(f'Traceback:\n{traceback.format_exc()}')
10,846
Python
44.767932
127
0.584271
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/dragdrop/usd_file_drop_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['UsdFileDropDelegate'] from .scene_drop_delegate import SceneDropDelegate import omni.usd import omni.kit.commands from pxr import Gf, Sdf, Usd, UsdGeom import carb import os class UsdFileDropDelegate(SceneDropDelegate): def __init__(self, preview_setting: str = None, *args, **kwargs): super().__init__(*args, **kwargs) self.__drag_to_open = False self.__world_space_pos = None self.__alternate_drop_marker = False self.__pickable_collection = None self.__preview_setting = preview_setting # Method to allow subclassers to test url and keep all other default behavior def ignore_url(self, url: str): # Validate it's a USD file and there is a Stage or UsdContet to use if not omni.usd.is_usd_readable_filetype(url): return True # Early out for other .usda handlers that claim the protocol if super().is_ignored_protocol(url): return True if super().is_ignored_extension(url): return True return False # Test if the drop should do a full preview or just a cross-hair def drop_should_disable_preview(self): # The case with no Usd.Stage in the UsdContext, cannot preview anything if self.__drag_to_open: return True # Test if there is a seting holding whether to preview or not, and invert it if self.__preview_setting: return False if carb.settings.get_settings().get(self.__preview_setting) else True return False # Subclasses can override to provide a different -alternate- behavior. Default is to fallback to crosshairs def add_alternate_drop_marker(self, drop_data: dict, world_space_pos: Gf.Vec3d): self.__alternate_drop_marker = True self.__world_space_pos = world_space_pos super().add_drop_marker(drop_data, world_space_pos) # Subclasses can override to clean out their -alternate- behavior. def remove_alternate_drop_marker(self, drop_data: dict): if self.__alternate_drop_marker: self.__world_space_pos = None super().remove_drop_marker(drop_data) def reset_state(self): self.__pickable_collection = None return super().reset_state() def accepted(self, drop_data: dict): # Reset self's state self.__drag_to_open = False self.__world_space_pos = None # Reset super's state self.reset_state() url = self.get_url(drop_data) if self.ignore_url(url): return False usd_context, stage = self.get_context_and_stage(drop_data) if not usd_context: return False try: import omni.kit.window.file except ImportError: carb.log_warn('omni.kit.window.file must be present to drop and load a USD file without a stage') return False # Validate not dropping a cyclical reference if stage: root_layer = stage.GetRootLayer() if url == self.normalize_sdf_path(root_layer.realPath): return False else: self.__drag_to_open = True return True def add_drop_marker(self, drop_data: dict, world_space_pos: Gf.Vec3d): # Try and add the USD reference, this will invoke super.add_drop_marker # In the case it can't be accomplished, fallback to an alternate marker. usd_prim_droped = drop_data.get('usd_prim_droped') if usd_prim_droped is None: if self.drop_should_disable_preview(): self.add_alternate_drop_marker(drop_data, world_space_pos) return elif self.__alternate_drop_marker: self.remove_alternate_drop_marker(drop_data) usd_prim_droped = self.add_usd_drop_marker(drop_data, world_space_pos, True) if usd_prim_droped is None: return drop_data['usd_prim_droped'] = usd_prim_droped elif self.drop_should_disable_preview(): # If preview was diabled mid-drag, undo the reference operation and add simple cross-hairs self.remove_drop_marker(drop_data) self.add_alternate_drop_marker(drop_data, world_space_pos) return # Constantly update the Prim's position, but avoid undo so that the reference/drop is what's undoable omni.kit.commands.create('TransformPrimSRTCommand', path=usd_prim_droped, new_translation=world_space_pos).do() self.update_pickability(drop_data, False) def update_pickability(self, drop_data: dict, pickable: bool): if self.__pickable_collection: usd_context, _ = self.get_context_and_stage(drop_data) for sdf_path in self.__pickable_collection: usd_context.set_pickable(sdf_path.pathString, pickable) def remove_drop_marker(self, drop_data: dict): # If usd_prim_droped is None, fallback to super which may have added cross-hair in no-stage case if drop_data.get('usd_prim_droped'): omni.kit.undo.undo() del drop_data['usd_prim_droped'] self.remove_alternate_drop_marker(drop_data) def dropped(self, drop_data: dict): # If usd_prim_droped is None, but drop occured fallback to super which may have added cross-hair in no-stage case usd_prim_droped = drop_data.get('usd_prim_droped') if usd_prim_droped is not None: self.update_pickability(drop_data, True) self.__pickable_collection = None elif self.drop_should_disable_preview(): super().remove_drop_marker(drop_data) if self.__drag_to_open: omni.kit.window.file.open_stage(self.get_url(drop_data).replace(os.sep, '/')) elif self.__world_space_pos: usd_prim_path = self.add_usd_drop_marker(drop_data, self.__world_space_pos) if usd_prim_path: omni.kit.commands.create('TransformPrimSRTCommand', path=usd_prim_path, new_translation=self.__world_space_pos).do() def add_usd_drop_marker(self, drop_data: dict, world_space_pos: Gf.Vec3d, pickable_collection: bool = False): url = self.get_url(drop_data) usd_context, stage = self.get_context_and_stage(drop_data) sdf_layer = Sdf.Layer.FindOrOpen(url) if not sdf_layer: carb.log_warn(f'Could not get Sdf layer for {url}') return None if not sdf_layer.HasDefaultPrim(): message = f"Cannot reference {url} as it has no default prim." try: import omni.kit.notification_manager as nm nm.post_notification(message, status=nm.NotificationStatus.WARNING) except ImportError: pass finally: carb.log_warn(message) return None new_prim_path, edit_context, relative_url = self.add_reference_to_stage(usd_context, stage, url) if pickable_collection: self.__pickable_collection = set() self.__pickable_collection.add(new_prim_path) for prim in Usd.PrimRange(usd_context.get_stage().GetPrimAtPath(new_prim_path), Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)): if prim.IsA(UsdGeom.Gprim): self.__pickable_collection.add(prim.GetPath()) return new_prim_path
7,863
Python
41.73913
148
0.635127
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/dragdrop/legacy.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['create_drop_helper'] from .delegate import DragDropDelegate from typing import Callable class _LegacyDragDropObject(DragDropDelegate): def __init__(self, add_outline: bool, test_accepted_fn: Callable, drop_fn: Callable, pick_complete: Callable): super().__init__() self.__add_outline = add_outline self.__test_accepted_fn = test_accepted_fn self.__dropped = drop_fn self.__pick_complete = pick_complete @property def add_outline(self): return self.__add_outline def accepted(self, drop_data: dict): url = drop_data['mime_data'] return self.__test_accepted_fn(url) if self.__test_accepted_fn else False def dropped(self, drop_data: dict): url = drop_data['mime_data'] if (self.__dropped is not None) and url and self.accepted(drop_data): prim_path = drop_data.get('prim_path') prim_path = prim_path.pathString if prim_path else '' usd_context_name = drop_data.get('usd_context_name', '') payload = self.__dropped(url, prim_path, '', usd_context_name) if payload and self.__pick_complete: self.__pick_complete(payload, prim_path, usd_context_name) def create_drop_helper(pickable: bool = False, add_outline: bool = True, on_drop_accepted_fn: Callable = None, on_drop_fn: Callable = None, on_pick_fn: Callable = None): """Add a viewport drop handler. Args: pickable (bool): Deprecated, use on_pick_fn to signal you want picking. add_outline (False): True to add outline to picked prim when dropping. on_drop_accepted_fn (Callable): Callback function to check if drop helper could handle the dragging payload. Return True if payload accepted by this drop helper and will handle dropping later. Args: url (str): url in the payload. on_drop_fn (Callable): Callback function to handle dropping. Return a payload that evaluates to True in order to block other drop handlers. Args: url (str): url in the payload. target (str): picked prim path to drop. viewport_name (str): name of viewport window. usd_context_name (str): name of dropping usd context. on_pick_fn (Callable): Callback function to handle pick. Args: payload (Any): Return value from from on_drop_fn. target (str): picked prim path. usd_context_name (str): name of picked usd context. """ if pickable: import carb carb.log_warn('pickable argument to create_drop_helper is deprecated, use on_pick_fn') return _LegacyDragDropObject(add_outline, on_drop_accepted_fn, on_drop_fn, on_pick_fn)
3,167
Python
44.913043
169
0.666246
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/dragdrop/scene_drop_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['SceneDropDelegate'] from .delegate import DragDropDelegate import omni.usd import omni.ui as ui from omni.ui import scene as sc from pxr import Gf, Tf, Sdf, Usd, UsdGeom import carb import os from typing import Sequence, Tuple class SceneDropDelegate(DragDropDelegate): # XXX: We know these have a meanining that we don't handle, so early out __g_ignore_protocols = set(('sky::', 'material::')) __g_ignore_extensions = set() @staticmethod def add_ignored_protocol(protocol: str): '''Add a protocol that should be ignored by default file-handlers''' SceneDropDelegate.__g_ignore_protocols.add(protocol) @staticmethod def remove_ignored_protocol(protocol: str): '''Remove a protocol that should be ignored by default file-handlers''' SceneDropDelegate.__g_ignore_protocols.discard(protocol) @staticmethod def add_ignored_extension(extension: str): '''Add a file extension that should be ignored by default file-handlers''' SceneDropDelegate.__g_ignore_extensions.add(extension) @staticmethod def remove_ignored_extension(extension: str): '''Remove a file extension that should no longer be ignored by default file-handlers''' SceneDropDelegate.__g_ignore_extensions.discard(extension) @staticmethod def is_ignored_protocol(url: str): '''Early out for other protocol handlers that claim the format''' for protocol in SceneDropDelegate.__g_ignore_protocols: if url.startswith(protocol): return True return False @staticmethod def is_ignored_extension(url: str): '''Early out for other extension handlers that claim the format''' for extension in SceneDropDelegate.__g_ignore_extensions: if url.endswith(extension): return True return False def __init__(self, *args, **kw_args): super().__init__(*args, **kw_args) self.__ndc_z = None self.__color = None self.__transform = None self.__xf_to_screen = None self.__max_plane_dist = 0 try: max_plane_dist = carb.settings.get_settings().get("/exts/omni.kit.viewport.window/dragDrop/maxPlaneDistance") max_plane_dist = float(max_plane_dist) self.__max_plane_dist = max_plane_dist if max_plane_dist >= 0 else 0 except ValueError: pass @property def add_outline(self) -> bool: return True @property def honor_picking_mode(self) -> bool: return False def reset_state(self): # Reset any previous cached drag-drop info self.__ndc_z = None self.__color = None def accepted(self, drop_data: dict): self.reset_state() return True def update_drop_position(self, drop_data: dict): self.__color = drop_data['locator_color'] world_space_pos = self._get_world_position(drop_data) if world_space_pos: self.add_drop_marker(drop_data, world_space_pos) return True def dropped(self, drop_data: dict): self.remove_drop_marker(drop_data) def cancel(self, drop_data: dict): self.remove_drop_marker(drop_data) # Helper methods to inspect drop_data def get_url(self, drop_data: dict): return drop_data.get('mime_data') def get_context_and_stage(self, drop_data: dict): usd_context = omni.usd.get_context(drop_data['usd_context_name']) return (usd_context, usd_context.get_stage()) if usd_context else (None, None) @property def color(self): return self.__color def make_prim_path(self, stage: Usd.Stage, url: str, prim_path: Sdf.Path = None, prim_name: str = None): '''Make a new/unique prim path for the given url''' if prim_path is None: if stage.HasDefaultPrim(): prim_path = stage.GetDefaultPrim().GetPath() else: prim_path = Sdf.Path.absoluteRootPath if prim_name is None: prim_name = Tf.MakeValidIdentifier(os.path.basename(os.path.splitext(url)[0])) return Sdf.Path(omni.usd.get_stage_next_free_path(stage, prim_path.AppendChild(prim_name).pathString, False)) def create_instanceable_reference(self, usd_context, stage: Usd.Stage, url: str, prim_path: str) -> bool: '''Return whether to create the reference as instanceable=True''' return carb.settings.get_settings().get('/persistent/app/stage/instanceableOnCreatingReference') def create_as_payload(self, usd_context, stage: Usd.Stage, url: str, prim_path: str): '''Return whether to create as a reference or payload''' dd_import = carb.settings.get_settings().get('/persistent/app/stage/dragDropImport') return dd_import == 'payload' def normalize_sdf_path(self, sdf_layer_path: str): return sdf_layer_path.replace('\\', '/') def make_relative_to_layer(self, stage: Usd.Stage, url: str) -> str: # XXX: PyBind omni::usd::UsdUtils::makePathRelativeToLayer stage_layer = stage.GetEditTarget().GetLayer() if not stage_layer.anonymous and not Sdf.Layer.IsAnonymousLayerIdentifier(url): stage_layer_path = stage_layer.realPath if self.normalize_sdf_path(stage_layer_path) == url: carb.log_warn(f'Cannot reference {url} onto itself') return relative_url = omni.client.make_relative_url(stage_layer_path, url) if relative_url: # omniverse path can have '\' return relative_url.replace('\\', '/') return url def add_reference_to_stage(self, usd_context, stage: Usd.Stage, url: str) -> Tuple[str, Usd.EditContext, str]: '''Add a Usd.Prim to an exiting Usd.Stage, pointing to the url''' # Get a realtive URL if possible relative_url = self.make_relative_to_layer(stage, url) # When in auto authoring mode, don't create it in the current edit target # as it will be cleared each time to be moved to default edit layer. edit_context = None layers = usd_context.get_layers() if layers and layers.get_layer_edit_mode() == omni.usd.LayerEditMode.AUTO_AUTHORING: default_identifier = layers.get_default_edit_layer_identifier() edit_layer = Sdf.Layer.Find(default_identifier) if edit_layer is None: edit_layer = stage.GetRootLayer() edit_context = Usd.EditContext(stage, edit_layer) new_prim_path = self.make_prim_path(stage, url) instanceable = self.create_instanceable_reference(usd_context, stage, url, new_prim_path) as_payload = self.create_as_payload(usd_context, stage, url, new_prim_path) cmd_name = 'CreatePayloadCommand' if as_payload else 'CreateReferenceCommand' omni.kit.commands.execute(cmd_name, usd_context=usd_context, path_to=new_prim_path, asset_path=url, instanceable=instanceable) return (new_prim_path, edit_context, relative_url) # Meant to be overriden by subclasses to draw drop information # Default draws a cross-hair in omni.ui.scene def add_drop_shape(self, world_space_pos: Gf.Vec3d, scale: float = 50, thickness: float = 1, color: ui.color = None): self.__xf_to_screen = sc.Transform(scale_to=sc.Space.SCREEN) with self.__xf_to_screen: sc.Line((-scale, 0, 0), (scale, 0, 0), color=color, thickness=thickness) sc.Line((0, -scale, 0), (0, scale, 0), color=color, thickness=thickness) sc.Line((0, 0, -scale), (0, 0, scale), color=color, thickness=thickness) def add_drop_marker(self, drop_data: dict, world_space_pos: Gf.Vec3d): if not self.__transform: scene_view = drop_data['scene_view'] if scene_view: with scene_view.scene: self.__transform = sc.Transform() with self.__transform: self.add_drop_shape(world_space_pos, color=self.color) if self.__transform: self.__transform.transform = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, world_space_pos[0], world_space_pos[1], world_space_pos[2], 1 ] return self.__transform def remove_drop_marker(self, drop_data: dict): if self.__xf_to_screen: self.__xf_to_screen.clear() self.__xf_to_screen = None if self.__transform: self.__transform.clear() self.__transform = None # Semi and fully private methods def __cache_screen_ndc(self, viewport_api, world_space_pos: Gf.Vec3d): screen_space_pos = viewport_api.world_to_ndc.Transform(world_space_pos) self.__ndc_z = screen_space_pos[2] def _get_world_position_object(self, viewport_api, world_space_pos: Gf.Vec3d, drop_data: dict) -> Tuple[Gf.Vec3d, bool]: """Return a world-space position that is located between two objects as mouse is dragged over them""" success = False # If previosuly dragged over an object, use that as the depth to drop onto if self.__ndc_z is None: # Otherwise use the camera's center-of-interest as the depth camera = viewport_api.stage.GetPrimAtPath(viewport_api.camera_path) coi_attr = camera.GetAttribute('omni:kit:centerOfInterest') if coi_attr: world_space_pos = viewport_api.transform.Transform(coi_attr.Get(viewport_api.time)) self.__cache_screen_ndc(viewport_api, world_space_pos) # If we have depth (in NDC), move (x_ndc, y_ndz, z_ndc) to a world-space position if self.__ndc_z is not None: success = True mouse_ndc = drop_data['mouse_ndc'] world_space_pos = viewport_api.ndc_to_world.Transform(Gf.Vec3d(mouse_ndc[0], mouse_ndc[1], self.__ndc_z)) return (world_space_pos, success) def _get_world_position_plane(self, viewport_api, world_space_pos: Gf.Vec3d, drop_data: dict, mode: str) -> Tuple[Gf.Vec3d, bool]: success = False test_one_plane = False # User can specify plane to test against explicitly if mode == "z": up_axis, test_one_plane = UsdGeom.Tokens.z, True elif mode == "x": up_axis, test_one_plane = UsdGeom.Tokens.x, True elif mode == "y": up_axis, test_one_plane = UsdGeom.Tokens.y, True else: # Otherwise test against multiple planes unless mode is 'ground' (single plane test based on scene-up) up_axis, test_one_plane = UsdGeom.GetStageUpAxis(viewport_api.stage), mode == "ground" if up_axis == UsdGeom.Tokens.z: normals = (Gf.Vec3d(0, 0, 1), Gf.Vec3d(0, 1, 0), Gf.Vec3d(1, 0, 0)) elif up_axis == UsdGeom.Tokens.x: normals = (Gf.Vec3d(1, 0, 0), Gf.Vec3d(0, 1, 0), Gf.Vec3d(0, 0, 1)) else: normals = (Gf.Vec3d(0, 1, 0), Gf.Vec3d(0, 0, 1), Gf.Vec3d(1, 0, 0)) def create_ray(projection: Gf.Matrix4d, view: Gf.Matrix4d, ndx_x: float, ndc_y: float, ndc_z: float = 0): pv_imatrix = (view * projection).GetInverse() origin = pv_imatrix.Transform(Gf.Vec3d(ndx_x, ndc_y, ndc_z)) if projection[3][3] == 1: # Orthographic is simpler than perspective dir = Gf.Vec3d(view[0][2], view[1][2], view[2][2]).GetNormalized() else: dir = pv_imatrix.Transform(Gf.Vec3d(ndx_x, ndc_y, 0.5)) dir = Gf.Vec3d(dir[0] - origin[0], dir[1] - origin[1], dir[2] - origin[2]).GetNormalized() return (origin, dir) def intersect_plane(normal: Gf.Vec3d, ray_orig: Gf.Vec3d, ray_dir: Gf.Vec3d, epsilon: float = 1e-5): denom = Gf.Dot(normal, ray_dir) if abs(denom) < epsilon: return (None, None) distance = Gf.Dot(-ray_orig, normal) / denom if distance < epsilon: return (None, None) return (ray_orig + ray_dir * distance, distance) # Build ray origin and direction from mouse NDC co-ordinates mouse_ndc = drop_data['mouse_ndc'] ray_origin, ray_dir = create_ray(viewport_api.projection, viewport_api.view, mouse_ndc[0], mouse_ndc[1]) # Try normal-0, any hit on that plane wins (the Stage's ground normal) plane0_pos, plane0_dist = intersect_plane(normals[0], ray_origin, ray_dir) # Check that the hit distance is within tolerance (or no tolerance specified) def distance_in_bounds(distance: float) -> bool: if self.__max_plane_dist > 0: return distance < self.__max_plane_dist return True # Return a successful hit (caching the screen-ndc in case mode fallsback/transitions to object) def return_valid_position(position: Gf.Vec3d): self.__cache_screen_ndc(viewport_api, position) return (position, True) # If the hit exists and is within the max allowed distance (or no max allowed distance) it wins if plane0_pos and distance_in_bounds(plane0_dist): return return_valid_position(plane0_pos) # If testing more than one plane if not test_one_plane: # Check if other planes were hit, and if so use the best/closests plane1_pos, plane1_dist = intersect_plane(normals[1], ray_origin, ray_dir) plane2_pos, plane2_dist = intersect_plane(normals[2], ray_origin, ray_dir) if plane1_pos and distance_in_bounds(plane1_dist): # plane-1 hit and valid, check if plane-2 also hit and valid and use closest of the two if plane2_pos and distance_in_bounds(plane2_dist) and (plane2_dist < plane1_dist): return return_valid_position(plane2_pos) # Return plane-1, plane-2 was either invalid, further, or above tolerance return return_valid_position(plane1_pos) elif plane2_pos and distance_in_bounds(plane2_dist): # Return plane-2 it is valid and within tolerance return return_valid_position(plane2_pos) # Nothing worked, return input and False return (world_space_pos, False) def _get_world_position(self, drop_data: dict) -> Gf.Vec3d: prim_path = drop_data['prim_path'] viewport_api = drop_data['viewport_api'] world_space_pos = drop_data['world_space_pos'] if world_space_pos: world_space_pos = Gf.Vec3d(*world_space_pos) # If there is no prim-path, deliver a best guess at world-position if not prim_path and viewport_api.stage: success = False # Can change within a drag-drop operation via hotkey mode = carb.settings.get_settings().get("/exts/omni.kit.viewport.window/dragDrop/intersectMode") or "" if mode != "object": world_space_pos, success = self._get_world_position_plane(viewport_api, world_space_pos, drop_data, mode) if not success: world_space_pos, success = self._get_world_position_object(viewport_api, world_space_pos, drop_data) else: self.__cache_screen_ndc(viewport_api, world_space_pos) return world_space_pos
15,838
Python
44.777457
134
0.623374
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/dragdrop/material_file_drop_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['MaterialFileDropDelegate'] from .usd_prim_drop_delegate import UsdShadeDropDelegate from pxr import Sdf, Usd, UsdGeom import carb import os import asyncio from typing import List class MaterialFileDropDelegate(UsdShadeDropDelegate): def __init__(self, preview_setting: str = None, *args, **kwargs): super().__init__(*args, **kwargs) self.__mdl_future = None @property def honor_picking_mode(self): return True # Method to allow subclassers to test url and keep all other default behavior def accept_url(self, url: str) -> str: # Early out for protocols not understood if super().is_ignored_protocol(url): return False if super().is_ignored_extension(url): return False # Validate it's a USD file and there is a Stage or UsdContet to use url_path, ext = os.path.splitext(url) if not (ext in ['.mdl']): return False return url def reset_state(self) -> None: self.__mdl_future = None super().reset_state() def accepted(self, drop_data: dict) -> bool: # Reset state (base-class implemented) self.reset_state() # Validate there is a UsdContext and Usd.Stage usd_context, stage = self.get_context_and_stage(drop_data) if not usd_context: return False # Test if this url should be accepted url = self.get_url(drop_data) url = self.accept_url(url) if (url is None) or (not url): return False # Queue any remote MDL parsing try: import omni.kit.material.library asyncio.ensure_future(omni.kit.material.library.get_subidentifier_from_mdl(mdl_file=url, show_alert=False)) except ImportError: carb.log_error("Cannot import materials as omni.kit.material.library isn't loaded") return True def get_material_prim_location(self, stage: Usd.Stage) -> Sdf.Path: # Place material at /Looks under root or defaultPrim if stage.HasDefaultPrim(): looks_path = stage.GetDefaultPrim().GetPath() else: looks_path = Sdf.Path.absoluteRootPath return looks_path.AppendChild('Looks') def get_material_name(self, url: str, need_result: bool) -> List[str]: try: import omni.kit.material.library # Get the material subid's subid_list = [] def have_subids(id_list): nonlocal subid_list subid_list = id_list asyncio.get_event_loop().run_until_complete(omni.kit.material.library.get_subidentifier_from_mdl(mdl_file=url, on_complete_fn=have_subids)) # covert from SubIDEntry to str return [id.name for id in subid_list] except ImportError: carb.log_error("Cannot import materials as omni.kit.material.library isn't loaded") return [] def dropped(self, drop_data: dict): # Validate there is still a UsdContext and Usd.Stage usd_context, stage = self.get_context_and_stage(drop_data) if stage is None: return url_path = self.accept_url(drop_data.get('mime_data')) if (url_path is None) or (not url_path): return try: import omni.usd import omni.kit.commands omni.kit.undo.begin_group() looks_path = self.get_material_prim_location(stage) looks_prim = stage.GetPrimAtPath(looks_path) looks_prim_valid = looks_prim.IsValid() if (not looks_prim_valid) or (not UsdGeom.Scope(looks_prim)): if looks_prim_valid: looks_path = omni.usd.get_stage_next_free_path(stage, looks_path, False) looks_path = Sdf.Path(looks_path) omni.kit.commands.execute('CreatePrimCommand', prim_path=looks_path, prim_type='Scope', select_new_prim=False, context_name=drop_data.get('usd_context_name') or '') dropped_onto = drop_data.get('prim_path') dropped_onto_model = drop_data.get('model_path') mtl_name = self.get_material_name(url_path, True) num_materials = len(mtl_name) if mtl_name else 0 if num_materials < 1: raise RuntimeError('Could not get material name from "{url_path}"') material_prim = self.make_prim_path(stage, url_path, looks_path, mtl_name[0]) if material_prim is None: return if True: try: from omni.kit.material.library import custom_material_dialog, multi_descendents_dialog if dropped_onto or dropped_onto_model: # Dropped onto a Prim, use multi_descendents_dialog to choose subset or prim def multi_descendent_chosen(prim_path): if num_materials > 1: custom_material_dialog(mdl_path=url_path, bind_prim_paths=[prim_path]) else: with omni.kit.undo.group(): omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url=url_path, mtl_name=mtl_name[0], mtl_path=material_prim, select_new_prim=False) omni.kit.commands.execute('BindMaterialCommand', prim_path=prim_path, material_path=material_prim, strength=self.binding_strength) multi_descendents_dialog(prim_paths=[dropped_onto_model if dropped_onto_model else dropped_onto], on_click_fn=multi_descendent_chosen) elif num_materials > 1: # Get the sub-material required custom_material_dialog(mdl_path=url_path, bind_prim_paths=[dropped_onto]) else: # One sub-material, not dropped onto a Prim, just create the material omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url=url_path, mtl_name=mtl_name[0], mtl_path=material_prim, select_new_prim=False) return except ImportError: pass # Fallback to UsdShadeDropDelegate.handle_prim_drop # Need to create the material first omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url=url_path, mtl_name=mtl_name[0], mtl_path=material_prim, select_new_prim=False) material_prim = stage.GetPrimAtPath(material_prim) if not material_prim.IsValid(): raise RuntimeError(f'Could not create material {material_prim} for "{url_path}"') # If the material was dropped onto nothing, its been created so done if not dropped_onto: return # handle_prim_drop expects Usd.Prims, not paths dropped_onto = stage.GetPrimAtPath(dropped_onto) dropped_onto_model = stage.GetPrimAtPath(dropped_onto_model) if dropped_onto_model else None self.handle_prim_drop(stage, material_prim, dropped_onto, dropped_onto_model) except Exception: import traceback carb.log_error(traceback.format_exc()) finally: omni.kit.undo.end_group()
7,794
Python
40.684492
180
0.607005
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/dragdrop/audio_file_drop_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['AudioFileDropDelegate'] from .scene_drop_delegate import SceneDropDelegate from pxr import Gf, Tf import re, os class AudioFileDropDelegate(SceneDropDelegate): # Method to allow subclassers to test url and keep all other default behavior def accept_url(self, url: str) -> str: # Early out for protocols not understood if super().is_ignored_protocol(url): return False if super().is_ignored_extension(url): return False # Validate it's a known Audio file is_audio = re.compile(r"^.*\.(wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus)(\?.*)?$", re.IGNORECASE).match(url) return url if bool(is_audio) else False def accepted(self, drop_data: dict) -> bool: # Reset state (base-class implemented) self.reset_state() # Validate there is a UsdContext and Usd.Stage usd_context, stage = self.get_context_and_stage(drop_data) if not usd_context: return False # Test if this url should be accepted url = self.get_url(drop_data) url = self.accept_url(url) if (url is None) or (not url): return False return True def dropped(self, drop_data: dict): self.remove_drop_marker(drop_data) # Validate there is still a UsdContext and Usd.Stage usd_context, stage = self.get_context_and_stage(drop_data) if stage is None: return url_path = self.accept_url(drop_data.get('mime_data')) if (url_path is None) or (not url_path): return import omni.usd import omni.kit.commands url_path = self.make_relative_to_layer(stage, url_path) prim_path = self.make_prim_path(stage, url_path) try: omni.kit.undo.begin_group() omni.kit.commands.execute('CreateAudioPrimFromAssetPath', path_to=prim_path, asset_path=url_path, usd_context=usd_context) world_space_pos = self._get_world_position(drop_data) if world_space_pos: omni.kit.commands.execute('TransformPrimCommand', path=prim_path, new_transform_matrix=Gf.Matrix4d().SetTranslate(world_space_pos), usd_context_name=drop_data.get('usd_context_name', '')) finally: omni.kit.undo.end_group()
2,922
Python
35.5375
117
0.616359
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/scene/layer.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportSceneLayer'] import omni.ui as ui from omni.ui import scene as sc from omni.kit.viewport.registry import RegisterScene from .scenes import _flatten_matrix from ..events import add_event_delegation, remove_event_delegation from typing import Sequence import carb import traceback import weakref class _SceneItem(): def __init__(self, transform, instance, factory): self.__transform = transform self.__instance = instance self.__transform.visible = self.__instance.visible def __repr__(self) -> str: return f'<class {self.__class__.__name__} {self.__instance}>' @property def name(self): return self.__instance.name @property def visible(self): return self.__transform.visible @visible.setter def visible(self, value): self.__transform.visible = bool(value) self.__instance.visible = bool(value) @property def layers(self): return tuple() @property def categories(self): return self.__instance.categories @property def layer(self): return self.__instance def destroy(self): try: if hasattr(self.__instance, 'destroy'): self.__instance.destroy() except Exception: carb.log_error(f"Error destroying {self.__instance}. Traceback:\n{traceback.format_exc()}") self.__instance = None self.__transform.clear() self.__transform = None class ViewportSceneLayer: """Viewport Scene Overlay""" @property def layers(self): return self.__scene_items.values() def __view_changed(self, viewport_api): self.__scene_view.view = _flatten_matrix(viewport_api.view) self.__scene_view.projection = _flatten_matrix(viewport_api.projection) def ___scene_type_added(self, factory): # Push both our scopes onto the stack, to capture anything that's created if not self.__scene_view: viewport_api = self.__factory_args.get('viewport_api') if not viewport_api: raise RuntimeError('Cannot create a ViewportSceneLayer without a viewport') with self.__ui_frame: self.__scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH) add_event_delegation(weakref.proxy(self.__scene_view), viewport_api) # 1030 Tell the ViewportAPI that we have a SceneView we want it to be updating if hasattr(viewport_api, 'add_scene_view'): viewport_api.add_scene_view(self.__scene_view) self.__view_change_sub = None else: self.__view_change_sub = viewport_api.subscribe_to_view_change(self.__view_changed) # 1030 Fixes menu issue triggering selection (should remove hasattr pre 103-final) if hasattr(self.__scene_view, 'child_windows_input'): self.__scene_view.child_windows_input = False with self.__scene_view.scene: transform = sc.Transform() with transform: try: # Shallow copy, but should help keeping any errant extensions from messing with one-another instance = factory(self.__factory_args.copy()) if instance: self.__scene_items[factory] = _SceneItem(transform, instance, factory) except Exception: carb.log_error(f"Error loading {factory}. Traceback:\n{traceback.format_exc()}") def ___scene_type_removed(self, factory): scene = self.__scene_items.get(factory) if not scene: return scene.destroy() del self.__scene_items[factory] # Cleanup if we know we're empty if not self.__scene_items and self.__scene_view: self.__scene_view.destroy() self.__scene_view = None self.__dd_handler = None def ___scene_type_notification(self, factory, loading): if loading: self.___scene_type_added(factory) else: self.___scene_type_removed(factory) def __init__(self, factory_args, *args, **kwargs): super().__init__(*args, **kwargs) self.__scene_items = {} self.__factory_args = factory_args self.__ui_frame = ui.Frame() self.__scene_view = None self.__dd_handler = None RegisterScene.add_notifier(self.___scene_type_notification) def __del__(self): self.destroy() def destroy(self): remove_event_delegation(self.__scene_view) RegisterScene.remove_notifier(self.___scene_type_notification) self.__dd_handler = None for factory, instance in self.__scene_items.items(): try: if hasattr(instance, 'destroy'): instance.destroy() except Exception: carb.log_error(f"Error destroying {instance} from {factory}. Traceback:\n{traceback.format_exc()}") if self.__scene_view: scene_view, self.__scene_view = self.__scene_view, None scene_view.destroy() viewport_api = self.__factory_args.get('viewport_api') if viewport_api: if hasattr(viewport_api, 'remove_scene_view'): viewport_api.remove_scene_view(scene_view) else: self.__view_change_sub = None if self.__ui_frame: self.__ui_frame.destroy() self.__ui_frame = None self.__scene_items = {} self.__factory_args = None
6,070
Python
35.136905
115
0.602965
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/scene/scenes.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportSceneView', 'SimpleGrid', 'SimpleOrigin', 'CameraAxis'] from typing import Optional, Sequence import omni.ui from omni.ui import ( scene as sc, color as cl ) from pxr import UsdGeom, Gf import carb # Simple scene items that don't yet warrant a devoted extension def _flatten_matrix(matrix: Gf.Matrix4d): m0, m1, m2, m3 = matrix[0], matrix[1], matrix[2], matrix[3] return [m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3]] def _flatten_rot_matrix(matrix: Gf.Matrix3d): m0, m1, m2 = matrix[0], matrix[1], matrix[2] return [m0[0], m0[1], m0[2], 0, m1[0], m1[1], m1[2], 0, m2[0], m2[1], m2[2], 0, 0, 0, 0, 1] class SimpleGrid: def __init__(self, vp_args, lineCount: float = 100, lineStep: float = 10, thicknes: float = 1, color: cl = cl(0.25)): self.__viewport_grid_vis_sub: Optional[carb.SubscriptionId] = None self.__transform: sc.Transform = sc.Transform() with self.__transform: for i in range(lineCount * 2 + 1): sc.Line( ((i - lineCount) * lineStep, 0, -lineCount * lineStep), ((i - lineCount) * lineStep, 0, lineCount * lineStep), color=color, thickness=thicknes, ) sc.Line( (-lineCount * lineStep, 0, (i - lineCount) * lineStep), (lineCount * lineStep, 0, (i - lineCount) * lineStep), color=color, thickness=thicknes, ) self.__vc_change = None viewport_api = vp_args.get('viewport_api') if viewport_api: self.__vc_change = viewport_api.subscribe_to_view_change(self.__view_changed) self.__viewport_api_id: str = str(viewport_api.id) self.__viewport_grid_vis_sub = carb.settings.get_settings().subscribe_to_node_change_events( f"/persistent/app/viewport/{self.__viewport_api_id}/guide/grid/visible", self.__viewport_grid_display_changed ) self.__viewport_grid_display_changed(None, carb.settings.ChangeEventType.CHANGED) def __del__(self): self.destroy() def __view_changed(self, viewport_api): stage = viewport_api.stage up = UsdGeom.GetStageUpAxis(stage) if stage else None if up == UsdGeom.Tokens.z: self.__transform.transform = [0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1] elif up == UsdGeom.Tokens.x: self.__transform.transform = [0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1] else: self.__transform.transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] def __viewport_grid_display_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: key = f"/persistent/app/viewport/{self.__viewport_api_id}/guide/grid/visible" self.visible = bool(carb.settings.get_settings().get(key)) @property def name(self): return 'Grid' @property def categories(self): return ['guide'] @property def visible(self): return self.__transform.visible @visible.setter def visible(self, value): self.__transform.visible = bool(value) def destroy(self): if self.__viewport_grid_vis_sub is not None: carb.settings.get_settings().unsubscribe_to_change_events(self.__viewport_grid_vis_sub) self.__viewport_grid_vis_sub = None if self.__vc_change: self.__vc_change.destroy() self.__vc_change = None class SimpleOrigin: def __init__(self, desc: dict, visible: bool = False, length: float = 5, thickness: float = 4): self.__viewport_origin_vis_sub: Optional[carb.SubscriptionId] = None self._transform: sc.Transform = sc.Transform(visible=visible) with self._transform: origin = (0, 0, 0) sc.Line(origin, (length, 0, 0), color=cl.red, thickness=thickness) sc.Line(origin, (0, length, 0), color=cl.green, thickness=thickness) sc.Line(origin, (0, 0, length), color=cl.blue, thickness=thickness) viewport_api = desc.get('viewport_api') if not viewport_api: raise RuntimeError('Cannot create CameraAxisLayer without a viewport') self.__viewport_api_id: str = str(viewport_api.id) self.__viewport_origin_vis_sub = carb.settings.get_settings().subscribe_to_node_change_events( f"/persistent/app/viewport/{self.__viewport_api_id}/guide/origin/visible", self.__viewport_origin_display_changed ) self.__viewport_origin_display_changed(None, carb.settings.ChangeEventType.CHANGED) def __viewport_origin_display_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: key = f"/persistent/app/viewport/{self.__viewport_api_id}/guide/origin/visible" self.visible = bool(carb.settings.get_settings().get(key)) @property def name(self): return 'Origin' @property def categories(self): return ['guide'] @property def visible(self): return self._transform.visible @visible.setter def visible(self, value): self._transform.visible = bool(value) def destroy(self): if self.__viewport_origin_vis_sub: carb.settings.get_settings().unsubscribe_to_change_events(self.__viewport_origin_vis_sub) self.__viewport_origin_vis_sub = None class CameraAxisLayer: CAMERA_AXIS_DEFAULT_SIZE = (60, 60) CAMERA_AXIS_SIZE_SETTING = "/app/viewport/defaults/guide/axis/size" def __init__(self, desc: dict): self.__transform = None self.__scene_view = None self.__vc_change = None self.__root = None self.__change_event_subs: Optional[Sequence[carb.SubscriptionId]] = None viewport_api = desc.get('viewport_api') if not viewport_api: raise RuntimeError('Cannot create CameraAxisLayer without a viewport') settings = carb.settings.get_settings() size = settings.get(CameraAxisLayer.CAMERA_AXIS_SIZE_SETTING) or CameraAxisLayer.CAMERA_AXIS_DEFAULT_SIZE alignment = omni.ui.Alignment.LEFT_BOTTOM direction = omni.ui.Direction.BOTTOM_TO_TOP self.__root = omni.ui.Stack(direction) with self.__root: self.__scene_view = sc.SceneView( alignment=alignment, width=omni.ui.Length(size[0]), height=omni.ui.Length(size[1]) ) omni.ui.Spacer() thickness = 2 length = 0.5 text_offset = length + 0.25 text_size = 14 colors = ( (0.6666, 0.3765, 0.3765, 1.0), (0.4431, 0.6392, 0.4627, 1.0), (0.3098, 0.4901, 0.6274, 1.0), ) labels = ('X', 'Y', 'Z') with self.__scene_view.scene: origin = (0, 0, 0) self.__transform = sc.Transform() with self.__transform: for i in range(3): color = colors[i] vector = [0, 0, 0] vector[i] = length sc.Line(origin, vector, color=color, thickness=thickness) vector[i] = text_offset with sc.Transform(transform=sc.Matrix44.get_translation_matrix(vector[0], vector[1], vector[2])): sc.Label(labels[i], color=color, alignment=omni.ui.Alignment.CENTER, size=text_size) self.__vc_change = viewport_api.subscribe_to_view_change(self.__view_changed) self.__viewport_api_id: str = str(viewport_api.id) self.__change_event_subs = ( settings.subscribe_to_node_change_events( f"/persistent/app/viewport/{self.__viewport_api_id}/guide/axis/visible", self.__viewport_axis_display_changed ), settings.subscribe_to_node_change_events( f"{CameraAxisLayer.CAMERA_AXIS_SIZE_SETTING}/0", self.__viewport_axis_size_changed ), settings.subscribe_to_node_change_events( f"{CameraAxisLayer.CAMERA_AXIS_SIZE_SETTING}/1", self.__viewport_axis_size_changed ) ) self.__viewport_axis_display_changed(None, carb.settings.ChangeEventType.CHANGED) def __view_changed(self, viewport_api): self.__transform.transform = _flatten_rot_matrix(viewport_api.view.GetOrthonormalized().ExtractRotationMatrix()) def __viewport_axis_display_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: key = f"/persistent/app/viewport/{self.__viewport_api_id}/guide/axis/visible" self.visible = bool(carb.settings.get_settings().get(key)) def __viewport_axis_size_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: size = carb.settings.get_settings().get(CameraAxisLayer.CAMERA_AXIS_SIZE_SETTING) if len(size) == 2: self.__scene_view.width, self.__scene_view.height = omni.ui.Length(size[0]), omni.ui.Length(size[1]) def destroy(self): if self.__change_event_subs: settings = carb.settings.get_settings() for sub in self.__change_event_subs: settings.unsubscribe_to_change_events(sub) self.__change_event_subs = None if self.__vc_change: self.__vc_change.destroy() self.__vc_change = None if self.__transform: self.__transform.clear() self.__transform = None if self.__scene_view: self.__scene_view.destroy() self.__scene_view = None if self.__root: self.__root.clear() self.__root.destroy() self.__root = None @property def visible(self): return self.__root.visible @visible.setter def visible(self, value): self.__root.visible = value @property def categories(self): return ['guide'] @property def name(self): return 'Axis'
10,992
Python
38.260714
121
0.592431
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/scene/legacy.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['LegacyGridScene', 'LegacyLightScene', 'LegacyAudioScene'] import carb import omni.usd from pxr import UsdGeom class LegacyGridScene: AUTO_TRACK_PATH = '/app/viewport/grid/trackCamera' def __init__(self, desc: dict, *args, **kwargs): self.__vc_change = None self.__viewport_grid_vis_sub = None self.__auto_track_sub = None self.__usd_context_name = desc['usd_context_name'] self.__viewport_api = desc.get('viewport_api') settings = carb.settings.get_settings() self.__viewport_grid_vis_sub = settings.subscribe_to_node_change_events( f"/persistent/app/viewport/{self.__viewport_api.id}/guide/grid/visible", self.__viewport_grid_display_changed ) self.__auto_track_sub = settings.subscribe_to_node_change_events( "/app/viewport/grid/trackCamera", self.__auto_track_changed ) self.__viewport_grid_display_changed(None, carb.settings.ChangeEventType.CHANGED) self.__auto_track_changed() def __setup_view_tracking(self): if self.__vc_change: return self.__persp_grid = 'XZ' self.__last_grid = None self.__on_stage_opened(self.stage) self.__stage_sub = self.usd_context.get_stage_event_stream().create_subscription_to_pop( self.__on_usd_context_event, name='LegacyGridScene StageUp watcher' ) self.__vc_change = self.__viewport_api.subscribe_to_view_change(self.__view_changed) def __destroy_view_tracking(self, settings): self.__stage_sub = None if self.__vc_change: self.__vc_change.destroy() self.__vc_change = None @property def usd_context(self): return omni.usd.get_context(self.__usd_context_name) @property def stage(self): return self.usd_context.get_stage() def __auto_track_changed(self, *args, **kwargs): settings = carb.settings.get_settings() if settings.get(self.AUTO_TRACK_PATH): self.__destroy_view_tracking(settings) else: self.__setup_view_tracking() def __on_usd_context_event(self, event: carb.events.IEvent): if event.type == int(omni.usd.StageEventType.OPENED): self.__on_stage_opened(self.stage) def __set_grid(self, grid: str): if self.__last_grid != grid: self.__last_grid = grid carb.settings.get_settings().set('/app/viewport/grid/plane', grid) def __on_stage_opened(self, stage): up = UsdGeom.GetStageUpAxis(stage) if stage else None if up == UsdGeom.Tokens.x: self.__persp_grid = 'YZ' elif up == UsdGeom.Tokens.z: self.__persp_grid = 'XY' else: self.__persp_grid = 'XZ' def __view_changed(self, viewport_api): is_ortho = viewport_api.projection[3][3] == 1 if is_ortho: ortho_dir = viewport_api.transform.TransformDir((0, 0, 1)) ortho_dir = [abs(v) for v in ortho_dir] if ortho_dir[1] > ortho_dir[0] and ortho_dir[1] > ortho_dir[2]: self.__set_grid('XZ') elif ortho_dir[2] > ortho_dir[0] and ortho_dir[2] > ortho_dir[1]: self.__set_grid('XY') else: self.__set_grid('YZ') else: self.__on_stage_opened(viewport_api.stage) self.__set_grid(self.__persp_grid) def __viewport_grid_display_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: key = f"/persistent/app/viewport/{self.__viewport_api.id}/guide/grid/visible" self.visible = bool(carb.settings.get_settings().get(key)) @property def name(self): return 'Grid (legacy)' @property def categories(self): return ['guide'] @property def visible(self): return carb.settings.get_settings().get('/app/viewport/grid/enabled') @visible.setter def visible(self, value): carb.settings.get_settings().set('/app/viewport/grid/enabled', bool(value)) return self.visible def destroy(self): settings = carb.settings.get_settings() self.__destroy_view_tracking(settings) if self.__viewport_grid_vis_sub is not None: settings.unsubscribe_to_change_events(self.__viewport_grid_vis_sub) self.__viewport_grid_vis_sub = None if self.__auto_track_sub is not None: settings.unsubscribe_to_change_events(self.__auto_track_sub) self.__auto_track_sub = None class LegacyLightScene: def __init__(self, *args, **kwargs): carb.settings.get_settings().set_default('/app/viewport/show/lights', True) @property def name(self): return 'Lights (legacy)' @property def categories(self): return ['scene'] @property def visible(self): return carb.settings.get_settings().get('/app/viewport/show/lights') @visible.setter def visible(self, value): carb.settings.get_settings().set('/app/viewport/show/lights', bool(value)) return self.visible def destroy(self): pass class LegacyAudioScene: def __init__(self, *args, **kwargs): carb.settings.get_settings().set_default('/app/viewport/show/audio', True) @property def name(self): return 'Audio (legacy)' @property def categories(self): return ['scene'] @property def visible(self): return carb.settings.get_settings().get('/app/viewport/show/audio') @visible.setter def visible(self, value): carb.settings.get_settings().set('/app/viewport/show/audio', bool(value)) return self.visible def destroy(self): pass
6,306
Python
32.547872
117
0.615604
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/manipulator/camera.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportCameraManiulatorFactory'] from omni.kit.manipulator.camera import ViewportCameraManipulator import omni.kit.app import carb class ViewportCameraManiulatorFactory: VP1_CAM_VELOCITY = '/persistent/app/viewport/camMoveVelocity' VP1_CAM_INERTIA_ENABLED = '/persistent/app/viewport/camInertiaEnabled' VP1_CAM_INERTIA_SEC = '/persistent/app/viewport/camInertiaAmount' VP1_CAM_ROTATIONAL_STEP = '/persistent/app/viewport/camFreeRotationStep' VP1_CAM_LOOK_SPEED = '/persistent/app/viewport/camYawPitchSpeed' VP2_FLY_ACCELERATION = '/persistent/app/viewport/manipulator/camera/flyAcceleration' VP2_FLY_DAMPENING = '/persistent/app/viewport/manipulator/camera/flyDampening' VP2_LOOK_ACCELERATION = '/persistent/app/viewport/manipulator/camera/lookAcceleration' VP2_LOOK_DAMPENING = '/persistent/app/viewport/manipulator/camera/lookDampening' def __init__(self, desc: dict, *args, **kwargs): self.__manipulator = ViewportCameraManipulator(desc.get('viewport_api')) def setting_changed(value, event_type, set_fn): if event_type != carb.settings.ChangeEventType.CHANGED: return set_fn(value.get('', None)) self.__setting_subs = ( omni.kit.app.SettingChangeSubscription(ViewportCameraManiulatorFactory.VP1_CAM_VELOCITY, lambda *args: setting_changed(*args, self.__set_flight_velocity)), omni.kit.app.SettingChangeSubscription(ViewportCameraManiulatorFactory.VP1_CAM_INERTIA_ENABLED, lambda *args: setting_changed(*args, self.__set_inertia_enabled)), omni.kit.app.SettingChangeSubscription(ViewportCameraManiulatorFactory.VP1_CAM_INERTIA_SEC, lambda *args: setting_changed(*args, self.__set_inertia_seconds)), omni.kit.app.SettingChangeSubscription(ViewportCameraManiulatorFactory.VP2_FLY_ACCELERATION, lambda *args: setting_changed(*args, self.__set_flight_acceleration)), omni.kit.app.SettingChangeSubscription(ViewportCameraManiulatorFactory.VP2_FLY_DAMPENING, lambda *args: setting_changed(*args, self.__set_flight_dampening)), omni.kit.app.SettingChangeSubscription(ViewportCameraManiulatorFactory.VP2_LOOK_ACCELERATION, lambda *args: setting_changed(*args, self.__set_look_acceleration)), omni.kit.app.SettingChangeSubscription(ViewportCameraManiulatorFactory.VP2_LOOK_DAMPENING, lambda *args: setting_changed(*args, self.__set_look_dampening)) ) settings = carb.settings.get_settings() settings.set_default(ViewportCameraManiulatorFactory.VP1_CAM_VELOCITY, 5.0) settings.set_default(ViewportCameraManiulatorFactory.VP1_CAM_INERTIA_ENABLED, False) settings.set_default(ViewportCameraManiulatorFactory.VP1_CAM_INERTIA_SEC, 0.55) settings.set_default(ViewportCameraManiulatorFactory.VP2_FLY_ACCELERATION, 1000.0) settings.set_default(ViewportCameraManiulatorFactory.VP2_FLY_DAMPENING, 10.0) settings.set_default(ViewportCameraManiulatorFactory.VP2_LOOK_ACCELERATION, 2000.0) settings.set_default(ViewportCameraManiulatorFactory.VP2_LOOK_DAMPENING, 20.0) self.__set_flight_velocity(settings.get(ViewportCameraManiulatorFactory.VP1_CAM_VELOCITY)) self.__set_inertia_enabled(settings.get(ViewportCameraManiulatorFactory.VP1_CAM_INERTIA_ENABLED)) self.__set_inertia_seconds(settings.get(ViewportCameraManiulatorFactory.VP1_CAM_INERTIA_SEC)) self.__set_flight_acceleration(settings.get(ViewportCameraManiulatorFactory.VP2_FLY_ACCELERATION)) self.__set_flight_dampening(settings.get(ViewportCameraManiulatorFactory.VP2_FLY_DAMPENING)) self.__set_look_acceleration(settings.get(ViewportCameraManiulatorFactory.VP2_LOOK_ACCELERATION)) self.__set_look_dampening(settings.get(ViewportCameraManiulatorFactory.VP2_LOOK_DAMPENING)) def __set_inertia_enabled(self, value): if value is not None: self.__manipulator.model.set_ints('inertia_enabled', [1 if value else 0]) def __set_inertia_seconds(self, value): if value is not None: self.__manipulator.model.set_floats('inertia_seconds', [value]) def __set_flight_velocity(self, value): if value is not None: self.__manipulator.model.set_floats('fly_speed', [value]) def __set_flight_acceleration(self, value): if value is not None: self.__manipulator.model.set_floats('fly_acceleration', [value, value, value]) def __set_flight_dampening(self, value): if value is not None: self.__manipulator.model.set_floats('fly_dampening', [10, 10, 10]) def __set_look_acceleration(self, value): if value is not None: self.__manipulator.model.set_floats('look_acceleration', [value, value, value]) def __set_look_dampening(self, value): if value is not None: self.__manipulator.model.set_floats('look_dampening', [value, value, value]) def __vel_changed(self, value, event_type): if event_type != carb.settings.ChangeEventType.CHANGED: return self.__set_flight_velocity(value.get('', None)) def destroy(self): self.__setting_subs = None if self.__manipulator: self.__manipulator.destroy() self.__manipulator = None @property def categories(self): return ['manipulator'] @property def name(self): return 'Camera' @property def visible(self): return self.__manipulator.visible @visible.setter def visible(self, value): self.__manipulator.visible = bool(value) @property def manipulator(self): return self.__manipulator
6,147
Python
48.580645
175
0.715634
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/manipulator/object_click.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. ## __all__ = ["ObjectClickFactory"] from omni.ui import scene as sc from pxr import Gf, Sdf import carb import omni.kit.commands from ..raycast import perform_raycast_query KIT_COI_ATTRIBUTE = 'omni:kit:centerOfInterest' class ObjectClickGesture(sc.DoubleClickGesture): def __init__(self, viewport_api, mouse_button: int): super().__init__(mouse_button=mouse_button) self.__viewport_api = viewport_api def __query_completed(self, prim_path: str, world_space_pos, *args): if prim_path: viewport_api = self.__viewport_api stage = viewport_api.stage cam_path = viewport_api.camera_path cam_prim = stage.GetPrimAtPath(cam_path) if not cam_prim: carb.log_error(f'Could not find prim for camera path "{cam_path}"') return if True: # Get position directly from USD from pxr import Usd, UsdGeom hit_prim = stage.GetPrimAtPath(prim_path) if not hit_prim: carb.log_error(f'Could not find prim for hit path "{prim_path}"') return box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) prim_center = box_cache.ComputeWorldBound(hit_prim).ComputeCentroid() else: # Get the word-transform of the hit prim prim_matrix = Gf.Matrix4d(*viewport_api.usd_context.compute_path_world_transform(prim_path)) # Get the position of the center of the object (based on transform) prim_center = prim_matrix.Transform(Gf.Vec3d(0,0,0)) # Move the prim center into local space of the camera prim_center = viewport_api.view.Transform(prim_center) # Set the camera's center-of-interest attribute (in an undo-able way) coi_attr = cam_prim.GetAttribute(KIT_COI_ATTRIBUTE) omni.kit.commands.execute('ChangePropertyCommand', prop_path=coi_attr.GetPath(), value=prim_center, prev=coi_attr.Get() if coi_attr else None, type_to_create_if_not_exist=Sdf.ValueTypeNames.Vector3d) def on_ended(self, *args): if self.state == sc.GestureState.CANCELED: return self.__ndc_mouse = self.sender.gesture_payload.mouse mouse, viewport_api = self.__viewport_api.map_ndc_to_texture_pixel(self.__ndc_mouse) if mouse and viewport_api: perform_raycast_query( viewport_api=viewport_api, mouse_ndc=self.__ndc_mouse, mouse_pixel=mouse, on_complete_fn=self.__query_completed ) class ObjectClickManipulator(sc.Manipulator): VP_COI_SETTING = "/exts/omni.kit.viewport.window/coiDoubleClick" def __init__(self, viewport_api, mouse_button: int = 0, *args, **kwargs): super().__init__(*args, **kwargs) self.__gesture = ObjectClickGesture(viewport_api, mouse_button) self.__transform = None self.__screen = None settings = carb.settings.get_settings() self.__setting_sub = settings.subscribe_to_node_change_events(self.VP_COI_SETTING, self.__coi_enabled_changed) def __coi_enabled_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if self.__screen and event_type == carb.settings.ChangeEventType.CHANGED: self.__screen.visible = carb.settings.get_settings().get(self.VP_COI_SETTING) def on_build(self): # Need to hold a reference to this or the sc.Screen would be destroyed when out of scope self.__transform = sc.Transform() with self.__transform: self.__screen = sc.Screen(gesture=self.__gesture) # Enable / Disable functionality based on current setting value self.__coi_enabled_changed(None, carb.settings.ChangeEventType.CHANGED) def destroy(self): setting_sub, self.__setting_sub = self.__setting_sub, None if setting_sub is not None: carb.settings.get_settings().unsubscribe_to_change_events(setting_sub) if self.__transform: self.__transform.clear() self.__transform = None self.__screen = None def ObjectClickFactory(desc: dict): manip = ObjectClickManipulator(desc.get('viewport_api')) manip.categories = ('manipulator',) manip.name = 'ObjectClick' return manip
4,921
Python
43.745454
118
0.641739
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/manipulator/context_menu.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. ## __all__ = ["ViewportClickFactory"] from omni.ui import scene as sc from pxr import Gf from typing import Sequence import carb import importlib.util from ..raycast import perform_raycast_query class WorldSpacePositionCache: def __init__(self): self.__ndc_z = None def __cache_screen_ndc(self, viewport_api, world_space_pos: Gf.Vec3d): screen_space_pos = viewport_api.world_to_ndc.Transform(world_space_pos) self.__ndc_z = screen_space_pos[2] def get_world_position(self, viewport_api, prim_path: str, world_space_pos: Sequence[float], mouse_ndc: Sequence[float]): # Simple case, prim hit and world_space_pos is valid, cache NDC-z if prim_path: world_space_pos = Gf.Vec3d(*world_space_pos) self.__cache_screen_ndc(viewport_api, world_space_pos) return world_space_pos # No prim-path, deliver a best guess at world-position # If never over an object, cacluate NDC-z from camera's center-of-interest if self.__ndc_z is None: # Otherwise use the camera's center-of-interest as the depth camera = viewport_api.stage.GetPrimAtPath(viewport_api.camera_path) coi_attr = camera.GetAttribute('omni:kit:centerOfInterest') if coi_attr: world_space_pos = viewport_api.transform.Transform(coi_attr.Get(viewport_api.time)) self.__cache_screen_ndc(viewport_api, world_space_pos) # If we have depth (in NDC), move (x_ndc, y_ndz, z_ndc) to a world-space position if mouse_ndc and self.__ndc_z is not None: return viewport_api.ndc_to_world.Transform(Gf.Vec3d(mouse_ndc[0], mouse_ndc[1], self.__ndc_z)) # Nothing, return whatever it was return Gf.Vec3d(*world_space_pos) class ClickGesture(sc.ClickGesture): def __init__(self, viewport_api, mouse_button: int = 1): super().__init__(mouse_button=mouse_button) self.__viewport_api = viewport_api def __query_completed(self, prim_path: str, world_space_pos, *args): viewport_api = self.__viewport_api world_space_pos = WorldSpacePositionCache().get_world_position(viewport_api, prim_path, world_space_pos, self.__ndc_mouse) if not prim_path: selected_prims = viewport_api.usd_context.get_selection().get_selected_prim_paths() if len(selected_prims) == 1: prim_path = selected_prims[0] else: prim_path = None self.on_clicked(viewport_api.usd_context_name, prim_path, world_space_pos, viewport_api.stage) def on_ended(self, *args): self.__ndc_mouse = self.sender.gesture_payload.mouse mouse, viewport_api = self.__viewport_api.map_ndc_to_texture_pixel(self.__ndc_mouse) if mouse and viewport_api: perform_raycast_query( viewport_api=viewport_api, mouse_ndc=self.__ndc_mouse, mouse_pixel=mouse, on_complete_fn=self.__query_completed ) # User callback when click and Viewport query have completed def on_clicked(self, usd_context_name: str, prim_path: str, world_space_pos: Gf.Vec3d, stage): # Honor legacy setting /exts/omni.kit.window.viewport/showContextMenu, but ony when it is actually set legacy_show_context_menu = carb.settings.get_settings().get("/exts/omni.kit.window.viewport/showContextMenu") if (legacy_show_context_menu is not None) and (bool(legacy_show_context_menu) is False): return try: from omni.kit.context_menu import ViewportMenu ViewportMenu.show_menu( usd_context_name, prim_path, world_space_pos, stage ) except (AttributeError, ImportError): if importlib.util.find_spec('omni.kit.context_menu') is None: carb.log_error('omni.kit.context_menu must be loaded to use the context menu') else: carb.log_error('omni.kit.context_menu 1.3.7+ must be loaded to use the context menu') class ViewportClickManipulator(sc.Manipulator): def __init__(self, viewport_api, mouse_button: int = 1, *args, **kwargs): super().__init__(*args, **kwargs) self.__gesture = ClickGesture(viewport_api, mouse_button) self.__transform = None def on_build(self): # Need to hold a reference to this or the sc.Screen would be destroyed when out of scope self.__transform = sc.Transform() with self.__transform: self.__screen = sc.Screen(gesture=self.__gesture) def destroy(self): if self.__transform: self.__transform.clear() self.__transform = None self.__screen = None def ViewportClickFactory(desc: dict): manip = ViewportClickManipulator(desc.get('viewport_api')) manip.categories = ('manipulator',) manip.name = 'ContextMenu' return manip
5,396
Python
42.524193
130
0.647331
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/manipulator/selection.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['SelectionManipulatorItem'] from omni.kit.manipulator.selection import SelectionManipulator, SelectionMode import omni.usd class SelectionManipulatorItem: def __init__(self, desc: dict, *args, **kwargs): self.__viewport_api = desc.get('viewport_api') self.__manipulator = SelectionManipulator() model = self.__manipulator.model self.__model_changed_sub = model.subscribe_item_changed_fn(self.__model_changed) self.__initial_selection = None self.__selection_args = None def __reset_state(self): self.__initial_selection = None self.__selection_args = None def __handle_selection(self, model, ndc_rect, mode, viewport_api): # Attempt to support live-selection for add and invert modes # usd_context = viewport_api.usd_context # if not self.__initial_selection: # # Save the initial selection # self.__initial_selection = usd_context.get_selection().get_selected_prim_paths() # elif mode != omni.usd.PickingMode.RESET_AND_SELECT: # # Restore the initial selection so that add & invert do the right thing # usd_context.get_selection().set_selected_prim_paths(self.__initial_selection, True) # Map the NDC screen coordinates into texture space box_start, start_in = viewport_api.map_ndc_to_texture_pixel((ndc_rect[0], ndc_rect[1])) box_end, end_in = viewport_api.map_ndc_to_texture_pixel((ndc_rect[2], ndc_rect[3])) # Clamp selection box to texture in pixel-space resolution = viewport_api.resolution box_start = (max(0, min(resolution[0], box_start[0])), max(0, min(resolution[1], box_start[1]))) box_end = (max(0, min(resolution[0], box_end[0])), max(0, min(resolution[1], box_end[1]))) # If the selection box overlaps the Viewport, save the state; otherwise clear it if (box_start[0] < resolution[0]) and (box_end[0] > 0) and (box_start[1] > 0) and (box_end[1] < resolution[1]): self.__selection_args = box_start, box_end, mode else: self.__selection_args = None def __request_pick(self): # If not selection state (pick is 100% outside of the viewport); clear the UsdContext's selection if self.__selection_args is None: usd_context = self.__viewport_api.usd_context if usd_context: usd_context.get_selection().set_selected_prim_paths([], False) return args = self.__selection_args if hasattr(self.__viewport_api, 'request_pick'): self.__viewport_api.request_pick(*args) return self.__viewport_api.pick(args[0][0], args[0][1], args[1][0], args[1][1], args[2]) def __model_changed(self, model, item): # https://gitlab-master.nvidia.com/omniverse/kit/-/merge_requests/13725 if not hasattr(omni.usd, 'PickingMode'): import carb carb.log_error('No picking support in omni.hydratexture') return # We only care about rect and mode changes if item != model.get_item('ndc_rect') and item != model.get_item('mode'): return live_select = False ndc_rect = model.get_as_floats('ndc_rect') if not ndc_rect: if not live_select: self.__request_pick() return self.__reset_state() # Convert the mode into an omni.usd.PickingMode mode = model.get_as_ints('mode') if not mode: return self.__reset_state() mode = { SelectionMode.REPLACE: omni.usd.PickingMode.RESET_AND_SELECT, SelectionMode.APPEND: omni.usd.PickingMode.MERGE_SELECTION, SelectionMode.REMOVE: omni.usd.PickingMode.INVERT_SELECTION }.get(mode[0], None) if mode is None: return self.__reset_state() self.__handle_selection(model, ndc_rect, mode, self.__viewport_api) # For reset selection, we can live-select as the drag occurs # live_select = mode == omni.usd.PickingMode.RESET_AND_SELECT if live_select: self.__request_pick() def destroy(self): self.__model_changed_sub = None self.__manipulator = None self.__viewport_api = None @property def categories(self): return ['manipulator'] @property def name(self): return 'Selection' @property def visible(self): return self.__manipulator.visible @visible.setter def visible(self, value): self.__manipulator.visible = bool(value)
5,058
Python
40.130081
120
0.627916
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/tests/test_drag_drop.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. ## __all__ = ["TestDragDrop"] import omni.kit.test from omni.kit.test import AsyncTestCase import omni.usd from pxr import Sdf, UsdGeom from ..dragdrop.usd_file_drop_delegate import UsdFileDropDelegate from ..dragdrop.material_file_drop_delegate import MaterialFileDropDelegate from ..dragdrop.audio_file_drop_delegate import AudioFileDropDelegate class TestDragDrop(AsyncTestCase): async def setUp(self): self.usd_context_name = '' self.usd_context = omni.usd.get_context(self.usd_context_name) await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() async def tearDown(self): self.usd_context = None self.stage = None async def createNewStage(self, default_prim: str = None): self.usd_context_name = '' self.usd_context = omni.usd.get_context(self.usd_context_name) await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() if default_prim is not None: self.stage.SetDefaultPrim(UsdGeom.Xform.Define(self.stage, f'/{default_prim}').GetPrim()) def validate_sdf_path(self, file_drop: UsdFileDropDelegate, url: str): prim_path = file_drop.make_prim_path(self.stage, url) # Make sure the return value is a completely valid SdfPath self.assertIsNotNone(prim_path) self.assertTrue(Sdf.Path.IsValidPathString(prim_path.pathString)) # If it was dropped onto a stage wit a defaultPrim, make sure it was dropped into that Prim default_prim = self.stage.GetDefaultPrim() if default_prim: default_prim_path = default_prim.GetPath() self.assertEqual(prim_path.GetCommonPrefix(default_prim_path), default_prim_path) async def test_prim_name_generation_in_world(self): '''Test new prim is generated with a valid path under defaultPrim=World''' await self.createNewStage('World') usd_file_drop = UsdFileDropDelegate() # Test against a file path self.validate_sdf_path(usd_file_drop, '/fake/path.usda') self.validate_sdf_path(usd_file_drop, '/fake/path with spaces.usda') self.validate_sdf_path(usd_file_drop, '/fake/a_weird_name-off__-_that-is_ still odd.usda') # Test against an omni protocol self.validate_sdf_path(usd_file_drop, 'omni://fake/omnipath.usda') self.validate_sdf_path(usd_file_drop, 'omni://fake/1 omni path path with spaces.usda') self.validate_sdf_path(usd_file_drop, 'omni:///fake/a_weird_name-off__-_that-is_ still odd.usda') # Test a protocol other than omni, just use https self.validate_sdf_path(usd_file_drop, 'https://fake/protocolpath.usda') self.validate_sdf_path(usd_file_drop, 'https://fake/2 prot') self.validate_sdf_path(usd_file_drop, 'https:///fake/a_weird_name-off__-_that-is_ still odd.usda') async def test_prim_name_generation_in_another_world(self): '''Test new prim is generated with a valid path under defaultPrim=AnotherNonStandardWorld''' await self.createNewStage('AnotherNonStandardWorld') usd_file_drop = UsdFileDropDelegate() # Test against a file path self.validate_sdf_path(usd_file_drop, '/fake/path.usda') self.validate_sdf_path(usd_file_drop, '/fake/path with spaces.usda') self.validate_sdf_path(usd_file_drop, '/fake/a_weird_name-off__-_that-is_ still odd.usda') # Test against an omni protocol self.validate_sdf_path(usd_file_drop, 'omni://fake/omnipath.usda') self.validate_sdf_path(usd_file_drop, 'omni://fake/1 omni path path with spaces.usda') self.validate_sdf_path(usd_file_drop, 'omni:///fake/a_weird_name-off__-_that-is_ still odd.usda') # Test a protocol other than omni, just use https self.validate_sdf_path(usd_file_drop, 'https://fake/protocolpath.usda') self.validate_sdf_path(usd_file_drop, 'https://fake/2 prot') self.validate_sdf_path(usd_file_drop, 'https:///fake/a_weird_name-off__-_that-is_ still odd.usda') async def test_prim_name_root_generation(self): '''Test new prim is generated with a valid path''' await self.createNewStage() usd_file_drop = UsdFileDropDelegate() # Test against a file path self.validate_sdf_path(usd_file_drop, '/fake/path.usda') self.validate_sdf_path(usd_file_drop, '/fake/path with spaces.usda') self.validate_sdf_path(usd_file_drop, '/fake/a_weird_name-off__-_that-is_ still odd.usda') # Test against an omni protocol self.validate_sdf_path(usd_file_drop, 'omni://fake/omnipath.usda') self.validate_sdf_path(usd_file_drop, 'omni://fake/1 omni path path with spaces.usda') self.validate_sdf_path(usd_file_drop, 'omni:///fake/a_weird_name-off__-_that-is_ still odd.usda') # Test a protocol other than omni, just use https self.validate_sdf_path(usd_file_drop, 'https://fake/protocolpath.usda') self.validate_sdf_path(usd_file_drop, 'https://fake/2 prot') self.validate_sdf_path(usd_file_drop, 'https:///fake/a_weird_name-off__-_that-is_ still odd.usda') async def test_mdl_drop(self): '''Test Material will be accepted by MDL handler and denied by USD handler''' await self.createNewStage('World') usd_file_drop = UsdFileDropDelegate() mtl_file_drop = MaterialFileDropDelegate() def make_drop_object(url: str): return {'mime_data': url, 'usd_context_name': self.usd_context_name} self.assertFalse(usd_file_drop.accepted(make_drop_object('/fake/mdlfile.mdl'))) self.assertFalse(usd_file_drop.accepted(make_drop_object('https://fake/mdlfile.mdl'))) self.assertFalse(usd_file_drop.accepted(make_drop_object('material::https://fake/mdlfile.mdl'))) self.assertTrue(mtl_file_drop.accepted(make_drop_object('/fake/mdlfile.mdl'))) self.assertTrue(mtl_file_drop.accepted(make_drop_object('https://fake/mdlfile.mdl'))) self.assertFalse(mtl_file_drop.accepted(make_drop_object('material::https://fake/mdlfile.mdl'))) self.assertEqual(mtl_file_drop.accept_url('/fake/mdlfile.mdl'), '/fake/mdlfile.mdl') self.assertEqual(mtl_file_drop.accept_url('https://fake/mdlfile.mdl'), 'https://fake/mdlfile.mdl') self.assertFalse(mtl_file_drop.accept_url('material::https://fake/mdlfile.mdl')) async def test_mdl_drop_material_location(self): '''Test Material will be created in proper Scope location''' mtl_file_drop = MaterialFileDropDelegate() await self.createNewStage('World') self.assertEqual(mtl_file_drop.get_material_prim_location(self.stage), Sdf.Path('/World/Looks')) await self.createNewStage() self.assertEqual(mtl_file_drop.get_material_prim_location(self.stage), Sdf.Path('/Looks')) async def test_audio_drop_delegate(self): '''Test Audio will be created in proper location''' audio_drop = AudioFileDropDelegate() await self.createNewStage('World') def make_drop_object(url: str): return {'mime_data': url, 'usd_context_name': self.usd_context_name} self.validate_sdf_path(audio_drop, '/fake/path.wav') self.validate_sdf_path(audio_drop, '/fake/path.wave') self.validate_sdf_path(audio_drop, '/fake/path.ogg') self.validate_sdf_path(audio_drop, '/fake/path.mp3') self.assertFalse(audio_drop.accepted(make_drop_object('/fake/path.txt'))) self.assertFalse(audio_drop.accepted(make_drop_object('/fake/path.usda'))) self.assertFalse(audio_drop.accepted(make_drop_object('material::https://fake/mdlfile.mdl'))) async def test_ignored_dragdrop_protocols(self): '''Test DragDropDelegates to ensure registered protocols are ignored''' delegates = [UsdFileDropDelegate, MaterialFileDropDelegate, AudioFileDropDelegate] protocol = "test://" for delegate in delegates: self.assertFalse(delegate.is_ignored_protocol(protocol)) delegate.add_ignored_protocol(protocol) self.assertTrue(delegate.is_ignored_protocol(protocol+"test.ext")) delegate.remove_ignored_protocol(protocol) self.assertFalse(delegate.is_ignored_protocol(protocol)) async def test_ignored_dragdrop_extensions(self): '''Test DragDropDelegates to ensure registered extensions are ignored''' delegates = [UsdFileDropDelegate, MaterialFileDropDelegate, AudioFileDropDelegate] extension = ".test" for delegate in delegates: self.assertFalse(delegate.is_ignored_extension(extension)) delegate.add_ignored_extension(extension) self.assertTrue(delegate.is_ignored_extension("test"+extension)) delegate.remove_ignored_extension(extension) self.assertFalse(delegate.is_ignored_extension(extension))
9,484
Python
47.392857
106
0.67577
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/tests/test_window_viewport.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. ## __all__ = ["TestWindowViewport"] import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.window import ViewportWindow from pathlib import Path import carb import omni.usd import omni.timeline from pxr import Gf DATA_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.window}/data")).absolute().resolve() TEST_FILES = DATA_PATH.joinpath("tests") USD_FILES = TEST_FILES.joinpath("usd") TEST_WIDTH, TEST_HEIGHT = 360, 240 class TestWindowViewport(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() async def test_timeline_time_projection(self): """Test that changing attribute that affect projection work when time-sampled.""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) usd_context = vp_window.viewport_api.usd_context # L1 test without a render, so cannot lock to reults as there are none vp_window.viewport_api.lock_to_render_result = False await usd_context.open_stage_async(str(USD_FILES.joinpath("timesampled_camera.usda"))) timeline = omni.timeline.get_timeline_interface() timeline.set_current_time(2) timeline.commit() expected_proj = Gf.Matrix4d(2.542591218004352, 0, 0, 0, 0, 4.261867184464438, 0, 0, 0, 0, -1.000002000002, -1, 0, 0, -2.000002000002, 0) self.assertTrue(Gf.IsClose(expected_proj, vp_window.viewport_api.projection, 1e-07)) # Test no Window are reachable after destruction vp_window.destroy() del vp_window # Unblocks devices again await self.finalize_test_no_image() async def test_viewport_instance_resolution_serialization(self): """Test that restoring a Viewport instance resolution works from persistent data.""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) vp_window = None settings = carb.settings.get_settings() try: vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) self.assertEqual(vp_window.viewport_api.resolution, (1280, 720)) self.assertEqual(vp_window.viewport_api.resolution_scale, 1.0) finally: if vp_window: vp_window.destroy() del vp_window try: settings.set('/persistent/app/viewport/TestWindow/Viewport0/resolution', [512, 512]) settings.set('/persistent/app/viewport/TestWindow/Viewport0/resolutionScale', 0.25) vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) self.assertEqual(vp_window.viewport_api.full_resolution, (512, 512)) self.assertEqual(vp_window.viewport_api.resolution, (128, 128)) self.assertEqual(vp_window.viewport_api.resolution_scale, 0.25) finally: settings.destroy_item('/persistent/app/viewport/TestWindow/Viewport0/resolution') settings.destroy_item('/persistent/app/viewport/TestWindow/Viewport0/resolutionScale') if vp_window: vp_window.destroy() del vp_window # Unblocks devices again await self.finalize_test_no_image() async def test_viewport_startup_resolution_serialization(self): """Test that restoring a Viewport instance resolution works from startup data.""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) vp_window = None settings = carb.settings.get_settings() try: vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) self.assertEqual(vp_window.viewport_api.resolution, (1280, 720)) self.assertEqual(vp_window.viewport_api.resolution_scale, 1.0) finally: if vp_window: vp_window.destroy() del vp_window try: settings.set('/app/viewport/TestWindow/Viewport0/resolution', [1024, 1024]) settings.set('/app/viewport/TestWindow/Viewport0/resolutionScale', 0.125) vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) self.assertEqual(vp_window.viewport_api.full_resolution, (1024, 1024)) self.assertEqual(vp_window.viewport_api.resolution, (128, 128)) self.assertEqual(vp_window.viewport_api.resolution_scale, 0.125) finally: settings.destroy_item('/app/viewport/TestWindow/Viewport0/resolution') settings.destroy_item('/app/viewport/TestWindow/Viewport0/resolutionScale') if vp_window: vp_window.destroy() del vp_window # Unblocks devices again await self.finalize_test_no_image() async def test_viewport_globals_resolution_serialization(self): """Test that restoring a Viewport instance resolution works from startup global data.""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) vp_window = None settings = carb.settings.get_settings() try: vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) self.assertEqual(vp_window.viewport_api.resolution, (1280, 720)) self.assertEqual(vp_window.viewport_api.resolution_scale, 1.0) finally: if vp_window: vp_window.destroy() del vp_window try: settings.set('/app/viewport/defaults/resolution', [512, 512]) settings.set('/app/viewport/defaults/resolutionScale', 0.5) vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) self.assertEqual(vp_window.viewport_api.full_resolution, (512, 512)) self.assertEqual(vp_window.viewport_api.resolution, (256, 256)) self.assertEqual(vp_window.viewport_api.resolution_scale, 0.5) finally: settings.destroy_item('/app/viewport/defaults/resolution') settings.destroy_item('/app/viewport/defaults/resolutionScale') if vp_window: vp_window.destroy() del vp_window # Unblocks devices again await self.finalize_test_no_image() async def __test_viewport_hud_visibility(self, golden_img_name: str, visible: bool, bg_alpha: float = None): """Test that toggling Viewport HUD visibility.""" vp_window = None settings = carb.settings.get_settings() hud_setting_prefix = "/persistent/app/viewport/TestWindow/Viewport0/hud" hud_setting_keys = ("visible", "renderResolution/visible") golden_img_names = [f"{golden_img_name}_off.png", f"{golden_img_name}_on.png"] try: settings.destroy_item("/persistent/app/viewport/TestWindow/Viewport0") settings.destroy_item("/app/viewport/forceHideFps") settings.destroy_item("/app/viewport/showLayerMenu") for hk in hud_setting_keys: settings.set(f"{hud_setting_prefix}/{hk}", True) if bg_alpha is not None: settings.set("/persistent/app/viewport/ui/background/opacity", bg_alpha) settings.set(f"{hud_setting_prefix}/renderFPS/visible", False) settings.set(f"{hud_setting_prefix}/hostMemory/visible", False) await self.wait_n_updates() await self.create_test_area(width=320, height=240) vp_window = ViewportWindow('TestWindow', width=320, height=240) settings.set(f"{hud_setting_prefix}/visible", visible) await self.wait_n_updates() await self.capture_and_compare(golden_img_name=golden_img_names[visible], golden_img_dir=TEST_FILES) await self.wait_n_updates() settings.set(f"{hud_setting_prefix}/visible", not visible) await self.wait_n_updates() await self.finalize_test(golden_img_name=golden_img_names[not visible], golden_img_dir=TEST_FILES) finally: settings.destroy_item("/persistent/app/viewport/ui/background/opacity") if vp_window: vp_window.destroy() del vp_window async def test_viewport_hud_visibility(self): """Test that toggling Viewport HUD visibility works forward.""" await self.__test_viewport_hud_visibility("test_viewport_hud_visibility", True) async def test_viewport_hud_visibility_with_bg(self): """Test that toggling Viewport HUD visibility works and is affected by UI background color.""" await self.__test_viewport_hud_visibility("test_viewport_hud_visibility_no_bg", False, 0.0) async def test_camera_axis_resize(self): """Test that camera axis overlay properly sizes as requested.""" from omni.kit.viewport.window.scene.scenes import CameraAxisLayer async def test_size(camera_axis_layer, size, golden_img_name): """test custom sizes""" # one way to set the size settings.set(CameraAxisLayer.CAMERA_AXIS_SIZE_SETTING, size) # another way to set the size settings.set(f"{CameraAxisLayer.CAMERA_AXIS_SIZE_SETTING}/0", size[0]) settings.set(f"{CameraAxisLayer.CAMERA_AXIS_SIZE_SETTING}/1", size[1]) # wait for UI refresh await self.wait_n_updates() # read back the actual layer extents and check if the values are as expected self.assertEqual(camera_axis_layer._CameraAxisLayer__scene_view.width.value, float(size[0])) self.assertEqual(camera_axis_layer._CameraAxisLayer__scene_view.height.value, float(size[1])) # finally, the image test await self.capture_and_compare(golden_img_name=golden_img_name, golden_img_dir=TEST_FILES) await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) settings = carb.settings.get_settings() vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) viewport_api = vp_window.viewport_api # Test requires a USD context so that the implicit cameras are actually created await viewport_api.usd_context.new_stage_async() # turn the CameraAxisLayer on axis_visibility_key = f"/persistent/app/viewport/{viewport_api.id}/guide/axis/visible" axis_vis_restore = settings.get(axis_visibility_key) try: settings.set(axis_visibility_key, True) # get CameraAxis layer cam_axis_layer = vp_window._find_viewport_layer(layer_id="Axis", category="guide") self.assertTrue(cam_axis_layer is not None, "Axis widget is not available!") def_size = CameraAxisLayer.CAMERA_AXIS_DEFAULT_SIZE await test_size(cam_axis_layer, (def_size[0] + 20, def_size[1] + 30), "test_camera_axis_resize_enlarge.png") await test_size(cam_axis_layer, (def_size[0] - 20, def_size[1] - 30), "test_camera_axis_resize_shrink.png") finally: settings.set(axis_visibility_key, axis_vis_restore) if vp_window: vp_window.destroy() del vp_window await self.finalize_test_no_image() async def __test_engine_creation_arguments(self, hydra_engine_options, verify_engine): vp_window = None try: await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT, hydra_engine_options=hydra_engine_options) await self.wait_n_updates() self.assertIsNotNone(vp_window) await verify_engine(vp_window.viewport_widget.viewport_api._hydra_texture) finally: if vp_window: vp_window.destroy() del vp_window await self.finalize_test_no_image() async def test_engine_creation_default_arguments(self): '''Test default engine creation arguments''' hydra_engine_options = {} async def verify_engine(hydra_texture): settings = carb.settings.get_settings() tick_rate = settings.get(f"{hydra_texture.get_settings_path()}hydraTickRate") is_async = settings.get(f"{hydra_texture.get_settings_path()}async") is_async_ll = settings.get(f"{hydra_texture.get_settings_path()}asyncLowLatency") self.assertEqual(is_async, bool(settings.get("/app/asyncRendering"))) self.assertEqual(is_async_ll, bool(settings.get("/app/asyncRenderingLowLatency"))) self.assertEqual(tick_rate, int(settings.get("/persistent/app/viewport/defaults/tickRate"))) await self.__test_engine_creation_arguments(hydra_engine_options, verify_engine) async def test_engine_creation_forward_arguments(self): '''Test forwarding of engine creation arguments''' settings = carb.settings.get_settings() # Make sure the defaults are in a state that overrides from hydra_engine_options can be tested self.assertFalse(bool(settings.get("/app/asyncRendering"))) self.assertFalse(bool(settings.get("/app/asyncRenderingLowLatency"))) self.assertNotEqual(30, int(settings.get("/persistent/app/viewport/defaults/tickRate"))) try: hydra_engine_options = { "is_async": True, "is_async_low_latency": True, "hydra_tick_rate": 30 } async def verify_engine(hydra_texture): tick_rate = settings.get(f"{hydra_texture.get_settings_path()}hydraTickRate") is_async = settings.get(f"{hydra_texture.get_settings_path()}async") is_async_ll = settings.get(f"{hydra_texture.get_settings_path()}asyncLowLatency") self.assertEqual(is_async, hydra_engine_options.get("is_async")) self.assertEqual(is_async_ll, hydra_engine_options.get("is_async_low_latency")) self.assertEqual(tick_rate, hydra_engine_options.get("hydra_tick_rate")) await self.__test_engine_creation_arguments(hydra_engine_options, verify_engine) finally: settings.set("/app/asyncRendering", False) settings.destroy_item("/app/asyncRenderingLowLatency")
15,016
Python
44.923547
144
0.647376
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/tests/test_events.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. ## __all__ = ["Test01_ViewportEvents"] import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.window import ViewportWindow from pathlib import Path import carb from carb.input import MouseEventType import omni.kit.app from omni.kit.ui_test import emulate_mouse_move_and_click, emulate_mouse_scroll, Vec2 from omni.kit.ui_test.input import emulate_mouse import math DATA_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.window}/data")) TESTS_PATH = DATA_PATH.joinpath("tests").absolute().resolve() USD_FILES = TESTS_PATH.joinpath("usd") TEST_WIDTH, TEST_HEIGHT = 360, 240 # # XXX: This test must run first!!! This is likely due to block_devices=False argument below, which conflicts with # the default block_devices=True argument that is used if other tests are run first? # class Test01_ViewportEvents(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() @staticmethod async def wait_frames(app, n_frame: int = 3): for _ in range(n_frame): await app.next_update_async() async def __test_camera_scroll_wheel(self, initial_speed: float, scroll_y: float, vel_scale: float, test_op): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) app = omni.kit.app.get_app() settings = carb.settings.get_settings() settings.set('/persistent/app/viewport/camMoveVelocity', initial_speed) settings.set('/persistent/app/viewport/camVelocityScalerMultAmount', vel_scale) settings.set('/persistent/app/viewport/show/flySpeed', True) await self.wait_frames(app) vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) # Odd, but need to scale scroll by window height ? y_scroll_scale = scroll_y * TEST_HEIGHT try: await emulate_mouse_move_and_click(Vec2(TEST_WIDTH-40, TEST_HEIGHT-40)) settings.set('/exts/omni.kit.manipulator.camera/viewportMode', [vp_window.viewport_api.id, 'fly']) await self.wait_frames(app) await emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN) await app.next_update_async() for _ in range(15): await emulate_mouse_scroll(Vec2(0, y_scroll_scale)) await app.next_update_async() test_op(settings.get('/persistent/app/viewport/camMoveVelocity')) finally: await emulate_mouse(MouseEventType.RIGHT_BUTTON_UP) await app.next_update_async() settings.set('/persistent/app/viewport/camMoveVelocity', 5) settings.set('/persistent/app/viewport/camVelocityScalerMultAmount', 1) settings.set('/persistent/app/viewport/show/flySpeed', False) settings.set('/exts/omni.kit.manipulator.camera/viewportMode', None) # Test no Window are reachable after destruction vp_window.destroy() del vp_window # Restore devices and window sizes again await self.finalize_test_no_image() async def test_camera_speed_scroll_wheel_down(self): """Test that the camera-speed scroll adjusts speed within proper ranges when adjusting speed down.""" initial_speed = 0.001 def test_range(value): self.assertTrue(value > 0, msg="Camera speed has become or fallen below zero") self.assertTrue(value < initial_speed, msg="Camera speed has wrapped around") await self.__test_camera_scroll_wheel(initial_speed, -1, 1.1, test_range) async def test_camera_speed_scroll_up(self): """Test that the camera-speed scroll adjusts speed within proper ranges when adjusting speed up.""" initial_speed = 1.7976931348623157e+307 def test_range(value): self.assertTrue(math.isfinite(value), msg="Camera speed has become infinite") self.assertTrue(value > initial_speed, msg="Camera speed has wrapped around") await self.__test_camera_scroll_wheel(initial_speed, 1, 1.4, test_range) async def test_camera_speed_buttons(self): """""" import carb settings = carb.settings.get_settings() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) settings.set("/persistent/app/viewport/TestWindow/Viewport0/hud/visible", True) settings.set("/persistent/app/viewport/TestWindow/Viewport0/hud/cameraSpeed/visible", True) settings.set("/persistent/app/viewport/TestWindow/Viewport0/hud/renderResolution/visible", False) settings.set("/persistent/exts/omni.kit.viewport.window/cameraSpeedMessage/showFlyViewLock", True) settings.set("/persistent/exts/omni.kit.viewport.window/cameraSpeedMessage/collapsed", False) settings.set("/persistent/exts/omni.kit.manipulator.camera/flyViewLock", False) settings.set("/app/viewport/forceHideFps", False) fade_in = settings.get("/exts/omni.kit.viewport.window/cameraSpeedMessage/fadeIn") settings.set("/exts/omni.kit.viewport.window/cameraSpeedMessage/fadeIn", 0) vp_window = None click_received = False app = omni.kit.app.get_app() await self.wait_frames(app) import omni.ui.scene as sc from omni.kit.viewport.registry import RegisterScene class ObjectClickGesture(sc.ClickGesture): def on_ended(self, *args): nonlocal click_received click_received = True class ViewportClickManipulator(sc.Manipulator): def __init__(self, viewport_desc): super().__init__() def on_build(self): # Need to hold a reference to this or the sc.Screen would be destroyed when out of scope self.__transform = sc.Transform() with self.__transform: self.__screen = sc.Screen(gesture=ObjectClickGesture(mouse_button=0)) scoped_factory = RegisterScene(ViewportClickManipulator, 'omni.kit.viewport.window.tests.test_camera_speed_buttons') try: vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) settings.set("/exts/omni.kit.manipulator.camera/viewportMode", [vp_window.viewport_api.id, "fly"]) await self.wait_frames(app) await self.capture_and_compare(golden_img_dir=TESTS_PATH, golden_img_name="test_camera_speed_buttons_start.png") await self.wait_frames(app) await emulate_mouse_move_and_click(Vec2(30, 85)) await self.capture_and_compare(golden_img_dir=TESTS_PATH, golden_img_name="test_camera_speed_buttons_down.png") await self.wait_frames(app) await emulate_mouse_move_and_click(Vec2(30, 85)) await self.capture_and_compare(golden_img_dir=TESTS_PATH, golden_img_name="test_camera_speed_buttons_up.png") await self.wait_frames(app) await emulate_mouse_move_and_click(Vec2(275, 105)) await self.wait_frames(app, 100) await self.capture_and_compare(golden_img_dir=TESTS_PATH, golden_img_name="test_camera_speed_lock_down.png") self.assertFalse(click_received) finally: if vp_window: vp_window.destroy() del vp_window settings.set("/exts/omni.kit.viewport.window/cameraSpeedMessage/fadeIn", fade_in) settings.destroy_item("/persistent/app/viewport/TestWindow/Viewport0/hud/visible") settings.destroy_item("/persistent/app/viewport/TestWindow/Viewport0/hud/cameraSpeed/visible") settings.destroy_item("/persistent/exts/omni.kit.viewport.window/cameraSpeedMessage/showFlyViewLock") settings.destroy_item("/persistent/exts/omni.kit.viewport.window/cameraSpeedMessage/collapsed") settings.destroy_item("/persistent/app/viewport/TestWindow/Viewport0/hud/renderResolution/visible") settings.destroy_item("/persistent/exts/omni.kit.manipulator.camera/flyViewLock") settings.destroy_item("/app/viewport/forceHideFps") await self.finalize_test_no_image()
8,766
Python
44.900523
124
0.675337
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/tests/test_window_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. ## __all__ = ["TestWindowAPI"] import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import carb import omni.usd import omni.ui as ui from omni.kit.viewport.window import ViewportWindow, get_viewport_window_instances CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.window}/data")) TEST_WIDTH, TEST_HEIGHT = 360, 240 NUM_DEFAULT_WINDOWS = 0 class TestWindowAPI(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") self.assertNoViewportWindows() # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() @staticmethod async def wait_frames(n_frames: int = 3): app = omni.kit.app.get_app() for _ in range(n_frames): await app.next_update_async() def assertNoViewportWindows(self): self.assertEqual(NUM_DEFAULT_WINDOWS, sum(1 for x in get_viewport_window_instances())) async def test_new_window(self): """Test basic creartion of a ViewportWindow""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) self.assertIsNotNone(vp_window) self.assertEqual('', vp_window.viewport_api.usd_context_name) self.assertEqual(1 + NUM_DEFAULT_WINDOWS, sum(1 for x in get_viewport_window_instances())) await self.wait_frames() await self.finalize_test(golden_img_dir=self._golden_img_dir) # Test no Window are reachable after destruction vp_window.destroy() del vp_window self.assertNoViewportWindows() async def _test_post_message(self, vp_callback, golden_img_name: str): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) settings = carb.settings.get_settings() try: # These 0 avoid a fade-in fade-out animation, but also test that zero is valid (no divide by zero) settings.set('/app/viewport/toastMessage/fadeIn', 0) settings.set('/app/viewport/toastMessage/fadeOut', 0) # Keep the message for a short amount of time settings.set('/app/viewport/toastMessage/seconds', 0.5) # Need to show the Viewport Hud globally, it contains the scroll speed settings.set('/app/viewport/forceHideFps', False) settings.destroy_item("/persistent/app/viewport/TestWindow/Viewport0") vp_window = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) vp_callback(vp_window) await self.wait_frames() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) finally: # Restore to default state settings.set('/app/viewport/toastMessage/seconds', 3) settings.set('/app/viewport/toastMessage/fadeIn', 0.5) settings.set('/app/viewport/toastMessage/fadeOut', 0.5) settings.set("/app/viewport/forceHideFps", True) # Test no Window are reachable after destruction vp_window.destroy() del vp_window self.assertNoViewportWindows() async def test_post_message(self): """Test the legacy post-message API works for a single line""" def vp_callback(vp_window): vp_window._post_toast_message("My First Message", "message_id.0") await self._test_post_message(vp_callback, golden_img_name="single_messages.png") async def test_post_multiple_messages(self): """Test the legacy post-message API works for multiple lines""" def vp_callback(vp_window): vp_window._post_toast_message("My First Message", "message_id.0") vp_window._post_toast_message("My Second Message", "message_id.1") vp_window._post_toast_message("My Third Message", "message_id.2") vp_window._post_toast_message("My First Message Changed", "message_id.0") await self._test_post_message(vp_callback, golden_img_name="multiple_messages.png") async def test_post_message_no_background(self): """Test the legacy post-message API works without a background""" def vp_callback(vp_window): vp_window._post_toast_message("Message with no BG", "message_id.0") settings = carb.settings.get_settings() try: settings.set("/persistent/app/viewport/ui/background/opacity", 0.0) await self._test_post_message(vp_callback, golden_img_name="single_messages_no_bg.png") finally: settings.destroy_item("/persistent/app/viewport/ui/background/opacity") async def test_new_window_custom_context(self): """Test instantiating a ViewportWindow to non-default omni.UsdContext""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_context_name = 'TestContext' usd_context = omni.usd.create_context(usd_context_name) vp_window = ViewportWindow(f'Custom UsdContext {usd_context_name}', usd_context_name=usd_context_name, width=TEST_WIDTH, height=TEST_HEIGHT) self.assertIsNotNone(vp_window) self.assertEqual(usd_context, vp_window.viewport_api.usd_context) self.assertEqual(usd_context_name, vp_window.viewport_api.usd_context_name) # This should equal 0, as it retrieves only ViewportWindow on UsdContext '' self.assertEqual(0 + NUM_DEFAULT_WINDOWS, sum(1 for x in get_viewport_window_instances())) # This should equal 1, as it retrieves only ViewportWindow on UsdContext 'TestContext' self.assertEqual(1 + NUM_DEFAULT_WINDOWS, sum(1 for x in get_viewport_window_instances(usd_context_name))) # This should also equal 1, as it retrieves -all- ViewportWindow on any UsdContext self.assertEqual(1 + NUM_DEFAULT_WINDOWS, sum(1 for x in get_viewport_window_instances(None))) await self.wait_frames() await self.finalize_test(golden_img_dir=self._golden_img_dir) # Test no Window are reachable after destruction vp_window.destroy() del vp_window self.assertNoViewportWindows() async def test_new_window_add_frame(self): """Test add_frame API for a ViewportWindow instance""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) vp_window = None settings = carb.settings.get_settings() settings.set("/rtx/post/backgroundZeroAlpha/enabled", True) try: vp_window = ViewportWindow('TestWindowWithFrame', width=TEST_WIDTH, height=TEST_HEIGHT) custom_frame = vp_window.get_frame('custom_frame') # Test the frame is returned from a second call with the same name self.assertEqual(custom_frame, vp_window.get_frame('custom_frame')) with custom_frame: ui.Rectangle(width=TEST_WIDTH, height=TEST_HEIGHT / 2, style_type_name_override='CustomFrame') vp_window.set_style({ 'ViewportBackgroundColor': {'background_color': 0xffff0000}, 'CustomFrame': {'background_color': 0xff0000ff}, }) await self.wait_frames() await self.finalize_test(golden_img_dir=self._golden_img_dir) finally: settings.destroy_item("/rtx/post/backgroundZeroAlpha/enabled") # Test no Window are reachable after destruction if vp_window: vp_window.destroy() del vp_window self.assertNoViewportWindows() async def test_viewport_widget_api(self): """Test ViewportWidget and ViewportAPI accessors on a ViewportWindow instance""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) vp_window = ViewportWindow('TestWindowWithFrame', width=TEST_WIDTH, height=TEST_HEIGHT) self.assertIsNotNone(vp_window.viewport_widget) self.assertIsNotNone(vp_window.viewport_widget.display_delegate) # Test no Window are reachable after destruction vp_window.destroy() del vp_window self.assertNoViewportWindows() # Unblocks devices again await self.finalize_test_no_image() async def __test_hud_memory_info(self, settings, name: str): if name != "Host": # Chaneg from defaults to values settings.set("/exts/omni.kit.viewport.window/hud/hostMemory/label", name) settings.set("/exts/omni.kit.viewport.window/hud/hostMemory/perProcess", True) else: # Need to test lack of any values still instantiates a usable ViewportWindow self.assertEqual(settings.get("/exts/omni.kit.viewport.window/hud/hostMemory/label"), None) self.assertEqual(settings.get("/exts/omni.kit.viewport.window/hud/hostMemory/perProcess"), None) await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) vp_window = ViewportWindow('TestWindowHudMemory', width=TEST_WIDTH, height=TEST_HEIGHT) found_layer = vp_window._find_viewport_layer(f"{name} Memory") is not None vp_window.destroy() del vp_window self.assertTrue(found_layer) self.assertNoViewportWindows() async def test_hud_memory_info(self): """Test ability to change label of Viewport HUD memory""" settings = carb.settings.get_settings() try: settings.set("/app/viewport/forceHideFps", False) await self.__test_hud_memory_info(settings, "Host") await self.__test_hud_memory_info(settings, "Process") finally: # Reset to known prior defaults by delting these items settings.destroy_item("/app/viewport/forceHideFps") settings.destroy_item("/exts/omni.kit.viewport.window/hud/hostMemory/label") settings.destroy_item("/exts/omni.kit.viewport.window/hud/hostMemory/perProcess") await self.finalize_test_no_image()
10,595
Python
43.708861
148
0.665219
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/events/delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportEventDelegate'] from ..dragdrop.handler import DragDropHandler import carb import math import traceback def _limit_camera_velocity(value: float, settings: carb.settings.ISettings, context_name: str): cam_limit = settings.get('/exts/omni.kit.viewport.window/cameraSpeedLimit') if context_name in cam_limit: vel_min = settings.get('/persistent/app/viewport/camVelocityMin') if vel_min is not None: value = max(vel_min, value) vel_max = settings.get('/persistent/app/viewport/camVelocityMax') if vel_max is not None: value = min(vel_max, value) return value class ViewportEventDelegate: def __init__(self, scene_view, viewport_api): self.__scene_view = scene_view self.__viewport_api = viewport_api scene_view.set_mouse_wheel_fn(self.mouse_wheel) scene_view.set_key_pressed_fn(self.key_pressed) scene_view.set_accept_drop_fn(self.drop_accept) scene_view.set_drop_fn(self.drop) scene_view.scroll_only_window_hovered = True self.__dd_handler = None self.__key_down = set() def destroy(self): scene_view = self.scene_view if scene_view: scene_view.set_mouse_wheel_fn(None) scene_view.set_key_pressed_fn(None) scene_view.set_accept_drop_fn(None) scene_view.set_drop_fn(None) self.__scene_view = None @property def scene_view(self): try: if self.__scene_view: return self.__scene_view except ReferenceError: pass return None @property def viewport_api(self): try: if self.__viewport_api: return self.__viewport_api except ReferenceError: pass return None @property def drag_drop_handler(self): return self.__dd_handler def adjust_flight_speed(self, x: float, y: float): try: import omni.appwindow iinput = carb.input.acquire_input_interface() app_window = omni.appwindow.get_default_app_window() mouse = app_window.get_mouse() mouse_value = iinput.get_mouse_value(mouse, carb.input.MouseInput.RIGHT_BUTTON) if mouse_value > 0: settings = carb.settings.get_settings() value = settings.get('/persistent/app/viewport/camMoveVelocity') or 1 scaler = settings.get('/persistent/app/viewport/camVelocityScalerMultAmount') or 1.1 scaler = 1.0 + (max(scaler, 1.0 + 1e-8) - 1.0) * abs(y) if y < 0: value = value / scaler elif y > 0: value = value * scaler if math.isfinite(value) and (value > 1e-8): value = _limit_camera_velocity(value, settings, 'scroll') settings.set('/persistent/app/viewport/camMoveVelocity', value) return True # OM-58310: orbit + scroll does not behave well together, but when scroll is moved to omni.ui.scene # they cannot both exists anyway, so disable this possibility for now by returning True if any button down return (iinput.get_mouse_value(mouse, carb.input.MouseInput.LEFT_BUTTON) or iinput.get_mouse_value(mouse, carb.input.MouseInput.MIDDLE_BUTTON)) except Exception: carb.log_error(f"Traceback:\n{traceback.format_exc()}") return False def mouse_wheel(self, x: float, y: float, modifiers: int): # Do not use horizontal scroll at all (do we want to hide this behind a setting, or allow it for speed bu not zoom) x = 0 # Try to apply flight speed first (should be applied when flight-mode key is active) if self.adjust_flight_speed(x, y): return # If a key is down, ignore the wheel-event (i.e. don't zoom on paint b+scroll event) if self.__key_down: import omni.appwindow app_window = omni.appwindow.get_default_app_window() key_input = carb.input.acquire_input_interface() keyboard = app_window.get_keyboard() app_window.get_keyboard() for key in self.__key_down: if key_input.get_keyboard_value(keyboard, key): return self.__key_down = set() try: from omni.kit.manipulator.camera.viewport_camera_manipulator import _zoom_operation _zoom_operation(x, y, self.viewport_api) except Exception: carb.log_error(f"Traceback:\n{traceback.format_exc()}") def key_pressed(self, key_index: int, modifiers: int, is_down: bool): # Ignore all key-modifier up/down events, only care about escape or blocking scroll with real-key if key_index >= int(carb.input.KeyboardInput.LEFT_SHIFT): return if key_index == int(carb.input.KeyboardInput.ESCAPE): self.stop_drag_drop() return if is_down: self.__key_down.add(carb.input.KeyboardInput(key_index)) else: self.__key_down.discard(carb.input.KeyboardInput(key_index)) def mouse_moved(self, x: float, y: float, modifiers: int, is_pressed: bool, *args): if self.__dd_handler: self.__dd_handler._perform_query(self.__scene_view, (x, y)) def drop_accept(self, url: str): dd_handler = DragDropHandler({ 'viewport_api': self.__viewport_api, 'scene_view': self.__scene_view }) if not dd_handler.accepted(self.__scene_view, url): return False self.__dd_handler = dd_handler self.__scene_view.set_mouse_moved_fn(self.mouse_moved) self.__scene_view.set_mouse_hovered_fn(self.mouse_hovered) return True def drop(self, data): dd_handler = self.stop_drag_drop(False) if dd_handler: dd_handler.dropped(self.__scene_view, data) def mouse_hovered(self, value: bool, *args): if not value and self.__dd_handler: self.stop_drag_drop() def stop_drag_drop(self, cancel: bool = True): dd_handler, self.__dd_handler = self.__dd_handler, None self.__scene_view.set_mouse_moved_fn(None) self.__scene_view.set_mouse_hovered_fn(None) if dd_handler and cancel: dd_handler.cancel(self) return dd_handler
6,931
Python
39.302325
123
0.608859
omniverse-code/kit/exts/omni.kit.viewport.window/omni/kit/viewport/window/events/__init__.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportEventDelegate', 'add_event_delegation', 'remove_event_delegation', 'set_ui_delegate'] from .delegate import ViewportEventDelegate _ui_delegate_setup = ViewportEventDelegate _ui_delegate_list = [] def add_event_delegation(scene_view, viewport_api): global _ui_delegate_setup if _ui_delegate_setup: delegate = _ui_delegate_setup(scene_view, viewport_api) if delegate: _ui_delegate_list.append(delegate) def remove_event_delegation(in_scene_view): global _ui_delegate_list new_delegate_list = [] for delegate in _ui_delegate_list: scene_view = delegate.scene_view if delegate and scene_view != in_scene_view: new_delegate_list.append(delegate) elif delegate: delegate.destroy() _ui_delegate_list = new_delegate_list def set_ui_delegate(ui_delegate_setup): global _ui_delegate_setup, _ui_delegate_list _ui_delegate_setup = ui_delegate_setup new_delegate_list = [] if ui_delegate_setup: # Transfer all valid event handling to the new delegate for delegate in _ui_delegate_list: scene_view = delegate.scene_view viewport_api = delegate.viewport_api if scene_view and viewport_api: delegate = ui_delegate_setup(scene_view, viewport_api) if delegate: new_delegate_list.append(delegate) # Destroy all of the old event delegates for delegate in _ui_delegate_list: try: delegate.destroy() except Exception: carb.log_error(f"Traceback:\n{traceback.format_exc()}") _ui_delegate_list = new_delegate_list
2,127
Python
33.885245
105
0.67748
omniverse-code/kit/exts/omni.kit.viewport.window/docs/index.rst
omni.kit.viewport.window ################################ .. mdinclude:: README.md .. toctree:: :maxdepth: 1 README API (python) <API.rst> CHANGELOG
168
reStructuredText
13.083332
32
0.5