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.preferences/omni/kit/window/preferences/scripts/preferences_actions.py
import omni.kit.actions.core def register_actions(extension_id, cls, get_self_fn): action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "Window Preferences Actions" # actions action_registry.register_action( extension_id, "show_preferences_window", get_self_fn().show_preferences_window, display_name="Show Preferences Window", description="Show Preferences Window", tag=actions_tag, ) action_registry.register_action( extension_id, "hide_preferences_window", get_self_fn().hide_preferences_window, display_name="Hide Preferences Window", description="Hide Preferences Window", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_preferences_window", get_self_fn()._toggle_preferences_window, display_name="Toggle Preferences Window", description="Toggle Preferences Window", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
1,202
Python
29.074999
70
0.666389
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/material_path_widget.py
import os import pathlib import carb import carb.settings import omni.kit.notification_manager as nm import omni.ui as ui from omni.kit.window.filepicker import FilePickerDialog from omni.mdl import pymdlsdk from omni.ui import color as cl from . import material_config_utils from . material_config_widget import EditableListItemDelegate, EditableListModel, EditableListWidget class MdlPathItem(ui.AbstractItem): def __init__(self, text): super().__init__() text = pathlib.PurePath(text).as_posix() self.name_model = ui.SimpleStringModel(text) class MdlDefaultPathListModel(ui.AbstractItemModel): SOURCE_MDL_SYSTEM_PATH = 0 SOURCE_MDL_USER_PATH = 1 SOURCE_ADDITIONAL_SYSTEM_PATHS = 2 SOURCE_ADDITIONAL_USER_PATHS = 3 SOURCE_RENDERER_REQUIRED = 4 SOURCE_RENDERER_TEMPLATES = 5 def __init__(self, mode): super().__init__() self._SETTING_NAME_MAP = { self.SOURCE_ADDITIONAL_SYSTEM_PATHS: "/app/mdl/additionalSystemPaths", self.SOURCE_ADDITIONAL_USER_PATHS: "/app/mdl/additionalUserPaths", self.SOURCE_RENDERER_REQUIRED: "/renderer/mdl/searchPaths/required", self.SOURCE_RENDERER_TEMPLATES: "/renderer/mdl/searchPaths/templates" } _FN_MAP = { self.SOURCE_MDL_SYSTEM_PATH: self._get_paths_from_mdl_config, self.SOURCE_MDL_USER_PATH: self._get_paths_from_mdl_config, self.SOURCE_ADDITIONAL_SYSTEM_PATHS: self._get_paths_from_setting, self.SOURCE_ADDITIONAL_USER_PATHS: self._get_paths_from_setting, self.SOURCE_RENDERER_REQUIRED: self._get_paths_from_setting, self.SOURCE_RENDERER_TEMPLATES: self._get_paths_from_setting } self._items = [] paths = _FN_MAP[mode](mode) for path in paths: self._items.append(MdlPathItem(path)) def _get_omni_neuray_api(self): import omni.mdl.neuraylib neuraylib = omni.mdl.neuraylib.get_neuraylib() ineuray = neuraylib.getNeurayAPI() neuray = pymdlsdk.attach_ineuray(ineuray) return neuray def _get_paths_from_mdl_config(self, mode): neuray = self._get_omni_neuray_api() paths = [] with neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg: if mode == self.SOURCE_MDL_SYSTEM_PATH: num_paths = cfg.get_mdl_system_paths_length() if num_paths: for i in range(0, num_paths): paths.append(cfg.get_mdl_system_path(i)) elif mode == self.SOURCE_MDL_USER_PATH: num_paths = cfg.get_mdl_user_paths_length() if num_paths: for i in range(0, num_paths): paths.append(cfg.get_mdl_user_path(i)) else: pass return paths def _get_paths_from_setting(self, mode): settings = carb.settings.get_settings() pathStr = settings.get(self._SETTING_NAME_MAP[mode]) paths = [] if pathStr: paths = pathStr.split(";") return paths def get_item_children(self, item): if item is not None: return [] return self._items def get_item_value_model_count(self, item): return 1 def get_item_value_model(self, item, column_id): if item and isinstance(item, MdlPathItem): return item.name_model def get_items(self): return self._items class MdlDefaultPathListWidget(ui.Widget): _TREEVIEW_STYLE = { "TreeView.Item": { "margin": 3, "font_size": 16.0, "color": cl("#777777") } } _FRAME_STYLE = { "CollapsableFrame": { "margin": 0, "padding": 3, "border_width": 0, "border_radius": 0, "secondary_color": cl("#2c2e2e") } } def __init__(self, **kwargs): super(MdlDefaultPathListWidget).__init__() self._models = {} entries = [ ["Standard System Paths", MdlDefaultPathListModel.SOURCE_MDL_SYSTEM_PATH], ["Additional System Paths", MdlDefaultPathListModel.SOURCE_ADDITIONAL_SYSTEM_PATHS], ["Standard User Paths", MdlDefaultPathListModel.SOURCE_MDL_USER_PATH], ["Additional User Paths", MdlDefaultPathListModel.SOURCE_ADDITIONAL_USER_PATHS], ["Renderer Required", MdlDefaultPathListModel.SOURCE_RENDERER_REQUIRED], ["Renderer Templates", MdlDefaultPathListModel.SOURCE_RENDERER_TEMPLATES] ] with ui.VStack(height=0): for entry in entries: model = MdlDefaultPathListModel(entry[1]) if not model.get_items(): continue # do not add widget if it is empty self._add_path_list_widget(entry[0], model) self._models[entry[1]] = model def _add_path_list_widget(self, title, model): with ui.CollapsableFrame(title, collapsed=True, style=self._FRAME_STYLE): with ui.ScrollingFrame(height=100): view = ui.TreeView( model, header_visible=False, root_visible=False, style=self._TREEVIEW_STYLE ) # do not allow select items view.set_selection_changed_fn(lambda i: view.clear_selection()) class MdlLocalPathListModel(EditableListModel): def __init__(self, setting_path): super().__init__( MdlPathItem, setting_path ) def populate_items(self): pathStr = self._settings.get(self._setting_path) paths = pathStr.split(";") if pathStr else [] self._items.clear() for path in paths: if not path: continue self._items.append(self._item_class(path)) self._item_changed(None) def find_path(self, path): pp = pathlib.PurePath(path) for item in self._items: ip = pathlib.PurePath(item.name_model.as_string) if pp == ip: return ip.as_posix() return "" def sanity_check_paths(self): bad_paths = [] for item in self._items: path = item.name_model.as_string if not os.path.exists(path): bad_paths.append(path) return bad_paths def save_entries_to_settings(self): pathStrs = [item.name_model.as_string for item in self._items] pathStr = ";".join(pathStrs) self._settings.set(self._setting_path, pathStr) def save_to_material_config_file(self): material_config_utils.save_carb_setting_to_config_file( "/app/mdl/nostdpath", "/options/noStandardPath" ) material_config_utils.save_carb_setting_to_config_file( self._setting_path, "/searchPaths/local", is_paths=True ) class MdlLocalPathListWidget(EditableListWidget): def __init__(self): super().__init__( MdlLocalPathListModel, EditableListItemDelegate, "/renderer/mdl/searchPaths/local", 150 ) self._file_picker_selection = None self._file_picker = FilePickerDialog( "Add New Search Path", allow_multi_selection=False, apply_button_label="Select", selection_changed_fn=self.on_file_picker_selection_changed, click_apply_handler=lambda f, d: self.on_file_picker_apply_clicked(), click_cancel_handler=None ) self._file_picker.hide() def on_file_picker_selection_changed(self, items): # this is a workaround for that FilePickerDialog has a bug that # the selection does not get updated if user select a directory if items: self._file_picker_selection = items[0].path def on_file_picker_apply_clicked(self): if self._model.find_path(self._file_picker_selection): nm.post_notification( "Path already exists in the list.", status=nm.NotificationStatus.INFO, hide_after_timeout=False ) return self._model.add_entry(self._file_picker_selection) self._file_picker.hide() def on_add_new_entry_button_clicked(self): self._view.clear_selection() self._file_picker.show() def on_save_button_clicked(self): bad_paths = self._model.sanity_check_paths() if bad_paths: paths = "\n".join(bad_paths) ok_button = nm.NotificationButtonInfo( "OK", on_complete=lambda: self.save_settings_and_config_file() ) cancel_button = nm.NotificationButtonInfo( "Cancel", on_complete=None ) nm.post_notification( f"Path(s) below do not exist. Continue?\n\n{paths}", status=nm.NotificationStatus.WARNING, button_infos=[ok_button, cancel_button], hide_after_timeout=False ) else: self.save_settings_and_config_file() def save_settings_and_config_file(self): self._model.save_entries_to_settings() config_file = material_config_utils.get_config_file_path() if not os.path.exists(config_file): ok_button = nm.NotificationButtonInfo( "OK", on_complete=self._model.save_to_material_config_file ) cancel_button = nm.NotificationButtonInfo( "Cancel", on_complete=None ) nm.post_notification( f"Material config file does not exist. Create?\n\n{config_file}", status=nm.NotificationStatus.INFO, button_infos=[ok_button, cancel_button], hide_after_timeout=False ) else: self._model.save_to_material_config_file() carb.log_info(f"Material config file saved: {config_file}")
10,259
Python
32.420195
100
0.573253
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/material_config_utils.py
import os import posixpath # import platform import pathlib import copy import toml import carb import carb.settings SETTING_BUILTINALLOWLIST = "/materialConfig/materialGraph/builtInAllowList" SETTING_BUILTINBLOCKLIST = "/materialConfig/materialGraph/builtInBlockList" SETTING_USERALLOWLIST = "/materialConfig/materialGraph/userAllowList" SETTING_USERBLOCKLIST = "/materialConfig/materialGraph/userBlockList" def _key_value_to_dict(key, value): # "/path/to/key", <value> -> {"path": {"to": {"key": <value>}}} tokens = key.split('/') tokens = list(filter(None, tokens)) # filter empty strings dct = value for token in reversed(tokens): dct = {token: dct} return dct def _merge_dict(dict1, dict2): merged = copy.deepcopy(dict1) for k2, v2 in dict2.items(): v1 = merged.get(k2) if isinstance(v1, dict) and isinstance(v2, dict): merged[k2] = _merge_dict(v1, v2) else: merged[k2] = copy.deepcopy(v2) return merged def get_default_config_file_path(): try: home_dir = pathlib.Path.home() except Exception as e: carb.log_error(str(e)) return "" config_file_path = home_dir / "Documents/Kit/shared" / "material.config.toml" config_file_path = config_file_path.as_posix() return str(config_file_path) def get_config_file_path(): settings = carb.settings.get_settings() file_path = settings.get('/materialConfig/configFilePath') if not file_path or not os.path.exists(file_path): file_path = get_default_config_file_path() return file_path def load_config_file(file_path): config = {} try: if os.path.exists(file_path): config = toml.load(file_path) except Exception as e: carb.log_error(str(e)) return config def save_config_file(config, file_path): # this setting should not be saved in file config.pop("configFilePath", None) try: toml_str = toml.dumps(config) # least prettify format toml_str = toml_str.replace(",", ",\n") toml_str = toml_str.replace("[ ", "[\n ") with open(file_path, "w") as f: f.write(toml_str) except Exception as e: carb.log_error(str(e)) return False return True def save_carb_setting_to_config_file(carb_setting_key, config_key, is_paths=False, non_standard_path=None): try: # get value from carb setting settings = carb.settings.get_settings() value = settings.get(carb_setting_key) if is_paths: value = value.split(";") if value else [] value = list(filter(None, value)) # remove empty strings # load config from file file_path = pathlib.Path(non_standard_path if non_standard_path else get_config_file_path()) if not file_path.exists(): file_path.touch() config = load_config_file(file_path) # deep merge configs new_config = _key_value_to_dict(config_key, value) merged_config = _merge_dict(config, new_config) # save config to file save_config_file(merged_config, file_path) except Exception as e: carb.log_error(str(e)) return False return True def save_live_config_to_file(non_standard_path=None): try: # get live material config from carb setting settings = carb.settings.get_settings() live_config = settings.get("/materialConfig") # save config to file file_path = pathlib.Path(non_standard_path if non_standard_path else get_config_file_path()) save_config_file(live_config, file_path) except Exception as e: carb.log_error(str(e)) return False return True
3,771
Python
25.194444
107
0.631132
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/screenshot_page.py
import os import carb.settings import omni.ui as ui from ..preferences_window import PreferenceBuilder, show_file_importer, PERSISTENT_SETTINGS_PREFIX, SettingType class ScreenshotPreferences(PreferenceBuilder): def __init__(self): super().__init__("Capture Screenshot") self._settings = carb.settings.get_settings() # setup captureFrame paths template_path = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path") if template_path is None or template_path == "./": template_path = self._settings.get("/app/captureFrame/path") if template_path[-1] != "/": template_path += "/" self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path", template_path) # 3D viewport self._settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/viewport", False) # ansel defaults if self._is_ansel_enabled(): ansel_quality_path = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/quality" self._settings.set_default_string(ansel_quality_path, "Medium") ansel_super_resolution_size_path = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/superResolution/size" self._settings.set_default_string(ansel_super_resolution_size_path, "2x") # create captureFrame directory original_umask = os.umask(0) if not os.path.isdir(template_path): try: os.makedirs(template_path) except Exception: carb.log_error(f"Failed to create directory {template_path}") os.umask(original_umask) def build(self): """ Capture Screenshot """ # The path widget. It's not standard because it has the button browse. Since the main layout has two columns, # we need to create another layout and put it to the main one. with ui.VStack(height=0): with self.add_frame("Capture Screenshot"): with ui.VStack(): self._settings_widget = self.create_setting_widget( "Path to save screenshots", PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path", SettingType.STRING, clicked_fn=self._on_browse_button_fn, ) self.create_setting_widget( "Capture only the 3D viewport", PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/viewport", SettingType.BOOL, ) # Show Ansel super resolution configuration, only when Ansel enabled self._create_ansel_super_resolution_settings() def _add_ansel_settings(self): # check if Ansel enabled. If not, do not show Ansel settings if not self._is_ansel_enabled(): return self.create_setting_widget_combo( "Quality", PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/quality", ["Low", "Medium", "High"] ) def _create_ansel_super_resolution_settings(self): # check if Ansel enabled. If not, do not show Ansel settings if not self._is_ansel_enabled(): return self.spacer() with self.add_frame("Super Resolution"): with ui.VStack(): self.create_setting_widget_combo( "Size", PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/superResolution/size", ["2x", "4x", "8x", "16x", "32x"], ) self._add_ansel_settings() def _is_ansel_enabled(self): return self._settings.get("/exts/omni.ansel/enable") def _on_browse_button_fn(self, owner): """ Called when the user picks the Browse button. """ navigate_to = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path") show_file_importer("Select Screenshot Directory", click_apply_fn=self._on_dir_pick, filename_url=navigate_to, show_only_folders=True) def _on_dir_pick(self, real_path): """ Called when the user accepts directory in the Select Directory dialog. """ directory = self.cleanup_slashes(real_path, is_directory=True) self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path", directory) self._settings_widget.model.set_value(directory)
4,486
Python
42.990196
117
0.596745
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/globals.py
import asyncio import carb.settings import omni.kit.app import omni.ui as ui from ..preferences_window import PreferenceBuilder class GlobalPreferences(PreferenceBuilder): def __init__(self): super().__init__("") def build(self): async def on_ok_clicked(dialog): import sys import carb.events import omni.kit.app dialog.hide() def run_process(args): import subprocess import platform kwargs = {"close_fds": False} if platform.system().lower() == "windows": kwargs["creationflags"] = subprocess.CREATE_NEW_CONSOLE | subprocess.CREATE_NEW_PROCESS_GROUP subprocess.Popen(args, **kwargs) # pylint: disable=consider-using-with def on_event(e: carb.events.IEvent): if e.type == omni.kit.app.PRE_SHUTDOWN_EVENT_TYPE: run_process(sys.argv + ["--reset-user"]) self._shutdown_sub = omni.kit.app.get_app().get_shutdown_event_stream().create_subscription_to_pop(on_event, name="preferences re-start", order=0) await omni.kit.app.get_app().next_update_async() omni.kit.app.get_app().post_quit() def reset_clicked(): from omni.kit.window.popup_dialog import MessageDialog if omni.usd.get_context().has_pending_edit(): dialog = MessageDialog( title= f"{omni.kit.ui.get_custom_glyph_code('${glyphs}/exclamation.svg')} Reset to Default Settings", width=400, message=f"This application will restart to remove all custom settings and restore the application to the installed state.\n\nYou will be prompted to save any unsaved changes.", ok_handler=lambda dialog: asyncio.ensure_future(on_ok_clicked(dialog)), ok_label="Continue", cancel_label="Cancel", ) else: dialog = MessageDialog( title= f"{omni.kit.ui.get_custom_glyph_code('${glyphs}/exclamation.svg')} Reset to Default Settings", width=400, message=f"This application will restart to remove all custom settings and restore the application to the installed state.", ok_handler=lambda dialog: asyncio.ensure_future(on_ok_clicked(dialog)), ok_label="Restart", cancel_label="Cancel", ) dialog.show() ui.Button("Reset to Default", clicked_fn=reset_clicked, name="global", tooltip="This will reset all settings back to the installed state after the application is restarted") def __del__(self): super().__del__()
2,806
Python
42.859374
196
0.581254
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/thumbnail_generation_page.py
import carb.settings import omni.ui as ui from ..preferences_window import PreferenceBuilder, show_file_importer, PERSISTENT_SETTINGS_PREFIX, SettingType MDL_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_thumbnail_generation_mdl" def set_default_usd_thumbnail_generator_settings(): """Setup default value for the setting of the USD Thumbnail Generator""" settings = carb.settings.get_settings() settings.set_default_int("/app/thumbnailsGenerator/usd/width", 256) settings.set_default_int("/app/thumbnailsGenerator/usd/height", 256) settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/renderer", "RayTracing") settings.set_default_int(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/iterations", 8) settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.thumbnails.usd/thumbnail_on_save", True) def set_default_mdl_thumbnail_generator_settings(): """Setup default value for the setting of the MDL Thumbnail Generator""" settings = carb.settings.get_settings() settings.set_default_int("/app/thumbnailsGenerator/mdl/width", 256) settings.set_default_int("/app/thumbnailsGenerator/mdl/height", 256) settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/renderer", "PathTracing") settings.set_default_int(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/iterations", 512) template_url = "/Library/AEC/Materials/Library_Default.thumbnail.usd" settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/usd_template_path", template_url ) settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/standin_usd_path", "/Stage/ShaderKnob" ) class ThumbnailGenerationPreferences(PreferenceBuilder): def __init__(self): super().__init__("Thumbnail Generation") self._settings = carb.settings.get_settings() # default_settings set_default_usd_thumbnail_generator_settings() set_default_mdl_thumbnail_generator_settings() def build(self): """Thumbnail Generation""" with ui.VStack(height=0): if carb.settings.get_settings().get(MDL_PREFERENCES_PATH): with self.add_frame("MDL Thumbnail Generation Settings"): with ui.VStack(): self._settings_widget = self.create_setting_widget( "Path usd template to render MDL Thumnail", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/usd_template_path", SettingType.STRING, clicked_fn=self._on_browse_button_fn, ) self.create_setting_widget( "Name of the standin Prim", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/standin_usd_path", SettingType.STRING, ) self.create_setting_widget_combo( "Renderer Type", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/renderer", ["RayTracing", "PathTracing"], ) self.create_setting_widget( "Rendering Samples", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/iterations", SettingType.INT, ) self.spacer() with self.add_frame("USD Thumbnail Generation Settings"): with ui.VStack(): self.create_setting_widget_combo( "Renderer Type", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/renderer", ["RayTracing", "PathTracing"], ) self.create_setting_widget( "Rendering Samples", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/iterations", SettingType.INT, ) self.create_setting_widget( "Save usd thumbnail on save", PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.thumbnails.usd/thumbnail_on_save", SettingType.BOOL, ) def _on_browse_button_fn(self, owner): """Called when the user picks the Browse button.""" path = self._settings_widget.model.get_value_as_string() show_file_importer(title="Select Template", click_apply_fn=self._on_file_pick, filename_url=path) def _on_file_pick(self, full_path): """Called when the user accepts directory in the Select Directory dialog.""" self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/usd_template_path", full_path) self._settings_widget.model.set_value(full_path)
5,142
Python
48.932038
116
0.6021
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/usdskel_page.py
import carb.settings import omni.kit.app from functools import partial from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType class UsdSkelPreferences(PreferenceBuilder): def __init__(self): super().__init__("UsdSkel") self._update_setting = {} settings = carb.settings.get_settings() if settings.get(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter", True ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape", True ) def build(self): import omni.ui as ui with ui.VStack(height=0): with self.add_frame("UsdSkel"): with ui.VStack(): self.create_setting_widget( "Enable BlendShape", PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape", SettingType.BOOL, tooltip="Enable BlendShape. Will be effective on the next stage load.", ) def _on_enable_blendshape_change(item, event_type, owner): if event_type == carb.settings.ChangeEventType.CHANGED: settings = carb.settings.get_settings() if settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape"): if not settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter"): settings.set_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter", True) self._update_setting["Enable BlendShape"] = omni.kit.app.SettingChangeSubscription( PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape", partial(_on_enable_blendshape_change, owner=self), ) def __del__(self): super().__del__() self._update_setting = {}
2,310
Python
40.267856
120
0.577056
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/material_page.py
import carb.settings import omni.kit.app import omni.ui as ui from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType from ..material_config_utils import SETTING_USERALLOWLIST, SETTING_USERBLOCKLIST from ..material_config_widget import EditableListWidget from ..material_path_widget import MdlDefaultPathListWidget from ..material_path_widget import MdlLocalPathListWidget class MaterialPreferences(PreferenceBuilder): def __init__(self): super().__init__("Material") settings = carb.settings.get_settings() self._sub_render_context = omni.kit.app.SettingChangeSubscription( PERSISTENT_SETTINGS_PREFIX + "/app/hydra/material/renderContext", self._on_render_context_changed ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath") is None: settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "Relative") if settings.get("/app/mdl/nostdpath") is None: settings.set_default_bool("/app/mdl/nostdpath", False) PreferenceBuilder.__init__(self, "Material") def build(self): """ Material """ with ui.VStack(height=0): """ Material """ with self.add_frame("Material"): with ui.VStack(): self.create_setting_widget_combo( "Binding Strength", PERSISTENT_SETTINGS_PREFIX + "/app/stage/materialStrength", ["weakerThanDescendants", "strongerThanDescendants"], ) self.create_setting_widget_combo( "Drag/Drop Path", PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", ["Absolute", "Relative"], ) self.create_setting_widget_combo( "Render Context / Material Network (Requires Stage Reload)", PERSISTENT_SETTINGS_PREFIX + "/app/hydra/material/renderContext", {"default": "", "mdl": "mdl"}, ) self.spacer() """ Material Search Path """ with self.add_frame("Material Search Path"): with ui.VStack(height=0): """ Default Paths """ default_path_frame = self.add_frame("Default Paths") # default_path_frame.collapsed = True default_path_frame.collapsed = False with default_path_frame: with ui.VStack(): self.create_setting_widget( "Ignore Standard Paths", "/app/mdl/nostdpath", SettingType.BOOL ) self.spacer() with ui.HStack(): ui.Spacer(width=5) self._mdl_default_paths = MdlDefaultPathListWidget() self.spacer() """ Local Paths """ with self.add_frame("Local Paths"): self._mdl_local_paths = MdlLocalPathListWidget() self.spacer() """ Material Graph """ if self._isExtensionEnabled("omni.kit.window.material_graph"): with self.add_frame("Material Graph"): with ui.VStack(height=0): """ User Allow List """ user_allow_list_frame = self.add_frame("User Allow List") with user_allow_list_frame: self._user_allow_list_widget = EditableListWidget(setting_path=SETTING_USERALLOWLIST) self.spacer() """ User Block List """ user_block_list_frame = self.add_frame("User Block List") with user_block_list_frame: self._user_block_list_widget = EditableListWidget(setting_path=SETTING_USERBLOCKLIST) def _isExtensionEnabled(self, name): manager = omni.kit.app.get_app().get_extension_manager() for ext in manager.get_extensions(): if ext["name"] == name and ext["enabled"] == True: return True return False def _on_render_context_changed(self, value: str, event_type: carb.settings.ChangeEventType): import omni.usd if event_type == carb.settings.ChangeEventType.CHANGED: stage = omni.usd.get_context().get_stage() if not stage or stage.GetRootLayer().anonymous: return msg = "Material render context has been changed. You will need to reload your stage for this to take effect." try: import asyncio import omni.kit.notification_manager import omni.kit.app async def show_msg(): await omni.kit.app.get_app().next_update_async() omni.kit.notification_manager.post_notification(msg, hide_after_timeout=False) asyncio.ensure_future(show_msg()) except: carb.log_warn(msg)
5,435
Python
42.488
121
0.529899
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/resourcemonitor_page.py
import omni.ui as ui from ..preferences_window import PreferenceBuilder, SettingType class ResourceMonitorPreferences(PreferenceBuilder): def __init__(self): super().__init__("Resource Monitor") def build(self): """ Resource Monitor """ try: import omni.resourcemonitor as rm with ui.VStack(height=0): with self.add_frame("Resource Monitor"): with ui.VStack(): self.create_setting_widget( "Time Between Queries", rm.timeBetweenQueriesSettingName, SettingType.FLOAT, ) self.create_setting_widget( "Send Device Memory Warnings", rm.sendDeviceMemoryWarningSettingName, SettingType.BOOL, ) self.create_setting_widget( "Device Memory Warning Threshold (MB)", rm.deviceMemoryWarnMBSettingName, SettingType.INT, ) self.create_setting_widget( "Device Memory Warning Threshold (Fraction)", rm.deviceMemoryWarnFractionSettingName, SettingType.FLOAT, range_from=0., range_to=1., ) self.create_setting_widget( "Send Host Memory Warnings", rm.sendHostMemoryWarningSettingName, SettingType.BOOL ) self.create_setting_widget( "Host Memory Warning Threshold (MB)", rm.hostMemoryWarnMBSettingName, SettingType.INT, ) self.create_setting_widget( "Host Memory Warning Threshold (Fraction)", rm.hostMemoryWarnFractionSettingName, SettingType.FLOAT, range_from=0., range_to=1., ) except ImportError: pass
2,435
Python
41.736841
73
0.420534
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/datetime_format_page.py
import carb.settings import omni.kit.app from functools import partial from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX class DatetimeFormatPreferences(PreferenceBuilder): def __init__(self): super().__init__("Datetime Format") settings = carb.settings.get_settings() if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/datetime/format") is None: settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/datetime/format", "MM/DD/YYYY") def build(self): import omni.ui as ui # OM-38343: allow user to switching between different date formats with ui.VStack(height=0): with self.add_frame("Datetime Format"): self.create_setting_widget_combo( "Display Date As", PERSISTENT_SETTINGS_PREFIX + "/app/datetime/format", [ "MM/DD/YYYY", "DD.MM.YYYY", "DD-MM-YYYY", "YYYY-MM-DD", "YYYY/MM/DD", "YYYY.MM.DD" ] ) def __del__(self): super().__del__()
1,232
Python
32.324323
106
0.529221
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/developer_page.py
import carb import carb.settings import omni.kit.app import omni.ui as ui from ..preferences_window import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX from typing import Any from typing import Dict from typing import Optional THREAD_SYNC_PRESETS = [ ( "No Pacing", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 120, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": False, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 120, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 120, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": False, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 120, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": False, "/app/runLoopsGlobal/syncToPresent": False, "/app/vsync": False, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": False, "/persistent/app/viewport/defaults/tickRate": 120, "/rtx-transient/dlssg/enabled": True, }, ), ( "30x2", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 60, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": True, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 60, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 30, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": True, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 30, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": True, "/app/runLoopsGlobal/syncToPresent": True, "/app/vsync": True, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": True, "/persistent/app/viewport/defaults/tickRate": 30, "/rtx-transient/dlssg/enabled": True, }, ), ( "60", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 60, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": True, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 60, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 60, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": True, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 60, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": True, "/app/runLoopsGlobal/syncToPresent": True, "/app/vsync": True, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": True, "/persistent/app/viewport/defaults/tickRate": 60, "/rtx-transient/dlssg/enabled": False, }, ), ( "60x2", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 60, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": True, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 120, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 60, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": True, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 60, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": True, "/app/runLoopsGlobal/syncToPresent": True, "/app/vsync": True, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": True, "/persistent/app/viewport/defaults/tickRate": 60, "/rtx-transient/dlssg/enabled": True, }, ), ( "120", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 120, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": True, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 120, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 120, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": True, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 120, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": True, "/app/runLoopsGlobal/syncToPresent": True, "/app/vsync": True, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": True, "/persistent/app/viewport/defaults/tickRate": 120, "/rtx-transient/dlssg/enabled": False, }, ), ] class ThreadSyncPresets: def __init__(self): # Get all the settings to watch names = [] paths = set() for name, setting in THREAD_SYNC_PRESETS: names.append(name) for key, default in setting.items(): paths.add(key) self._settings = carb.settings.get_settings() self._subscriptions = [] for path in paths: self._subscriptions.append(self._settings.subscribe_to_node_change_events(path, self._on_setting_changed)) combo = ui.ComboBox(*([0, ""] + names), height=0) self._model = combo.model self._sub = self._model.subscribe_item_changed_fn(self._on_model_changed) def _on_setting_changed(self, item, event_type): for name, setting in THREAD_SYNC_PRESETS: all_is_good = True for key, default in setting.items(): if self._settings.get(key) != default: all_is_good = False break if all_is_good: self._on_preset_changed(name) return self._on_preset_changed(None) def _on_preset_changed(self, preset: Optional[str]): # Find ID for i, child_item in enumerate(self._model.get_item_children()): if self._model.get_item_value_model(child_item).as_string == preset: self._set_preset_id(i) def _set_preset_id(self, preset_id: int): self._model.get_item_value_model().as_int = preset_id def _on_model_changed(self, model: ui.AbstractItemModel, item: ui.AbstractItem): preset_id = self._model.get_item_value_model().as_int child_item = self._model.get_item_children()[preset_id] child_name = self._model.get_item_value_model(child_item).as_string if not child_name: return # Find prest for name, setting in THREAD_SYNC_PRESETS: if name == child_name: self._set_settings(setting) break def _set_settings(self, batch: Dict[str, Any]): for key, value in batch.items(): if self._settings.get(key) != value: self._settings.set(key, value) carb.log_info(f"Present Sets Setting {key} -> {value}") class DeveloperPreferences(PreferenceBuilder): def __init__(self): super().__init__("Developer") def build(self): with ui.VStack(height=0): """ Throttle Rendering """ with self.add_frame("Throttle Rendering"): with ui.VStack(): with ui.HStack(): self.label("Global Thread Synchronization Preset") self.__presets = ThreadSyncPresets() self.create_setting_widget("Async Rendering", "/app/asyncRendering", SettingType.BOOL) self.create_setting_widget( "Skip Rendering While Minimized", "/app/renderer/skipWhileMinimized", SettingType.BOOL ) self.create_setting_widget( "Yield 'ms' while in focus", "/app/renderer/sleepMsOnFocus", SettingType.INT, range_from=0, range_to=50, ) self.create_setting_widget( "Yield 'ms' while not in focus", "/app/renderer/sleepMsOutOfFocus", SettingType.INT, range_from=0, range_to=200, ) self.create_setting_widget( "Enable UI FPS Limit", "/app/runLoops/main/rateLimitEnabled", SettingType.BOOL ) self.create_setting_widget( "UI FPS Limit uses Busy Loop", "/app/runLoops/main/rateLimitUseBusyLoop", SettingType.BOOL ) self.create_setting_widget( "UI FPS Limit", "/app/runLoops/main/rateLimitFrequency", SettingType.FLOAT, range_from=10, range_to=360, ) self.create_setting_widget( "Use Fixed Time Stepping", "/app/player/useFixedTimeStepping", SettingType.BOOL ) # Present thread self.create_setting_widget( "Use Present Thread", "/exts/omni.kit.renderer.core/present/enabled", SettingType.BOOL ) self.create_setting_widget( "Sync Threads and Present Thread", "/app/runLoopsGlobal/syncToPresent", SettingType.BOOL ) self.create_setting_widget( "Present Thread FPS Limit", "/app/runLoops/present/rateLimitFrequency", SettingType.FLOAT, range_from=10, range_to=360, ) self.create_setting_widget( "Sync Present Thread to Present After Rendering", "/exts/omni.kit.renderer.core/present/presentAfterRendering", SettingType.BOOL ) self.create_setting_widget( "Vsync", "/app/vsync", SettingType.BOOL )
12,661
Python
44.060498
118
0.564647
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/stage_page.py
import carb.settings import omni.kit.app from functools import partial from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType class StagePreferences(PreferenceBuilder): def __init__(self): super().__init__("Stage") self._update_setting = {} settings = carb.settings.get_settings() if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodeRange") is None: settings.set_float_array(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodeRange", [0, 100]) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodesPerSecond") is None: settings.set_default_float(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodesPerSecond", 60.0) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps", True ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType") is None: settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType", "Scale, Rotate, Translate" ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder") is None: settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder", "XYZ") # OM-47905: Default camera rotation order should be YXZ. if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultCameraRotationOrder") is None: settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultCameraRotationOrder", "YXZ") if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder") is None: settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:translate, xformOp:rotate, xformOp:scale", ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision") is None: settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision", "Double" ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/dragDropImport") is None: settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/stage/dragDropImport", "payload" ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/nestedGprimsAuthoring") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/app/stage/nestedGprimsAuthoring", False ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/movePrimInPlace") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/app/stage/movePrimInPlace", True ) def build(self): import omni.ui as ui """ New Stage """ with ui.VStack(height=0): with self.add_frame("New Stage"): with ui.VStack(): self.create_setting_widget_combo( "Default Up Axis", PERSISTENT_SETTINGS_PREFIX + "/app/stage/upAxis", ["Y", "Z"] ) self.create_setting_widget( "Default Animation Rate (TimeCodesPerSecond)", PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodesPerSecond", SettingType.FLOAT ) self.create_setting_widget( "Default Meters Per Unit", PERSISTENT_SETTINGS_PREFIX + "/simulation/defaultMetersPerUnit", SettingType.FLOAT, range_from=0.001, range_to=1.0, speed=0.001, identifier="default_meters_per_unit" ) self.create_setting_widget( "Default Time Code Range", PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodeRange", SettingType.DOUBLE2, ) self.create_setting_widget( "Default DefaultPrim Name", PERSISTENT_SETTINGS_PREFIX + "/app/stage/defaultPrimName", SettingType.STRING, ) self.create_setting_widget_combo( "Interpolation Type", PERSISTENT_SETTINGS_PREFIX + "/app/stage/interpolationType", ["Linear", "Held"], ) self.create_setting_widget( "Enable Static Material Network Topology", "/omnihydra/staticMaterialNetworkTopology", SettingType.BOOL, ) self._create_prim_creation_settings_widgets() self.spacer() """ Authoring """ with self.add_frame("Authoring"): with ui.VStack(): self.create_setting_widget( "Keep Prim World Transfrom When Reparenting", PERSISTENT_SETTINGS_PREFIX + "/app/stage/movePrimInPlace", SettingType.BOOL, ) self.create_setting_widget( 'Set "Instanceable" When Creating Reference', PERSISTENT_SETTINGS_PREFIX + "/app/stage/instanceableOnCreatingReference", SettingType.BOOL, ) self.create_setting_widget( "Transform Gizmo Manipulates Scale/Rotate/Translate Separately (New)", PERSISTENT_SETTINGS_PREFIX + "/app/transform/gizmoUseSRT", SettingType.BOOL, ) self.create_setting_widget( "Camera Controller Manipulates Scale/Rotate/Translate Separately (New)", PERSISTENT_SETTINGS_PREFIX + "/app/camera/controllerUseSRT", SettingType.BOOL, ) self.create_setting_widget( "Allow nested gprims authoring", PERSISTENT_SETTINGS_PREFIX + "/app/stage/nestedGprimsAuthoring", SettingType.BOOL, ) self.spacer() """ Import """ with self.add_frame("Import"): with ui.VStack(): self.create_setting_widget_combo( "Drag & Drop USD Method", PERSISTENT_SETTINGS_PREFIX + "/app/stage/dragDropImport", ["payload", "reference"], ) self.spacer() """ Logging """ with self.add_frame("Logging"): with ui.VStack(): self.create_setting_widget( "Mute USD Coding Error from USD Diagnostic Manager", PERSISTENT_SETTINGS_PREFIX + "/app/usd/muteUsdCodingError", SettingType.BOOL, ) self.spacer() """ Compatibility """ with self.add_frame("Compatibility"): with ui.VStack(): self.create_setting_widget( "Support unprefixed UsdLux attributes (USD <= 20.11)", PERSISTENT_SETTINGS_PREFIX + "/app/usd/usdLuxUnprefixedCompat", SettingType.BOOL, ) def __del__(self): super().__del__() self._update_setting = {} def _create_prim_creation_settings_widgets(self): self.create_setting_widget( "Start with Transform Op on Prim Creation", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps", SettingType.BOOL, ) def _on_prim_creation_with_default_xform_ops_change(item, event_type, owner): if event_type == carb.settings.ChangeEventType.CHANGED: owner._update_prim_creation_with_default_xform_ops() self._update_setting["PrimCreationWithDefaultXformOps"] = omni.kit.app.SettingChangeSubscription( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps", partial(_on_prim_creation_with_default_xform_ops_change, owner=self), ) widget = self.create_setting_widget_combo( " Default Transform Op Type", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType", ["Scale, Rotate, Translate", "Scale, Orient, Translate", "Transform"], ) def _on_default_xform_op_type_change(item, event_type, owner): if event_type == carb.settings.ChangeEventType.CHANGED: owner._update_prim_creation_with_default_xform_ops() self._update_setting["DefaultXformOpType"] = omni.kit.app.SettingChangeSubscription( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType", partial(_on_default_xform_op_type_change, owner=self), ) self._widget_default_xform_op_type = widget widget = self.create_setting_widget_combo( " Default Camera Rotation Order", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultCameraRotationOrder", ["XYZ", "XZY", "YZX", "YXZ", "ZXY", "ZYX"], ) self._widget_default_camera_rotation_order = widget widget = self.create_setting_widget_combo( " Default Rotation Order", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder", ["XYZ", "XZY", "YZX", "YXZ", "ZXY", "ZYX"], ) self._widget_default_rotation_order = widget widget = self.create_setting_widget_combo( " Default Xform Op Order", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", [ "xformOp:translate, xformOp:rotate, xformOp:scale", "xformOp:translate, xformOp:orient, xformOp:scale", "xformOp:transform", ], ) self._widget_default_xform_op_order = widget widget = self.create_setting_widget_combo( " Default Xform Precision", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision", ["Float", "Double"], ) self._widget_default_xform_op_precision = widget self._update_prim_creation_with_default_xform_ops() def _update_prim_creation_with_default_xform_ops(self): settings = carb.settings.get_settings() if settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps"): self._widget_default_xform_op_type.enabled = True default_xform_ops = settings.get_as_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType" ) if default_xform_ops == "Scale, Orient, Translate": self._widget_default_rotation_order.enabled = False self._widget_default_camera_rotation_order.enabled = False settings.set_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:translate, xformOp:orient, xformOp:scale", ) elif default_xform_ops == "Transform": self._widget_default_rotation_order.enabled = False self._widget_default_camera_rotation_order.enabled = False settings.set_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:transform" ) else: self._widget_default_rotation_order.enabled = True self._widget_default_camera_rotation_order.enabled = True settings.set_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:translate, xformOp:rotate, xformOp:scale", ) self._widget_default_xform_op_order.enabled = False self._widget_default_xform_op_precision.enabled = True else: self._widget_default_xform_op_type.enabled = False self._widget_default_rotation_order.enabled = False self._widget_default_camera_rotation_order.enabled = False self._widget_default_xform_op_order.enabled = False self._widget_default_xform_op_precision.enabled = False
13,140
Python
44.787456
123
0.563775
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/rendering_page.py
import carb import carb.settings import omni.kit.app import omni.ui as ui from ..preferences_window import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX from .developer_page import THREAD_SYNC_PRESETS # kit-extensions/kit-scene extension access this from typing import Any from typing import Dict from typing import Optional class RenderingPreferences(PreferenceBuilder): def post_notification(message: str, info: bool = False, duration: int = 3): import omni.kit.notification_manager as nm if info: type = nm.NotificationStatus.INFO else: type = nm.NotificationStatus.WARNING nm.post_notification(message, status=type, duration=duration) def __init__(self): super().__init__("Rendering") self._persistentDistillMaterialPath = PERSISTENT_SETTINGS_PREFIX + "/rtx/mdltranslator/distillMaterial" self._persistentMultiGPUPath = PERSISTENT_SETTINGS_PREFIX + "/renderer/multiGpu/enabled" self._persistentOpacityMicromapPath = PERSISTENT_SETTINGS_PREFIX + "/renderer/raytracingOmm/enabled" settings = carb.settings.get_settings() if settings.get(self._persistentDistillMaterialPath) is None: settings.set_default_bool(self._persistentDistillMaterialPath, False) self._sub_material_distilling_changed = omni.kit.app.SettingChangeSubscription( self._persistentDistillMaterialPath, self._on_material_distilling_changed ) self._sub_opacity_micromap_changed = omni.kit.app.SettingChangeSubscription( self._persistentOpacityMicromapPath, self._on_opacity_micromap_changed ) self._persistentPlaceholderTextureColorPath = PERSISTENT_SETTINGS_PREFIX + "/rtx/resourcemanager/placeholderTextureColor" if settings.get(self._persistentPlaceholderTextureColorPath) is None: settings.set_float_array(self._persistentPlaceholderTextureColorPath, [0,1,1]) # Note: No SettingChangeSubscription because it shows the same popup like 6 times when the color is changed self._enableFabricSceneDelegatePath = "/app/useFabricSceneDelegate" self._sub_fabric_delegate_changed = omni.kit.app.SettingChangeSubscription( self._enableFabricSceneDelegatePath, self._on_fabric_delegate_changed ) self._fabricMemBudgetPath = "/app/usdrt/scene_delegate/gpuMemoryBudgetPercent" if settings.get(self._fabricMemBudgetPath) is None: settings.set_default_float(self._fabricMemBudgetPath, 90) self._fabricEnableGeometryStreaming = "/app/usdrt/scene_delegate/geometryStreaming/enabled" if settings.get(self._fabricEnableGeometryStreaming) is None: settings.set_default_bool(self._fabricEnableGeometryStreaming, True) self._fabricEnableGeometryStreamingMinSize = "/app/usdrt/scene_delegate/geometryStreaming/solidAngleLimit" if settings.get(self._fabricEnableGeometryStreamingMinSize) is None: settings.set_default_float(self._fabricEnableGeometryStreamingMinSize, 0.) self._fabricEnableProxyCubes = "/app/usdrt/scene_delegate/enableProxyCubes" if settings.get(self._fabricEnableProxyCubes) is None: settings.set_default_bool(self._fabricEnableProxyCubes, False) self._fabricMergeSubcomponents = "/app/usdrt/population/utils/mergeSubcomponents" if settings.get(self._fabricMergeSubcomponents) is None: settings.set_default_bool(self._fabricMergeSubcomponents, False) self._fabricMergeInstances = "/app/usdrt/population/utils/mergeInstances" if settings.get(self._fabricMergeInstances) is None: settings.set_default_bool(self._fabricMergeInstances, False) self._fabricMergeMaterials = "/app/usdrt/population/utils/mergeMaterials" if settings.get(self._fabricMergeMaterials) is None: settings.set_default_bool(self._fabricMergeMaterials, True) self._fabricReadMaterials = "/app/usdrt/population/utils/readMaterials" if settings.get(self._fabricReadMaterials) is None: settings.set_default_bool(self._fabricReadMaterials, True) self._fabricReadLights = "/app/usdrt/population/utils/readLights" if settings.get(self._fabricReadLights) is None: settings.set_default_bool(self._fabricReadLights, True) self._fabricReadPrimvars = "/app/usdrt/population/utils/readPrimvars" if settings.get(self._fabricReadPrimvars) is None: settings.set_default_bool(self._fabricReadPrimvars, True) self._fabricInferDisplayColorFromMaterial = "/app/usdrt/population/utils/inferDisplayColorFromMaterial" if settings.get(self._fabricInferDisplayColorFromMaterial) is None: settings.set_default_bool(self._fabricInferDisplayColorFromMaterial, False) self._fabricHandleSceneGraphInstances = "/app/usdrt/population/utils/handleSceneGraphInstances" if settings.get(self._fabricHandleSceneGraphInstances) is None: settings.set_default_bool(self._fabricHandleSceneGraphInstances, True) self._fabricUseHydraBlendShape = "/app/usdrt/scene_delegate/useHydraBlendShape" if settings.get(self._fabricUseHydraBlendShape) is None: settings.set_default_bool(self._fabricUseHydraBlendShape, False) def build(self): with ui.VStack(height=0): """ Hydra Scene Delegate """ with self.add_frame("Fabric Scene Delegate"): with ui.VStack(): self.create_setting_widget("Enable Fabric delegate (preview feature, requires scene reload)", self._enableFabricSceneDelegatePath, SettingType.BOOL, tooltip="Enable Fabric Hydra scene delegate for faster load times on large scenes.\n" "This is a preview release of this new feature and some scene interactions will be limited.\n" "You should expect faster load times with geometry streaming, faster playback of USD animation, " "and GPU memory staying under a predefined budget.") self.create_setting_widget("Fabric delegate GPU memory budget %", self._fabricMemBudgetPath, SettingType.FLOAT, range_from=0, range_to=100, tooltip="Fabric Scene Delegate will stop loading geometry when this threshold of available GPU memory is reached.") with ui.CollapsableFrame(title="Advanced Fabric Scene Delegate Settings", collapsed=True): with ui.VStack(): self.create_setting_widget("Enable Geometry Streaming in Fabric Scene Delegate", self._fabricEnableGeometryStreaming, SettingType.BOOL, tooltip="This enables the progressive and sorted loading of geometry, as well as the device memory limit checks.") self.create_setting_widget("Geo Streaming Minimum Size", self._fabricEnableGeometryStreamingMinSize, SettingType.FLOAT, range_from=0, range_to=1, range_step=0.0001, tooltip="This sets a minimum relative size on screen for objects to be loaded, 0 loads everything.") self.create_setting_widget("Enable proxy cubes for unloaded prims", self._fabricEnableProxyCubes, SettingType.BOOL, tooltip="This helps visualizing scene content when having low device memory, but can have performance impact for very large scenes.") self.create_setting_widget("Merge subcomponents", self._fabricMergeSubcomponents, SettingType.BOOL, tooltip="Fabric Scene Delegate will merge all meshes within USD subcomponents.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Merge instances", self._fabricMergeInstances, SettingType.BOOL, tooltip="Fabric Scene Delegate will merge all meshes within USD scene graph instances.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Merge materials", self._fabricMergeMaterials, SettingType.BOOL, tooltip="Fabric Scene Delegate will identify unique materials and drop all duplicates.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Read materials", self._fabricReadMaterials, SettingType.BOOL, tooltip="When off, Fabric Scene Delegate will not read any material from USD, which can speed up load time.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Infer displayColor from material", self._fabricInferDisplayColorFromMaterial, SettingType.BOOL, tooltip="When on, Fabric Scene Delegate will read material info to infer mesh displayColor.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Read lights", self._fabricReadLights, SettingType.BOOL, tooltip="When off, Fabric Scene Delegate will not read any lights from USD.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Read primvars", self._fabricReadPrimvars, SettingType.BOOL, tooltip="When off, Fabric Scene Delegate will not read any mesh primvar from USD.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Use Fabric Scene Graph Instancing", self._fabricHandleSceneGraphInstances, SettingType.BOOL, tooltip="When off, Fabric Scene Delegate will ignore USD Scene Graph Instances.\n" "Each instanced geometry will be duplicated in Fabric.") self.create_setting_widget("Use Hydra BlendShape", self._fabricUseHydraBlendShape, SettingType.BOOL, tooltip="Fabric Scene Delegate will compute hydra BlendShape.\n" "This will be effective after next stage loading.") #define USDRT_POPULATION_UTILS_INFERDISPLAYCOLORFROMMATERIAL "/app/usdrt/population/utils/" self.spacer() """ White Mode """ with self.add_frame("White Mode"): with ui.VStack(): widget = self.create_setting_widget("Material", "/rtx/debugMaterialWhite", SettingType.STRING) widget.enabled = False self.create_setting_widget( "Exceptions (Requires Scene Reload)", PERSISTENT_SETTINGS_PREFIX + "/app/rendering/whiteModeExceptions", SettingType.STRING, ) self.spacer() """ MDL """ with self.add_frame("MDL"): with ui.VStack(): self.create_setting_widget( "Material Distilling (Experimental, requires app restart)", self._persistentDistillMaterialPath, SettingType.BOOL, tooltip="Enables transforming MDL materials of arbitrary complexity to predefined target material models, which can improve material rendering fidelity in RTX Real-Time mode." "\nImproves rendering fidelity of complex materials such as Clear Coat in RTX Real-Time mode." "\nRequires app restart to take effect." ) self.spacer() """ Texture Streaming """ with self.add_frame("Texture Streaming"): with ui.VStack(): self.create_setting_widget( "Placeholder Texture Color (requires app restart)", self._persistentPlaceholderTextureColorPath, SettingType.COLOR3, tooltip="Sets the color of the placeholder texture which is used while actual textures are loaded." "\nRequires app restart to take effect." ) self.spacer() """ Multi-GPU """ with self.add_frame("Multi-GPU"): with ui.VStack(): with ui.HStack(height=24): self.label("Multi-GPU") settings = carb.settings.get_settings() mgpu = str(settings.get(self._persistentMultiGPUPath)) index = 0 if mgpu == "True": index = 1 elif mgpu == "False": index = 2 widget = ui.ComboBox(index, "Auto", "True", "False") widget.model.add_item_changed_fn(self._on_multigpu_changed) self.spacer() """ Opacity MicroMap """ with self.add_frame("Opacity MicroMap"): with ui.VStack(): self.create_setting_widget( "Enable Opacity MicroMap", self._persistentOpacityMicromapPath, SettingType.BOOL, tooltip="Opacity MicroMaps improve efficiency of rendering translucent objects." "\nThis feature requires an Ada Lovelace architecture GPU." "\nRequires app restart to take effect." ) def _on_opacity_micromap_changed(self, value: bool, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: msg = "Opacity MicroMap settings has been changed. You will need to restart Omniverse for this to take effect." try: import asyncio import omni.kit.notification_manager import omni.kit.app async def show_msg(): await omni.kit.app.get_app().next_update_async() omni.kit.notification_manager.post_notification(msg, hide_after_timeout=False) asyncio.ensure_future(show_msg()) except: carb.log_warn(msg) def _on_material_distilling_changed(self, value: bool, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: msg = "Material distilling settings has been changed. You will need to restart Omniverse for this to take effect." try: import asyncio import omni.kit.notification_manager import omni.kit.app async def show_msg(): await omni.kit.app.get_app().next_update_async() omni.kit.notification_manager.post_notification(msg, hide_after_timeout=False) asyncio.ensure_future(show_msg()) except: carb.log_warn(msg) def _on_fabric_delegate_changed(self, value: str, event_type: carb.settings.ChangeEventType): import omni.usd if event_type == carb.settings.ChangeEventType.CHANGED: stage = omni.usd.get_context().get_stage() if not stage or stage.GetRootLayer().anonymous: return msg = "Hydra scene delegate changed. You will need to reload your stage for this to take effect." try: import asyncio import omni.kit.notification_manager import omni.kit.app async def show_msg(): await omni.kit.app.get_app().next_update_async() omni.kit.notification_manager.post_notification(msg, hide_after_timeout=True, duration=2) asyncio.ensure_future(show_msg()) except: carb.log_warn(msg) def _on_multigpu_changed(self, model, item): current_index = model.get_item_value_model().as_int settings = carb.settings.get_settings() if current_index == 0: # this is a string not a bool and will have no effect settings.set_string(self._persistentMultiGPUPath, "auto") elif current_index == 1: settings.set_bool(self._persistentMultiGPUPath, True) elif current_index == 2: settings.set_bool(self._persistentMultiGPUPath, False) # print restart message RenderingPreferences.post_notification(f"You need to restart {omni.kit.app.get_app().get_app_name()} for changes to take effect", info=True)
18,315
Python
54.335347
199
0.583347
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/audio_page.py
import os import platform import carb.settings import omni.kit.app import omni.kit.audiodeviceenum import omni.usd.audio from functools import partial import omni.ui as ui from omni.kit.audiodeviceenum import Direction, SampleType from ..preferences_window import PreferenceBuilder, show_file_importer, PERSISTENT_SETTINGS_PREFIX, SettingType class AudioPreferences(PreferenceBuilder): def __init__(self): super().__init__("Audio") self._settings = carb.settings.get_settings() self._enum = omni.kit.audiodeviceenum.acquire_audio_device_enum_interface() self._audio = omni.usd.audio.get_stage_audio_interface() carb.settings.get_settings().set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop", False ) carb.settings.get_settings().set_default_float(PERSISTENT_SETTINGS_PREFIX + "/audio/context/uiVolume", 1.0) def build(self): devices = self.get_device_list(Direction.PLAYBACK) capture_devices = self.get_device_list(Direction.CAPTURE) speaker_list = [ "auto-detect", "mono", "stereo", "2.1", "quad", "4.1 surround", "5.1 surround", "7.1 surround", "7.1.4 surround", "9.1 surround", "9.1.4 surround", "9.1.6 surround", ] """ Audio Device """ with ui.VStack(height=0): with self.add_frame("Audio Output"): with ui.VStack(): self._device_widget = self.create_setting_widget_combo( "Output Device", PERSISTENT_SETTINGS_PREFIX + "/audio/context/deviceName", devices ) self._capture_device_widget = self.create_setting_widget_combo( "Input Device", PERSISTENT_SETTINGS_PREFIX + "/audio/context/captureDeviceName", capture_devices ) self.create_setting_widget_combo( "Speaker Configuration", PERSISTENT_SETTINGS_PREFIX + "/audio/context/speakerMode", speaker_list ) with ui.HStack(height=24): ui.Button("Refresh", clicked_fn=partial(self._on_refresh_button_fn)) ui.Spacer(width=10) ui.Button("Apply", clicked_fn=partial(self._on_apply_button_fn)) self.spacer() """ Audio Parameters """ with self.add_frame("Audio Parameters"): with ui.VStack(): self.create_setting_widget( "Auto Stream Threshold (in Kilobytes)", PERSISTENT_SETTINGS_PREFIX + "/audio/context/autoStreamThreshold", SettingType.INT, range_from=0, range_to=10240, speed=10, ) self.spacer() """ Audio Player Parameters """ with self.add_frame("Audio Player Parameters"): with ui.VStack(): self.create_setting_widget( "Auto Stream Threshold (in Kilobytes)", PERSISTENT_SETTINGS_PREFIX + "/audio/context/audioPlayerAutoStreamThreshold", SettingType.INT, range_from=0, range_to=10240, speed=10, ) self.create_setting_widget( "Close Audio Player on Stop", PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop", SettingType.BOOL, ) self.spacer() """ Volume Levels """ with self.add_frame("Volume Levels"): with ui.VStack(): self.create_setting_widget( "Master Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/masterVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.create_setting_widget( "USD Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/usdVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.create_setting_widget( "Spatial Voice Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/spatialVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.create_setting_widget( "Non-spatial Voice Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/nonSpatialVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.create_setting_widget( "UI Audio Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/uiVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.spacer() """ Debug """ with self.add_frame("Debug"): with ui.VStack(): self.create_setting_widget( "Stream Dump Filename", PERSISTENT_SETTINGS_PREFIX + "/audio/context/streamerFile", SettingType.STRING, clicked_fn=self._on_browse_button_fn, ) # checkbox to enable stream dumping. Note that the setting path for # this is *intentionally* not persistent. This forces the stream # dumping to need to be toggled on at each launch instead of just # enabling it on startup and filling up everyone's harddrives. self.create_setting_widget("Enable Stream Dump", "/audio/context/enableStreamer", SettingType.BOOL) def _on_browse_button_fn(self, origin): """ Called when the user picks the Browse button. """ full_path = origin.model.get_value_as_string() path = os.path.dirname(full_path) if path == "": path = "/" if platform.system().lower() == "windows": path = "C:/" filename = os.path.basename(full_path) if filename == "": filename = "stream_dump" # NOTE: navigate_to doesn't work if target file doesn't exist... navigate_to = self.cleanup_slashes(os.path.join(path, filename)) if not os.path.exists(navigate_to): navigate_to = self.cleanup_slashes(path) show_file_importer( title="Select Filename (Local Files Only)", file_exts=[("RIFF Files(*.wav)", ""), ("All Files(*)", "")], click_apply_fn=self._on_file_pick, filename_url=navigate_to ) def _on_file_pick(self, full_path): """ Called when the user accepts filename in the Select Filename dialog. """ path = os.path.dirname(full_path) if path == "": path = "/" if platform.system().lower() == "windows": path = "C:/" filename = os.path.basename(full_path) if filename == "": filename = "stream_dump.bin" self._settings.set( PERSISTENT_SETTINGS_PREFIX + "/audio/context/streamerFile", self.cleanup_slashes(os.path.join(path, filename)), ) def _on_refresh_button_fn(self): """ Called when the user clicks on the 'Refresh' button. """ devices = self.get_device_list(Direction.PLAYBACK) self._device_widget.model.set_items(devices) devices = self.get_device_list(Direction.CAPTURE) self._capture_device_widget.model.set_items(devices) def _on_apply_button_fn(self): """ Called when the user clicks on the 'Apply' button. """ deviceId = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/audio/context/deviceName") self._audio.set_device(deviceId) def get_device_list(self, direction): device_count = self._enum.get_device_count(direction) default_device = self._enum.get_device_name(direction, 0) if default_device is None: return {"No audio device is connected": ""} devices = {"Default Device (" + self._enum.get_device_name(direction, 0) + ")": ""} for i in range(device_count): dev_name = self._enum.get_device_description(direction, i) dev_id = self._enum.get_device_id(direction, i) if dev_name == None or dev_id == None: continue devices[dev_name] = dev_id return devices
9,404
Python
39.891304
120
0.507656
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/tagging_page.py
import carb.settings import omni.kit.app from functools import partial import omni.ui as ui from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType class TaggingPreferences(PreferenceBuilder): def __init__(self): super().__init__("Tagging") self._showAdvanced = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/showAdvancedTagView" self._showHidden = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/showHiddenTags" self._modifyHidden = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/modifyHiddenTags" carb.settings.get_settings().set_default_bool(self._showAdvanced, False) carb.settings.get_settings().set_default_bool(self._showHidden, False) carb.settings.get_settings().set_default_bool(self._modifyHidden, False) def build(self): # update on setting change def _on_change(item, event_type, owner): if event_type == carb.settings.ChangeEventType.CHANGED: owner._update_visibility() self._update_setting = omni.kit.app.SettingChangeSubscription( self._showAdvanced, partial(_on_change, owner=self) ) self._update_setting2 = omni.kit.app.SettingChangeSubscription( self._showHidden, partial(_on_change, owner=self) ) """ Tagging """ with ui.VStack(height=0): with self.add_frame("Tagging"): with ui.VStack(): self.create_setting_widget("Allow advanced tag view", self._showAdvanced, SettingType.BOOL) self._showHiddenWidget = self.create_setting_widget( "Show hidden tags in advanced view", self._showHidden, SettingType.BOOL ) self._modifyHiddenWidget = self.create_setting_widget( "Allow adding and modifying hidden tags directly", self._modifyHidden, SettingType.BOOL ) self._update_visibility() def _update_visibility(self): settings = carb.settings.get_settings() if settings.get_as_bool(self._showAdvanced): self._showHiddenWidget.enabled = True self._modifyHiddenWidget.enabled = settings.get_as_bool(self._showHidden) else: self._showHiddenWidget.enabled = False self._modifyHiddenWidget.enabled = False
2,442
Python
42.624999
111
0.643735
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_material_config.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import carb import omni.usd import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.kit.window.preferences.scripts.material_config_utils as mc_utils import os from pathlib import Path import posixpath import shutil import tempfile import toml TEST_PATH_STRS = [ "C:/some/project/materials", "omniverse://another/project/materials", "/my/own/materials" ] def _compare_toml_files(file1, file2): # the toml module does not preserve the item order in files so can't use # simple line comparison. needs to compare them as dicts toml1 = toml.load(file1) toml2 = toml.load(file2) return (toml1 == toml2) class PreferencesTestMaterialConfigUtils(AsyncTestCase): # run only once at the beginning @classmethod def setUpClass(cls): # test config file path ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) data_tests_dir = Path(ext_path) / "data/tests" test_config_file_path = data_tests_dir / "material.config.toml" test_config_carb_file_path = data_tests_dir / "material.config.carb.toml" # create temp home dir cls._temp_home = Path(tempfile.mkdtemp()) cls._temp_home = cls._temp_home.as_posix() # copy test config files to the temp home cls._temp_kit_shared_dir = posixpath.join(cls._temp_home, "Documents/Kit/shared") if not os.path.exists(cls._temp_kit_shared_dir): os.makedirs(cls._temp_kit_shared_dir) shutil.copy(test_config_file_path, cls._temp_kit_shared_dir) shutil.copy(test_config_carb_file_path, cls._temp_kit_shared_dir) # temporary wipe out material config in settings settings = carb.settings.get_settings() cls._curr_material_config = settings.get("/materialConfig") settings.set("/materialConfig", {}) # run only once at the end @classmethod def tearDownClass(cls): # remove settings used in tests settings = carb.settings.get_settings() settings.destroy_item("/materialConfigTests") # restore material config in settings settings.set("/materialConfig", {}) settings.set("/materialConfig", cls._curr_material_config) # delete temp home dir if os.path.exists(cls._temp_home): shutil.rmtree(cls._temp_home) # before running each test async def setUp(self): # temporary set home path # replace both variables since Path.home() looks for different env var on Windows # depends on the Python version self._curr_profile = os.environ.get("USERPROFILE", "") if self._curr_profile: os.environ["USERPROFILE"] = str(self._temp_home) self._curr_home = os.environ.get("HOME", "") if self._curr_home: os.environ["HOME"] = str(self._temp_home) # after running each test async def tearDown(self): # restore env vars if self._curr_profile: os.environ["USERPROFILE"] = self._curr_profile if self._curr_home: os.environ["HOME"] = self._curr_home async def test_get_config_file_path(self): expect = Path(self._temp_home) / "Documents/Kit/shared" / "material.config.toml" expect = expect.as_posix() self.assertEqual(expect, mc_utils.get_config_file_path()) async def test_load_config_file(self): config_file_path = mc_utils.get_config_file_path() config = mc_utils.load_config_file(config_file_path) expect = ["my_materials", "my_maps"] self.assertEqual(expect, config["materialGraph"]["userAllowList"]) expect = ["foo_materials", "bar_maps"] self.assertEqual(expect, config["materialGraph"]["userBlockList"]) expect = False self.assertEqual(expect, config["options"]["noStandardPath"]) expect = TEST_PATH_STRS self.assertEqual(expect, config["searchPaths"]["local"]) async def test_save_config_file(self): config = {} config["materialGraph"] = {} config["materialGraph"]["userAllowList"] = ["my_materials", "my_maps"] config["materialGraph"]["userBlockList"] = ["foo_materials", "bar_maps"] config["options"] = {} config["options"]["noStandardPath"] = False config["searchPaths"] = {} config["searchPaths"]["local"] = TEST_PATH_STRS config["configFilePath"] = "/dummy/path/material.config.toml" # save new file new_config_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.saved.toml") self.assertTrue(mc_utils.save_config_file(config, new_config_file_path)) # compare to the original file orig_config_file_path = mc_utils.get_config_file_path() self.assertTrue(_compare_toml_files(new_config_file_path, orig_config_file_path)) async def test_save_carb_setting_to_config_file(self): test_settings = ( ("string", "coffee", False), ("float", 24.0, False), ("bool", True, False), ("paths", ";".join(TEST_PATH_STRS), True) ) # assign to carb settings settings = carb.settings.get_settings() for i in test_settings: setting_key = posixpath.join("/materialConfigTests", i[0]) settings.set(setting_key, i[1]) # save new file new_config_carb_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.carb.saved.toml") for i in test_settings: carb_key = posixpath.join("/materialConfigTests", i[0]) config_key = posixpath.join("tests", i[0]) mc_utils.save_carb_setting_to_config_file( carb_key, config_key, is_paths=i[2], non_standard_path=new_config_carb_file_path ) # compare to the original file orig_config_carb_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.carb.toml") self.assertTrue(_compare_toml_files(new_config_carb_file_path, orig_config_carb_file_path)) async def test_save_live_config_to_file(self): test_settings = ( ("materialGraph/userAllowList", ["my_materials", "my_maps"]), ("materialGraph/userBlockList", ["foo_materials", "bar_maps"]), ("options/noStandardPath", False), ("searchPaths/local", TEST_PATH_STRS) ) # assign to /materialConfig carb settings settings = carb.settings.get_settings() for i in test_settings: setting_key = posixpath.join("/materialConfig", i[0]) settings.set(setting_key, i[1]) # save new file new_config_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.saved2.toml") mc_utils.save_live_config_to_file(non_standard_path=new_config_file_path) # compare to the original file orig_config_file_path = mc_utils.get_config_file_path() self.assertTrue(_compare_toml_files(new_config_file_path, orig_config_file_path))
7,577
Python
37.467005
112
0.637455
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_pages.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import carb import omni.usd import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test class PreferencesTestPages(AsyncTestCase): # Before running each test async def setUp(self): omni.kit.window.preferences.show_preferences_window() # After running each test async def tearDown(self): omni.kit.window.preferences.hide_preferences_window() carb.settings.get_settings().set("/app/show_developer_preference_section", False) async def _change_values(self): # toggle checkboxes widgets = ui_test.find_all("Preferences//Frame/**/CheckBox[*]") if widgets: for w in widgets: # don't change audio as it causes exceptions on TC if not "audio" in w.widget.identifier: ov = w.model.get_value_as_bool() w.model.set_value(not ov) await ui_test.human_delay(10) w.model.set_value(ov) async def test_show_pages(self): pages = omni.kit.window.preferences.get_page_list() page_names = [page._title for page in pages] # is list alpha sorted. Don't compare with fixed list as members can change self.assertEqual(page_names, sorted(page_names)) for page in pages: omni.kit.window.preferences.select_page(page) await ui_test.human_delay(10) await self._change_values() async def test_developer_page(self): carb.settings.get_settings().set("/app/show_developer_preference_section", True) await ui_test.human_delay(10) omni.kit.window.preferences.select_page(omni.kit.window.preferences.get_instance()._developer_preferences) await ui_test.human_delay(10) await self._change_values()
2,284
Python
40.545454
114
0.672067
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/__init__.py
from .test_preferences import * from .test_stage import * from .test_pages import *
84
Python
20.249995
31
0.75
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_preferences.py
import os import unittest import carb import omni.kit.test from omni.kit.window.preferences.scripts.preferences_window import ( PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, ) class TestPreferencesWindow(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_new_preferences_window(self): called_init = False called_del = False class TestPreferences(PreferenceBuilder): def __init__(self): super().__init__("Test") def build(self): nonlocal called_init called_init = True def __del__(self): super().__del__() nonlocal called_del called_del = True self.assertFalse(called_init) self.assertFalse(called_del) called_init = False called_del = False page = omni.kit.window.preferences.register_page(TestPreferences()) omni.kit.window.preferences.select_page(page) omni.kit.window.preferences.rebuild_pages() prefs = omni.kit.window.preferences.get_instance() self.assertTrue(called_init) self.assertFalse(called_del) called_init = False called_del = False omni.kit.window.preferences.unregister_page(page) del page self.assertFalse(called_init) self.assertTrue(called_del)
1,450
Python
25.381818
75
0.608276
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_material.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb import omni.usd import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase class PreferencesTestDragDropImport(AsyncTestCase): # Before running each test async def setUp(self): from omni.kit import ui_test carb.settings.get_settings().set("/persistent/app/material/dragDropMaterialPath", "Absolute") omni.kit.window.preferences.show_preferences_window() for page in omni.kit.window.preferences.get_page_list(): if page.get_title() == "Material": omni.kit.window.preferences.select_page(page) await ui_test.human_delay(50) break # After running each test async def tearDown(self): carb.settings.get_settings().set("/persistent/app/material/dragDropMaterialPath", "Absolute") async def test_l1_app_materla_drag_drop_path(self): from omni.kit import ui_test frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_Material'") import_combo = frame.find("**/ComboBox[*].identifier=='/persistent/app/material/dragDropMaterialPath'") index_model = import_combo.model.get_item_value_model(None, 0) import_list = import_combo.model.get_item_children(None) for index, item in enumerate(import_list): index_model.set_value(item.model.value) await ui_test.human_delay(50) self.assertEqual(carb.settings.get_settings().get('/persistent/app/material/dragDropMaterialPath'), item.model.as_string)
2,000
Python
42.499999
133
0.706
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_stage.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb import omni.usd import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase class PreferencesTestDragDropImport(AsyncTestCase): # Before running each test async def setUp(self): from omni.kit import ui_test carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference") omni.kit.window.preferences.show_preferences_window() for page in omni.kit.window.preferences.get_page_list(): if page.get_title() == "Stage": omni.kit.window.preferences.select_page(page) await ui_test.human_delay(50) break # After running each test async def tearDown(self): carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference") async def test_l1_app_stage_drag_drop_import(self): from omni.kit import ui_test frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_Import'") import_combo = frame.find("**/ComboBox[*]") import_combo.widget.scroll_here_y(0.5) await ui_test.human_delay(50) index_model = import_combo.model.get_item_value_model(None, 0) import_list = import_combo.model.get_item_children(None) for index, item in enumerate(import_list): index_model.set_value(item.model.value) await ui_test.human_delay(50) self.assertEqual(carb.settings.get_settings().get('/persistent/app/stage/dragDropImport'), item.model.as_string) async def test_default_meters_zero(self): from omni.kit import ui_test # get widgets await ui_test.human_delay(10) frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_New Stage'") widget = frame.find("**/FloatSlider[*].identifier=='default_meters_per_unit'") # set to 0.5 widget.model.set_value(0.5) await ui_test.human_delay(10) # set to 0.0 - This is not allowed as minimum if 0.01 widget.model.set_value(0.0) await ui_test.human_delay(10) # verify self.assertAlmostEqual(widget.model.get_value_as_float(), 0.5)
2,667
Python
38.820895
124
0.674541
omniverse-code/kit/exts/omni.kit.window.preferences/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.3.8] - 2023-01-12 ### Changed - Fixed `create_setting_widget_combo` to support `setting_is_index` - Pages with same name to be grouped into same page ## [1.3.7] - 2022-09-13 ### Changed - Prevented "Material render context has been changed" message when stage not saved ## [1.3.6] - 2022-08-23 ### Changed - Alpha sorted page names ## [1.3.4] - 2022-07-27 ### Changed - Added "/omnihydra/staticMaterialNetworkTopology" to stage page ## [1.3.3] - 2022-06-22 ### Changed - Added "/persistent/app/material/dragDropMaterialPath" to materials page ## [1.3.2] - 2022-06-08 ### Changed - Updated menus to use actions ## [1.3.1] - 2022-06-06 ### Changed - Removed omni.kit.ui support ## [1.2.2] - 2022-02-22 ### Changed - Added stage import usd method payload/reference - Added identifier to `ui.CollapsableFrame` in `add_frame` ## [1.2.1] - 2022-02-22 ### Changed - Changed implementation on label function ## [1.2.0] - 2022-02-16 ### Added - Allow widgets to display tooltip information ## [1.1.5] - 2021-10-20 ### Changes - Cleans up on shutdown, including releasing handle to FilePickerDialog. ## [1.1.4] - 2021-10-18 ### Changes - Use float type for rateLimitFrequency in preferences. ## [1.1.3] - 2021-07-10 ### Added - Added support for "deep linking" of specific Preference pages from external components. ## [1.1.2] - 2021-05-19 ### Changes - Force "Preferences" to always at the bottom of the edit menu ## [1.1.1] - 2021-05-06 ### Changes - Added feeback when user changes `/app/hydra/material/renderContext` ## [1.1.0] - 2021-03-25 ### Changes - Added `PreferenceBuilder` for new `omni.ui` - Updated existing Pages to use `PreferenceBuilder` - Updated `PreferencePage` it still works, but now depricated ## [1.0.3] - 2021-03-02 ### Changes - Added test ## [1.0.2] - 2020-12-17 ### Changes - Updated menu to use `omni.kit.menu.utils` ## [1.0.1] - 2020-10-17 ### Changes - Added filepicker API - Updated pages to use new filepicker API ## [1.0.0] - 2020-08-13 ### Changes - Converted to extension 2.0
2,122
Markdown
22.853932
89
0.682846
omniverse-code/kit/exts/omni.kit.window.preferences/data/tests/material.config.carb.toml
[tests] paths = [ "C:/some/project/materials", "omniverse://another/project/materials", "/my/own/materials", ] string = "coffee" float = 24.0 bool = true
157
TOML
14.799999
41
0.66879
omniverse-code/kit/exts/omni.kit.window.preferences/data/tests/material.config.toml
[materialGraph] userAllowList = [ "my_materials", "my_maps", ] userBlockList = [ "foo_materials", "bar_maps", ] [options] noStandardPath = false [searchPaths] local = [ "C:/some/project/materials", "omniverse://another/project/materials", "/my/own/materials", ]
271
TOML
12.599999
41
0.678967
omniverse-code/kit/exts/omni.rtx.tests/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.4" # 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 = "RTX tests" description="Extension for RTX renderer python tests." # 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 = "Rendering" # Keywords for the extension keywords = ["kit", "rtx", "rendering", "tests"] # 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.commands" = {} "omni.kit.renderer.capture" = {} "omni.kit.test_helpers_gfx" = {} "omni.kit.window.property" = {} "omni.kit.viewport.utility" = {} "omni.usd" = {} # Temporary until we can move the tetmesh imaging # logic and test cases into the physics repo. "omni.usd.schema.physx" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.rtx.tests" [[test]] pythonTests.unreliable = [ "*UNSTABLE*" ] args = [ "--/renderer/enabled=rtx", "--/renderer/active=rtx", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", "--/app/asyncRendering=false", "--/app/captureFrame/setAlphaTo1=true", "--/omni.kit.plugin/syncUsdLoads=true", "--/rtx-transient/resourcemanager/texturestreaming/async=false", "--/rtx/materialDb/syncLoads=true", "--/rtx/hydra/materialSyncLoads=true", "--/rtx/pathtracing/lightcache/cached/enabled=false", "--/rtx/raytracing/lightcache/spatialCache/enabled=false", "--/rtx/post/aa/op=0", "--/rtx-defaults/post/aa/op=0", "--/app/viewport/forceHideFps=true", "--/persistent/app/viewport/displayOptions=0", "--/persistent/app/primCreation/PrimCreationWithDefaultXformOps=true", "--/app/window/hideUi=true", "--/app/docks/disabled=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/window/width=512", "--/app/window/height=512", "--no-window", ] # Aftermath in lightmode (Windows only right now) "filter:platform"."windows-x86_64"."args" = [ "--/renderer/debug/aftermath/enabled=true", "--/renderer/debug/aftermath/useLightMode=true", ] dependencies = [ "omni.usd", "omni.kit.commands", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.hydra.rtx", "omni.kit.viewport.utility", "omni.kit.window.viewport", "omni.volume" # Tests use volume rendering ] profiling = false # RTX regression OM-51983 timeout = 700
2,936
TOML
28.969387
117
0.690395
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_common.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. ## import omni.appwindow import omni.kit.app import omni.kit.test import omni.kit.commands import omni.timeline import omni.usd import carb import carb.settings import carb.windowing import inspect import pathlib from omni.kit.test_helpers_gfx.compare_utils import finalize_capture_and_compare, ComparisonMetric from omni.kit.viewport.utility import get_active_viewport_window, next_viewport_frame_async from omni.kit.viewport.utility.tests.capture import capture_viewport_and_wait from pxr import Sdf, Gf, Usd, UsdGeom, UsdLux # This settings should be set before stage opening/creation testSettings = { "/app/window/hideUi": True, "/app/asyncRendering": False, "/app/docks/disabled": True, "/app/window/scaleToMonitor": False, "/app/viewport/forceHideFps": True, "/app/captureFrame/setAlphaTo1": True, "/rtx/materialDb/syncLoads": True, "/omni.kit.plugin/syncUsdLoads": True, "/rtx/hydra/materialSyncLoads": True, "/renderer/multiGpu/autoEnable": False, "/persistent/app/viewport/displayOptions": 0, "/app/viewport/grid/enabled": False, "/app/viewport/show/lights": False, "/persistent/app/primCreation/PrimCreationWithDefaultXformOps": True, "/rtx-transient/resourcemanager/texturestreaming/async": False, "/app/viewport/outline/enabled": True } # Settings that should override settings that was set on stage opening/creation postLoadTestSettings = { "/rtx/post/aa/op": 0, "/rtx/pathtracing/lightcache/cached/enabled": False, "/rtx/raytracing/lightcache/spatialCache/enabled": False, "/rtx/sceneDb/ambientLightIntensity": 1.0, "/rtx/indirectDiffuse/enabled": False, } postLoadSkelTestSettings = { "/rtx/post/aa/op": 0, "/rtx/shadows/enabled": False, "/rtx/reflections/enabled": False, "/rtx/ambientOcclusion/enabled": False, "/rtx/post/tonemap/op": 1, "/renderer/multiGpu/autoEnable": False, } RENDER_WIDTH_SETTING = "/app/renderer/resolution/width" RENDER_HEIGHT_SETTING = "/app/renderer/resolution/height" OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path()) EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("data/golden") USD_DIR = EXTENSION_FOLDER_PATH.joinpath("data/usd") VOLUMES_DIR = EXTENSION_FOLDER_PATH.joinpath("data/volumes") async def next_resize_async(): """ Wait for the next event in the resize event stream of IAppWindow::getWindowResizeEventStream. We need it because the window resize event stream is independent of IApp::getUpdateEventStream. Without this function it's possible that resize happens several updates after. It's reproducable on Linux Release build. """ return await omni.appwindow.get_default_app_window().get_window_resize_event_stream().next_event() async def wait_for_update(usd_context=omni.usd.get_context(), wait_frames=10): max_loops = 0 while max_loops < wait_frames: _, files_loaded, total_files = usd_context.get_stage_loading_status() await omni.kit.app.get_app().next_update_async() if files_loaded or total_files: continue max_loops = max_loops + 1 def set_cursor_position(pos): app_window = omni.appwindow.get_default_app_window() windowing = carb.windowing.acquire_windowing_interface() os_window = app_window.get_window() windowing.set_cursor_position(os_window, pos) def set_transform_helper( prim_path, translate=Gf.Vec3d(0, 0, 0), euler=Gf.Vec3d(0, 0, 0), scale=Gf.Vec3d(1, 1, 1), ): rotation = ( Gf.Rotation(Gf.Vec3d.ZAxis(), euler[2]) * Gf.Rotation(Gf.Vec3d.YAxis(), euler[1]) * Gf.Rotation(Gf.Vec3d.XAxis(), euler[0]) ) xform = Gf.Matrix4d().SetScale(scale) * Gf.Matrix4d().SetRotate(rotation) * Gf.Matrix4d().SetTranslate(translate) omni.kit.commands.execute( "TransformPrimCommand", path=prim_path, new_transform_matrix=xform, ) async def setup_viewport_test_window(resolution_x: int, resolution_y: int, position_x: int = 0, position_y: int = 0): from omni.kit.viewport.utility import get_active_viewport_window viewport_window = get_active_viewport_window() if viewport_window: viewport_window.position_x = position_x viewport_window.position_y = position_y viewport_window.width = resolution_x viewport_window.height = resolution_y viewport_window.viewport_api.resolution = (resolution_x, resolution_y) return viewport_window class RtxTest(omni.kit.test.AsyncTestCase): THRESHOLD = 1e-5 WINDOW_SIZE = (640, 480) def __init__(self, tests=()): super().__init__(tests) self._saved_width = None self._saved_height = None self._savedSettings = {} self._failedImages = [] @property def __test_name(self) -> str: """ The full name of the test. It has the name of the module, class and the current test function. We use the stack to get the name of the test function and since it's only called from create_test_window and finalize_test, we get the third member. """ return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" async def create_test_area(self, width: int = 256, height: int = 256): """Resize the main window""" app_window = omni.appwindow.get_default_app_window() await omni.usd.get_context().new_stage_async() viewport_window = await setup_viewport_test_window(width, height) self.assertTrue(viewport_window is not None, "No active viewport window found.") # Current main window size current_width = app_window.get_width() current_height = app_window.get_height() # If the main window is already has requested size, do nothing if width == current_width and height == current_height: self._saved_width = None self._saved_height = None else: # Save the size of the main window to be able to restore it at the end of the test self._saved_width = current_width self._saved_height = current_height app_window.resize(width, height) # Wait for getWindowResizeEventStream await next_resize_async() # Wait until the Viewport has delivered some frames await next_viewport_frame_async(viewport_window.viewport_api, 0) async def screenshot_and_diff(self, golden_img_dir: pathlib.Path, output_subdir=None, golden_img_name=None, threshold=THRESHOLD): """ Capture the current frame and compare it with the golden image. Assert if the diff is more than given threshold. This method differs from capture_and_compare in that it lets callers outside omni.rtx.tests capture and compare images in their own directories. The screen captures will be placed in a common place with the rtx.tests output, either in a subdirectory passed in as output_subdir, or in a directory named for the test module. Golden images will be found in the directory passed in as golden_img_dir, this is the only required parameter. """ if not golden_img_dir: self.assertTrue(golden_img_dir, "A valid golden image dir is a required parameter") if not output_subdir: output_subdir = f"{self.__module__}" output_img_dir = OUTPUTS_DIR.joinpath(output_subdir) if not golden_img_name: golden_img_name = f"{self.__test_name}.png" return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir) async def capture_and_compare(self, img_subdir: pathlib.Path = None, golden_img_name=None, threshold=THRESHOLD, metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED): """ Capture current frame and compare it with the golden image. Assert if the diff is more than given threshold. """ golden_img_dir = GOLDEN_DIR.joinpath(img_subdir) output_img_dir = OUTPUTS_DIR.joinpath(img_subdir) if not golden_img_name: golden_img_name = f"{self.__test_name}.png" return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric) async def _capture_and_compare(self, golden_img_name, threshold, output_img_dir: pathlib.Path, golden_img_dir: pathlib.Path, metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED): # Capture directly from the Viewport's texture, not from UI swapchain await capture_viewport_and_wait(golden_img_name, output_img_dir) # Do the image comparison now diff = finalize_capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric=metric) if diff != 0: carb.log_warn(f"[{self.__test_name}] the generated image {golden_img_name} has max difference {diff}") if (diff is not None) and diff >= threshold: self._failedImages.append(golden_img_name) return diff def add_dir_light(self): omni.kit.commands.execute( "CreatePrimCommand", prim_path="/World/Light", prim_type="DistantLight", select_new_prim=False, # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 attributes={UsdLux.Tokens.inputsAngle: 1.0, UsdLux.Tokens.inputsIntensity: 3000} if hasattr(UsdLux.Tokens, 'inputsIntensity') else {UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.intensity: 3000}, create_default_xform=True, ) def add_floor(self): floor_path = "/World/Floor" omni.kit.commands.execute( "CreatePrimCommand", prim_path=floor_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100}, ) floor_prim = self.ctx.get_stage().GetPrimAtPath(floor_path) floor_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(25, 0.1, 25)) floor_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) def open_usd(self, usdSubpath: pathlib.Path): path = USD_DIR.joinpath(usdSubpath) omni.usd.get_context().open_stage(str(path)) def get_volumes_path(self, volumeSubPath: pathlib.Path): return Sdf.AssetPath(str(VOLUMES_DIR.joinpath(volumeSubPath))) def set_settings(self, newSettings): settingsAPI = carb.settings.get_settings() for s, v in newSettings.items(): if s not in self._savedSettings: # Remember old setting only when it was changed first time self._savedSettings[s] = settingsAPI.get(s) if v is None: # hideUi sometimes is None and it hangs kit v = False settingsAPI.set(s, v) def set_camera(self, cameraPos=None, targetPos=None): from omni.kit.viewport.utility.camera_state import ViewportCameraState camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(cameraPos, True) camera_state.set_target_world(targetPos, True) async def setUp_internal(self): self.ctx = omni.usd.get_context() await self.create_test_area(self.WINDOW_SIZE[0], self.WINDOW_SIZE[1]) async def setUp(self): await self.setUp_internal() async def tearDown(self): # Restore main window resolution if it was saved if self._saved_width is not None and self._saved_height is not None: app_window = omni.appwindow.get_default_app_window() app_window.resize(self._saved_width, self._saved_height) # Wait for getWindowResizeEventStream await next_resize_async() self.set_settings(self._savedSettings) self.ctx.close_stage() for imgName in self._failedImages: carb.log_warn(f"[{self.__test_name}] The image {imgName} doesn't match the golden") hasFailed = len(self._failedImages) self._failedImages = [] self.assertEqual(hasFailed, 0)
12,851
Python
41.415841
142
0.668897
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_domelight.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom, UsdLux, Gf, Sdf class TestRtxDomelight(RtxTest): TEST_PATH = "domelight" DOMELIGHT_PRIM_PATH = "/World/DomeLight" def create_mesh(self): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), "/World/box") box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box def create_dome_light(self, name=DOMELIGHT_PRIM_PATH): omni.kit.commands.execute( "CreatePrim", prim_path=name, prim_type="DomeLight", select_new_prim=False, # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 attributes={ UsdLux.Tokens.inputsIntensity: 1, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.inputsTextureFile: "daytime.hdr", UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited, } if hasattr(UsdLux.Tokens, 'inputsIntensity') else { UsdLux.Tokens.intensity: 1, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.textureFile: "daytime.hdr", UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited, }, create_default_xform=True, ) dome_light_prim = self.ctx.get_stage().GetPrimAtPath(name) return dome_light_prim async def setUp(self): await self.setUp_internal() print("RTX DomeLight Tests Setup") self.set_settings(testSettings) super().open_usd("hydra/dome_materials.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) my_settings = { "/rtx/pathtracing/lightcache/cached/enabled": False, "/rtx/raytracing/lightcache/spatialCache/enabled" : False, "/rtx-transient/resourcemanager/genMipsForNormalMaps" : False, "/rtx-transient/resourcemanager/texturestreaming/async" : False, "/rtx-transient/samplerFeedbackTileSize" : 1, "/rtx/post/aa/op" : 0, # 0 = None, 2 = FXAA "/rtx/directLighting/sampledLighting/enabled" : False, "/rtx/reflections/sampledLighting/enabled" : False, # LTC gives consistent lighting # perMaterialSyncLoads: Very important, otherwise the material updates for the domelight # materials (MDLs) are not sync-ed and updated properly. "/rtx/hydra/perMaterialSyncLoads" : True, } self.set_settings(my_settings) async def test_domelight_material_assignment(self): """ Test Domelight material assignment """ looksPath = "/World/Looks/" # Scene Setup self.set_settings({"/rtx/domeLight/baking/resolution": "1024"}) # We could show some minimal mesh but that might create false positives in the lighting. #self.create_mesh() dome_prim = self.create_dome_light() # The loaded domelight had a texture assigned check it: # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): dome_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(100) else: dome_prim.GetAttribute(UsdLux.Tokens.intensity).Set(100) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_texture_assigned.png") # Bind a material to the domelight # This material shows the emission direction in a color-coded way. omni.kit.commands.execute('BindMaterial', material_path=looksPath + "dome_emission_direction", prim_path=[self.DOMELIGHT_PRIM_PATH], strength=['weakerThanDescendants']) # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): dome_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(1) else: dome_prim.GetAttribute(UsdLux.Tokens.intensity).Set(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_emission_direction_mat.png") # Bind a different material to the domelight omni.kit.commands.execute('BindMaterial', material_path='/World/Looks/dome_gridspherejulia', prim_path=['/World/DomeLight'], strength=['weakerThanDescendants']) # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): dome_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(1) else: dome_prim.GetAttribute(UsdLux.Tokens.intensity).Set(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_gridspherejulia_mat.png") # Set a different baking resolution self.set_settings({"/rtx/domeLight/baking/resolution": "256"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_baking_resolution.png") # Testing domelight per pixel evaluation: # JIRA OM-49492 self.set_settings({ "/rtx/pathtracing/domeLight/primaryRaysEvaluateDomelightMdlDirectly" : True, "/rtx/rendermode" : 'PathTracing', "/rtx/pathtracing/spp" : 1, "/rtx/pathtracing/totalSpp" : 1, }) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04a_mdl_direct_evaluation.png") # Create another domelight (JIRA OM-19501) # The visible domelight can be any domelight if multiple domelights are in the scene. # Internally it depends which one is in the domelight buffer[0]. # Therefore, we need to explicitly disable the first one to see the result of the second. self.set_settings({ "/rtx/rendermode" : 'RaytracedLighting', }) dome2_path = "/World/DomeLight_2" dome_prim2 = self.create_dome_light(dome2_path) # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): dome_prim2.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(100) else: dome_prim2.GetAttribute(UsdLux.Tokens.intensity).Set(100) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/DomeLight_2.xformOp:rotateXYZ'), value=Gf.Vec3d(270.0, -90.0, 0.0), prev=Gf.Vec3d(270.0, 0.0, 0.0)) # Disable the first dome light dome_prim.GetAttribute(UsdGeom.Tokens.visibility).Set(UsdGeom.Tokens.invisible) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_second_domelight.png")
7,828
Python
47.030675
113
0.646525
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_material_distilling_toggle.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update class TestMaterialDistillingToggle(RtxTest): """ rtx test running renderer with material distilling toggle on to ensure renderer correctly loads in neuraylib plugins, compiles shader cache, inserts preprocessor macro (DISTILLED_MTL_MODE) """ async def setUp(self): await super().setUp() self.set_settings(testSettings) self.open_usd("material_distilling.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_material_distilling_toggle(self): await wait_for_update() await self.capture_and_compare("material_distilling_toggle", "material_distilling_toggle.png", 1e-3)
1,315
Python
42.866665
121
0.752091
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_skel.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. ## #TODO 02: omnihydra does not support dynamically switch animationsource on skelroot prim bindingAPI (should be a repopulate in this case) #TODO 03: omnihydra does not support joints/blendshapes change in skelanimation prim #TODO 04: omnihydra does not support blendshapes (target name) change in skelanimation prim (not in test) #TODO 05 when skelanimation become invalid, skinning result should retrive restTransform #TODO 06: after added time ranged control, the render result does not work correct for the specific animation source import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline import carb.settings from .test_hydra_common import RtxHydraTest from .test_common import testSettings, postLoadSkelTestSettings, set_transform_helper, wait_for_update from pxr import Gf, Sdf, Usd, UsdGeom, UsdSkel, UsdShade def _update_animation(animation : UsdSkel.Animation, animation_static : UsdSkel.Animation, timecode : Usd.TimeCode): trans = animation.GetTranslationsAttr().Get(timecode) rots = animation.GetRotationsAttr().Get(timecode) scales = animation.GetScalesAttr().Get(timecode) bsWeights = animation.GetBlendShapeWeightsAttr().Get(timecode) animation_static.GetTranslationsAttr().Set(trans) animation_static.GetRotationsAttr().Set(rots) animation_static.GetScalesAttr().Set(scales) animation_static.GetBlendShapeWeightsAttr().Set(bsWeights) class TestRtxHydraSkel(RtxHydraTest): TEST_PATH = "hydra/skel" async def setUp(self): await super().setUp() timeline = omni.timeline.get_timeline_interface() timeline.set_fast_mode(True) await omni.kit.app.get_app().next_update_async() async def test_01_skel_anim(self): """ Test hydra skel - skel anim """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelroot_path = "/Root/group1" skelroot_prim = stage.GetPrimAtPath(skelroot_path) skelroot = UsdSkel.Root(skelroot_prim) skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() # pure skeleton test await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_0_skeleton_0.png") #Test animation skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_1.png") timeline.set_current_time(1.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_2.png") skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_3.png") #Test animation in session layer (resync) with Usd.EditContext(stage, session_layer): skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_1.png") timeline.set_current_time(1.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_2.png") stage.RemovePrim(skeleton_path) self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_3.png") await wait_for_update() self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) #Test animation switch skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_1.png") skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_2.png") #Test animation switch in session layer with Usd.EditContext(stage, session_layer): skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path]) timeline.set_current_time(0.0) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_sessionlayer_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_sessionlayer_1.png") #TODO 06: after added time ranged control, the render result does not work correct for the specific animation source stage.RemovePrim(skeleton_path) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_sessionlayer_2.png") #Test animation switch to outside root animation await wait_for_update() self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_outside_path]) await wait_for_update() self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_outside_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_1.png") skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) await wait_for_update() self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) #Test animation switch to outside root animation in session layer with Usd.EditContext(stage, session_layer): skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_outside_path]) await wait_for_update() self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_outside_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_sessionlayer_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_sessionlayer_1.png") stage.RemovePrim(skeleton_path) ##TODO 02: omnihydra does not support dynamically switch animationsource on skelroot prim bindingAPI (should be a repopulate in this case) ##Test animation switch to at skelroot prim #skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #await wait_for_update() #self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) #skelroot_bindingAPI = UsdSkel.BindingAPI.Apply(skelroot_prim) #skelroot_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path]) #await wait_for_update() #self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim) #timeline.set_current_time(0.0) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_0.png") #timeline.set_current_time(0.5) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_1.png") #skelroot_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #self.assertTrue(not skelroot_bindingAPI.GetInheritedAnimationSource()) ##Test animation switch to outside root animation in session layer #with Usd.EditContext(stage, session_layer): # skelroot_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path]) # await wait_for_update() # self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_sessionlayer_0.png") # timeline.set_current_time(0.5) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_sessionlayer_1.png") # stage.RemovePrim(skeleton_path) timeline.set_auto_update(True) timeline.stop() async def test_02_skel_anim_update(self): """ Test hydra skel - skel animation update """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() #Test SRT/bsweights update skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_static_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_static_prim) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_0.png") timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond()) with Sdf.ChangeBlock(): _update_animation(animation, animation_static, timecode) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_1.png") #non play test timeline.play() timeline.set_auto_update(False) timeline.set_current_time(1.0) await omni.kit.app.get_app().next_update_async() timecode = Usd.TimeCode(timeline.get_current_time() * stage.GetTimeCodesPerSecond()) with Sdf.ChangeBlock(): _update_animation(animation, animation_static, timecode) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_2.png") # play test timeline.set_auto_update(True) timeline.stop() timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() with Sdf.ChangeBlock(): _update_animation(animation, animation_static, Usd.TimeCode.Default()) #Test SRT/bsweights update in session layer with Usd.EditContext(stage, session_layer): self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_static_prim) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_sessionlayer_0.png") timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond()) with Sdf.ChangeBlock(): _update_animation(animation, animation_static, timecode) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_sessionlayer_1.png") #non play test stage.RemovePrim(animation_static_path) timeline.set_current_time(1.0) await omni.kit.app.get_app().next_update_async() timecode = Usd.TimeCode(timeline.get_current_time() * stage.GetTimeCodesPerSecond()) with Sdf.ChangeBlock(): _update_animation(animation, animation_static, timecode) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_2_animation_update_sessionlayer_2.png") # play test timeline.set_auto_update(True) timeline.stop() await omni.kit.app.get_app().next_update_async() stage.RemovePrim(animation_static_path) ###Test joint change ##TODO 03: omnihydra does not support joints/blendshapes change in skelanimation prim ##TODO 04: omnihydra does not support blendshapes (target name) change in skelanimation prim (not in test) #with Sdf.ChangeBlock(): #_update_animation(animation, animation_static, Usd.TimeCode.Default()) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_0.png") #timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) #trans = animation.GetTranslationsAttr().Get(timecode) #rots = animation.GetRotationsAttr().Get(timecode) #scales = animation.GetScalesAttr().Get(timecode) #joints = animation.GetJointsAttr().Get() #new_joints = joints.__getitem__(slice(0,3,1)) #new_trans = trans.__getitem__(slice(0,3,1)) #new_rots = rots.__getitem__(slice(0,3,1)) #new_scales = scales.__getitem__(slice(0,3,1)) #animation_static.GetJointsAttr().Set(new_joints) #animation_static.GetTranslationsAttr().Set(new_trans) #animation_static.GetRotationsAttr().Set(new_rots) #animation_static.GetScalesAttr().Set(new_scales) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_1.png") #new_joints = joints.__getitem__(slice(0,2,1)) #new_trans = trans.__getitem__(slice(0,2,1)) #new_rots = rots.__getitem__(slice(0,2,1)) #new_scales = scales.__getitem__(slice(0,2,1)) #animation_static.GetJointsAttr().Set(new_joints) #animation_static.GetTranslationsAttr().Set(new_trans) #animation_static.GetRotationsAttr().Set(new_rots) #animation_static.GetScalesAttr().Set(new_scales) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_2.png") #animation_static.GetJointsAttr().Set(joints) #animation_static.GetTranslationsAttr().Set(trans) #animation_static.GetRotationsAttr().Set(rots) #animation_static.GetScalesAttr().Set(scales) #await wait_for_update() ###Test joint change in session layer #animation_static.GetJointsAttr().Set(joints) #with Sdf.ChangeBlock(): #_update_animation(animation, animation_static, Usd.TimeCode.Default()) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_sessionlayer_0.png") #with Usd.EditContext(stage, session_layer): # timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) # trans = animation.GetTranslationsAttr().Get(timecode) # rots = animation.GetRotationsAttr().Get(timecode) # scales = animation.GetScalesAttr().Get(timecode) # joints = animation.GetJointsAttr().Get() # new_joints = joints.__getitem__(slice(0,3,1)) # new_trans = trans.__getitem__(slice(0,3,1)) # new_rots = rots.__getitem__(slice(0,3,1)) # new_scales = scales.__getitem__(slice(0,3,1)) # animation_static.GetJointsAttr().Set(new_joints) # animation_static.GetTranslationsAttr().Set(new_trans) # animation_static.GetRotationsAttr().Set(new_rots) # animation_static.GetScalesAttr().Set(new_scales) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_sessionlayer_1.png") # new_joints = joints.__getitem__(slice(0,2,1)) # new_trans = trans.__getitem__(slice(0,2,1)) # new_rots = rots.__getitem__(slice(0,2,1)) # new_scales = scales.__getitem__(slice(0,2,1)) # animation_static.GetJointsAttr().Set(new_joints) # animation_static.GetTranslationsAttr().Set(new_trans) # animation_static.GetRotationsAttr().Set(new_rots) # animation_static.GetScalesAttr().Set(new_scales) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_sessionlayer_2.png") # animation_static.GetJointsAttr().Set(joints) # animation_static.GetTranslationsAttr().Set(trans) # animation_static.GetRotationsAttr().Set(rots) # animation_static.GetScalesAttr().Set(scales) # await wait_for_update() # stage.RemovePrim(animation_static_path) async def test_03_skel_anim_create_delete(self): """ Test hydra skel - skel animation update """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) trans = animation.GetTranslationsAttr().Get(timecode) rots = animation.GetRotationsAttr().Get(timecode) scales = animation.GetScalesAttr().Get(timecode) joints = animation.GetJointsAttr().Get() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_0_animation_create_0.png") animation_new_path = "/ZAnimation_New" animation_new = UsdSkel.Animation.Define(stage, animation_new_path) animation_new_prim = animation_new.GetPrim() await wait_for_update() self.assertTrue(animation_new_prim) with Sdf.ChangeBlock(): animation_new.GetJointsAttr().Set(joints) animation_new.GetTranslationsAttr().Set(trans) animation_new.GetRotationsAttr().Set(rots) animation_new.GetScalesAttr().Set(scales) skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_new_path]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_0_animation_create_1.png") stage.RemovePrim(animation_new_path) skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #This line should supposed not to be needed #TODO 05 when skelanimation become invalid, skinning result should retrive restTransform await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_1_animation_delete_0.png") with Usd.EditContext(stage, session_layer): animation_new = UsdSkel.Animation.Define(stage, animation_new_path) animation_new_prim = animation_new.GetPrim() await wait_for_update() self.assertTrue(animation_new_prim) with Sdf.ChangeBlock(): animation_new.GetJointsAttr().Set(joints) animation_new.GetTranslationsAttr().Set(trans) animation_new.GetRotationsAttr().Set(rots) animation_new.GetScalesAttr().Set(scales) skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_new_path]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_2_animation_create_sessionlayer_0.png") with Sdf.ChangeBlock(): stage.RemovePrim(animation_new_path) skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #This line should supposed not to be needed #TODO 05 when skelanimation become invalid, skinning result should retrive restTransform skel_root_prim = stage.GetPrimAtPath("/Root/group1") skel_root = UsdSkel.Root(skel_root_prim) visible = skel_root.GetVisibilityAttr().Set("invisible") await wait_for_update() # test repopulate crash due to resync by update visibility in skelroot. skel_root.GetVisibilityAttr().Set("inherited") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_3_animation_delete_with_root_recync_sessionlayer_0.png") #This test is temporarily since we cannot dynamically update animation source on skelroot's bindAPI in omnihydra yet. async def test_04_skel_anim_on_skel_root(self): """ Test hydra skel - skel anim on root """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder_root.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelroot_path = "/Root/group1" skelroot_prim = stage.GetPrimAtPath(skelroot_path) skelroot = UsdSkel.Root(skelroot_prim) skelroot_bindingAPI = UsdSkel.BindingAPI(skelroot_prim) skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() # pure skeleton test await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_0_skeleton_0.png") #Test animation self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_1_animation_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_1_animation_1.png") timeline.set_current_time(1.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_1_animation_2.png") timeline.set_auto_update(True) timeline.stop() await omni.kit.app.get_app().next_update_async() async def test_05_skel_anim_update_restTransforms(self): """ Test hydra skel - update restTransforms """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder.usda") # self.set_settings(postLoadSkelTestSettings) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelroot_path = "/Root/group1" skelroot_prim = stage.GetPrimAtPath(skelroot_path) skelroot = UsdSkel.Root(skelroot_prim) skelroot_bindingAPI = UsdSkel.BindingAPI(skelroot_prim) skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() # pure skeleton test await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_0_skeleton_0.png") #Test animation self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) timecode = Usd.TimeCode.Default() poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_0.png") timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond()) poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_1.png") timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_2.png") with Usd.EditContext(stage, session_layer): timecode = Usd.TimeCode.Default() poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_session_layer_0.png") timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond()) poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_session_layer_1.png") timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_session_layer_2.png") timeline.set_auto_update(True) timeline.stop() await omni.kit.app.get_app().next_update_async() async def test_06_skel_anim_reference(self): """ Test hydra skel - skel anim reference """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder_ref.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelroot_path = "/Root/group1" skelroot_prim = stage.GetPrimAtPath(skelroot_path) skelroot = UsdSkel.Root(skelroot_prim) skelroot_bindingAPI = UsdSkel.BindingAPI(skelroot_prim) skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() # pure skeleton tests await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_0_skeleton_0.png") # Test animation self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) refs = animation_prim.GetReferences() refs.SetReferences([Sdf.Reference(assetPath="./assets/skelcylinder_anim_flat.usda")]) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_1_animation_reference_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_1_animation_reference_1.png") timeline.set_current_time(1.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_1_animation_reference_2.png") timeline.set_auto_update(True) timeline.stop() async def test_07_skel_mesh_material_switch(self): """ Test hydra skel - skel anim reference """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder_material_test.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelmesh1_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder1" skelmesh1_prim = stage.GetPrimAtPath(skelmesh1_path) skelmesh2_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder2" skelmesh2_prim = stage.GetPrimAtPath(skelmesh2_path) print(skelmesh2_prim) material_red_path = "/Root/Looks/PreviewSurface_Red" material_blue_path = "/Root/Looks/PreviewSurface_Blue" session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await wait_for_update() # pure skeleton tests timeline.set_current_time(0.1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_0.png") # Test animations omni.kit.commands.execute( "BindMaterial", prim_path=Sdf.Path(skelmesh1_path), material_path=Sdf.Path(material_blue_path), strength=UsdShade.Tokens.weakerThanDescendants, ) timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_1.png") omni.kit.commands.execute( "BindMaterial", prim_path=Sdf.Path(skelmesh2_path), material_path=Sdf.Path(material_red_path), strength=UsdShade.Tokens.weakerThanDescendants, ) timeline.set_current_time(0.6) await wait_for_update() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_2.png") imageable = UsdGeom.Imageable(skelmesh2_prim) imageable.MakeInvisible() timeline.set_current_time(0.7) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_3.png") timeline.set_auto_update(True) timeline.stop() async def test_08_skel_mesh_animation_rename(self): """ Test hydra skel - skel anim reference """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder_material_test.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelmesh1_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder1" skelmesh1_prim = stage.GetPrimAtPath(skelmesh1_path) skelmesh2_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder2" skelmesh2_prim = stage.GetPrimAtPath(skelmesh2_path) animation_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) new_animation_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_joint1/Animation2" session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await wait_for_update() # pure skeleton tests timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_0.png") old_prim_name = Sdf.Path(animation_path) move_dict = {old_prim_name: new_animation_path} omni.kit.commands.execute("MovePrims", paths_to_move=move_dict, destructive=False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_1.png") omni.kit.undo.undo() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_2.png") # Test animations omni.kit.commands.execute( "DeletePrims", paths=[Sdf.Path(animation_path)] ) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_3.png") omni.kit.undo.undo() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_4.png") timeline.set_auto_update(True) timeline.stop()
40,592
Python
50.448669
212
0.674985
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_light_collections.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.kit.commands import omni.kit.undo from .test_hydra_common import RtxHydraTest from .test_common import wait_for_update class TestRtxHydraLightCollections(RtxHydraTest): """ To run: from omni.kit.test import unittests from omni.rtx.tests import test_hydra_light_collections unittests.run_tests_in_modules([test_hydra_light_collections]) """ TEST_PATH = "hydra/lightCollections" LIGHT_PATH = "/World/defaultLight" LIGHT_VIS_PATH = LIGHT_PATH + ".visibility" LIGHT_SHADOW_EXCLUDE_PATH = LIGHT_PATH + ".collection:shadowLink:excludes" LIGHT_LINK_INCLUDE_PATH = LIGHT_PATH + ".collection:lightLink:includeRoot" CUBE_PATH = "/World/Cube" SHADOW_LINK_INCLUDE_PATH = LIGHT_PATH + ".collection:shadowLink:includeRoot" async def test_UNSTABLE_light_collection_undo(self): """ Regression test for usdImaging refresh issue when undoing light deletion """ self.open_usd("hydra/LightLink.usda") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-4) omni.kit.commands.execute("DeletePrims", paths=[self.LIGHT_PATH]) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionBlack.png", 1e-4) omni.kit.undo.undo() await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-4) # OM-56283, CI-1655 - Sporadic crash/unreliable image output async def test_UNSTABLE_light_collection_toggle_crash_UNSTABLE(self): """ Regression test for crash in Light Collection toggle """ self.open_usd("hydra/LightLink.usda") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=True, prev=False) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionInactive.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.SHADOW_LINK_INCLUDE_PATH, value=False, prev=True) await wait_for_update(wait_frames=1) omni.kit.commands.execute("ChangeProperty", prop_path=self.SHADOW_LINK_INCLUDE_PATH, value=True, prev=False) await wait_for_update(wait_frames=1) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=False, prev=True) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3) async def test_UNSTABLE_light_collection_lightvistoggle(self): """ Regression test for refresh issue when toggling light visibility """ self.open_usd("hydra/LightLink.usda") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_VIS_PATH, value="invisible", prev="inherited") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionBlack.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_VIS_PATH, value="inherited", prev="invisible") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3) # OM-53278 - occasionally produces pitch black image async def test_UNSTABLE_light_collection_refresh_issue_when_light_and_shadow_are_the_same_UNSTABLE(self): """ Regression test for refresh issue when the light and shadow collections become the same This is a regression test for OM-48040 Light Linking: light goes off after toggling Include Root on/off """ self.open_usd("hydra/LightLinkSimple.usda") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionSimpleCubeNoLight.png", 1e-3) omni.kit.commands.execute( "AddRelationshipTarget", relationship=omni.usd.get_context().get_stage().GetPropertyAtPath(self.LIGHT_SHADOW_EXCLUDE_PATH), target=self.CUBE_PATH ) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionSimpleCubeNoShadow.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=False, prev=True) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionBlack.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=True, prev=False) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionSimpleCubeNoShadow.png", 1e-3)
5,550
Python
43.766129
119
0.709369
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_postprocessing_tonemapper.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. ## import omni.kit.app import omni.kit.test import omni.kit.commands import carb import pathlib from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from .test_common import USD_DIR, EXTENSION_FOLDER_PATH from pxr import Gf, Sdf, Usd from pxr import UsdGeom, UsdLux class TestRtxPostprocessingTonemapper(RtxTest): TEST_PATH = "tonemapping" def open_usd_scene(self, path : pathlib.Path): omni.usd.get_context().open_stage(str(path)) def create_dome_light(self, name="/Xform/DomeLight"): omni.kit.commands.execute( "CreatePrim", prim_path=name, prim_type="DomeLight", select_new_prim=False, attributes={ UsdLux.Tokens.inputsIntensity: 1, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.inputsTextureFile: str(EXTENSION_FOLDER_PATH.joinpath("data/usd/hydra/daytime.hdr")), UsdGeom.Tokens.visibility: "inherited", } if hasattr(UsdLux.Tokens, 'inputsIntensity') else { UsdLux.Tokens.intensity: 1, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.textureFile: str(EXTENSION_FOLDER_PATH.joinpath("data/usd/hydra/daytime.hdr")), UsdGeom.Tokens.visibility: "inherited", }, create_default_xform=True, ) dome_light_prim = self.ctx.get_stage().GetPrimAtPath(name) return dome_light_prim async def setUp(self): await self.setUp_internal() carb.log_info("Setting up scene for RTX postprocessing tonemapping tests.") # Setting that should be set before opening a new stage self.set_settings(testSettings) rtxDataPath = EXTENSION_FOLDER_PATH.joinpath("../../../../../data/usd/tests") self.open_usd_scene(rtxDataPath.joinpath("BallCluster/ballcluster_stage.usda")) # Settings that should be set after opening a new stage self.set_settings(postLoadTestSettings) # camera setup: omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_path='/Ballcluster_set/Camera', prim_type='Camera', attributes={'focusDistance': 400, 'focalLength': 24, 'clippingRange': (1, 10000000)}, create_default_xform=False) omni.kit.commands.execute('TransformPrimCommand', path=Sdf.Path('/Ballcluster_set/Camera'), new_transform_matrix=Gf.Matrix4d(-0.6550639249522971, 0.7555734605093614, 6.112664085837494e-16, 0.0, 0.008064090705444693, 0.006991371699474781, 0.9999430439594318, 0.0, 0.7555304260366915, 0.6550266151048126, -0.010672808306432642, 0.0, 543.7716131933593, 536.4127523809548, 92.10006955095595, 1.0), old_transform_matrix=Gf.Matrix4d(-0.7071067811865474, 0.7071067811865478, 5.551115215516806e-17, 0.0, -0.4082482839677534, -0.4082482839677533, 0.8164965874238357, 0.0, 0.5773502737830692, 0.5773502737830688, 0.5773502600027394, 0.0, 500.0, 500.0, 500.0, 1.0), time_code=Usd.TimeCode.Default(), had_transform_at_key=False, usd_context_name='') # Create a domelight to get some high dynamic range going: self.domelight_prim = self.create_dome_light() # Disable this object so that the dome light is actually visible: omni.kit.commands.execute('DeletePrims', paths=['/Xform/sky_sphere_emiss'], destructive=False) await wait_for_update() # Activate the new camera: viewport_api = omni.kit.viewport.utility.get_active_viewport() viewport_api.set_active_camera("/Ballcluster_set/Camera") await omni.kit.app.get_app().next_update_async() my_settings = { "/app/hydraEngine/waitIdle" : True, "/app/renderer/waitIdle" : True, "/app/asyncRenderingLowLatency" : False, "/rtx-transient/resourcemanager/genMipsForNormalMaps" : False, "/rtx-transient/resourcemanager/texturestreaming/async" : False, "/rtx-transient/samplerFeedbackTileSize" : 1, "/rtx/hydra/perMaterialSyncLoads" : True, "/rtx/post/aa/op" : 0, # 0 = None, 2 = FXAA "/renderer/multiGpu/maxGpuCount" : 1, "/rtx/gatherColorToDisplayDevice" : True, "/rtx/rendermode" : 'PathTracing', "/rtx/raytracing/lightcache/spatialCache/enabled" : False, "/rtx/pathtracing/lightcache/cached/enabled" : False, "/rtx/pathtracing/cached/enabled" : False, "/rtx/pathtracing/optixDenoiser/enabled" : False, "/rtx/pathtracing/spp" : 1, "/rtx/pathtracing/totalSpp" : 1, "/rtx/pathtracing/maxBounces" : 2, "/rtx/hydra/perMaterialSyncLoads" : True, } self.set_settings(my_settings) await wait_for_update() # Marking unstable due to OM-86613 async def test_UNSTABLE_postprocessing_tonemappers_UNSTABLE(self): """ Test RTX Postprocessing Tonemappers """ self.set_settings({"/rtx/post/tonemap/op" : "0"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "0_tonemapper_test_clamp.png") # Make the domelight 'visible' for all non-clamp tonemappers # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): self.domelight_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(200) else: self.domelight_prim.GetAttribute(UsdLux.Tokens.intensity).Set(200) self.set_settings({"/rtx/post/tonemap/op" : "1"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "1_tonemapper_test_linear.png") self.set_settings({"/rtx/post/tonemap/op" : "2"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "2_tonemapper_test_reinhard.png") self.set_settings({"/rtx/post/tonemap/op" : "3"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "3_tonemapper_test_reinhard_modified.png") self.set_settings({"/rtx/post/tonemap/op" : "4"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "4_tonemapper_test_hejlhablealu.png") self.set_settings({"/rtx/post/tonemap/op" : "5"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "5_tonemapper_test_hableuc2.png") self.set_settings({"/rtx/post/tonemap/op" : "6"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "6_tonemapper_test_aces.png") self.set_settings({"/rtx/post/tonemap/op" : "7"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "7_tonemapper_test_iray.png")
7,492
Python
44.689024
115
0.645889
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/__init__.py
import sys if sys.platform == "win32": from .test_example import TestRtxExample1, TestRtxExample2 from .test_selectionoutline import TestRtxSelectionOutline from .test_hydra_mesh import * from .test_hydra_points import * from .test_hydra_basis_curves import * from .test_hydra_skel import * from .test_hydra_materials import * from .test_scenedb import TestRtxSceneDb from .test_hydra_light_collections import * from .test_hydra_volume import * from .test_domelight import TestRtxDomelight from .test_postprocessing_tonemapper import * from .test_light_toggling import * from .test_usdlux_schema_compat import * from .test_hydra_scene_delegate_omni_imaging import * from .test_picking import * from .test_material_distilling_toggle import * # Enable other extensions to use these test classes from .test_common import RtxTest, testSettings, postLoadTestSettings, OUTPUTS_DIR
944
Python
40.086955
81
0.745763
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_light_toggling.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test import omni.kit.commands import carb import pathlib from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from .test_common import EXTENSION_FOLDER_PATH from pxr import Gf, Sdf, Usd class TestRtxLightToggling(RtxTest): TEST_PATH = "light_toggling" def open_usd_scene(self, path : pathlib.Path): omni.usd.get_context().open_stage(str(path)) async def setUp(self): await self.setUp_internal() carb.log_info("Setting up scene for RTX postprocessing tonemapping tests.") self.set_settings(testSettings) rtxDataPath = EXTENSION_FOLDER_PATH.joinpath("../../../../../data/usd/tests") self.open_usd_scene(rtxDataPath.joinpath("KitchenSet/Kitchen_set.usda")) # camera setup: omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_path='/Kitchen_set/Camera', prim_type='Camera', attributes={'focusDistance': 400, 'focalLength': 24, 'clippingRange': (1, 10000000)}, create_default_xform=False) omni.kit.commands.execute('TransformPrimCommand', path=Sdf.Path('/Kitchen_set/Camera'), new_transform_matrix=Gf.Matrix4d( 0.929103525371008, 0.36981973871491086, 9.165845166192454e-16, 0.0, -0.07453993201486002, 0.18726775876424714, 0.9794766893921647, 0.0, 0.3622298133483562, -0.9100352451329841, 0.201557473037752, 0.0, 273.5074607559941, -621.0054603487383, 221.75447008156692, 1.0), old_transform_matrix=Gf.Matrix4d( 0.9305632067779971, 0.36613128545789503, 9.159340032886883e-16, 0.0, -0.09015111941855866, 0.22912905319151347, 0.9692123877928621, 0.0, 0.35485897742431627, -0.9019133876334855, 0.24622621174208614, 0.0, 328.2529492634561, -760.1471818173628, 259.74075506441545, 1.0), time_code=Usd.TimeCode.Default(), had_transform_at_key=False, usd_context_name='') # remove any selection, not sure why this happens, but otherwise weird bounding # boxes appear selection = omni.usd.get_context().get_selection() selection.clear_selected_prim_paths() await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) my_settings = { "/rtx/pathtracing/lightcache/cached/enabled": False, "/rtx/raytracing/lightcache/spatialCache/enabled" : False, "/rtx-transient/resourcemanager/genMipsForNormalMaps" : False, "/rtx-transient/resourcemanager/texturestreaming/async" : False, "/rtx-transient/samplerFeedbackTileSize" : 1, "/rtx/post/aa/op" : 0, # 0 = None, 2 = FXAA "/rtx/directLighting/sampledLighting/enabled" : False, # LTC gives consistent lighting "/rtx/reflections/enabled" : False, # Disabling reflections. "/rtx/reflections/sampledLighting/enabled" : False, # LTC gives consistent lighting "/rtx/sceneDb/ambientLightIntensity" : float(0.0), "/rtx/ambientOcclusion/enabled" : False, "/rtx/indirectDiffuse/enabled" : False, "/app/viewport/grid/enabled" : False, # Disable Kit Grid "/app/viewport/grid/showOrigin" : False, # Disable Kit Origin "/app/viewport/outline/enabled" : False, # Disable Selection drawing } self.set_settings(my_settings) async def test_light_toggling(self): """ Test RTX Light Toggling """ LIGHT_VIS_PATH = ".visibility" # Activate the main camera: viewport_api = omni.kit.viewport.utility.get_active_viewport() viewport_api.set_active_camera("/Kitchen_set/Camera") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "0_all_light_sources.png") # Disable SphereLight omni.kit.commands.execute("ChangeProperty", prop_path="/SphereLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "1_spherelight_off.png") # Disable DiskLight omni.kit.commands.execute("ChangeProperty", prop_path="/DiskLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "2_disklight_off.png") # Disable DistantLight # Disable RectLightLight omni.kit.commands.execute("ChangeProperty", prop_path="/DistantLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") omni.kit.commands.execute("ChangeProperty", prop_path="/RectLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") omni.kit.commands.execute("ChangeProperty", prop_path="/DiskLight" + LIGHT_VIS_PATH, value="inherited", prev="invisible") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "3_two_lights_off_one_light_on.png") # Enable Sphere Light # Enable Rect Light # Disable Cylinder Light omni.kit.commands.execute("ChangeProperty", prop_path="/SphereLight" + LIGHT_VIS_PATH, value="inherited", prev="invisible") omni.kit.commands.execute("ChangeProperty", prop_path="/RectLight" + LIGHT_VIS_PATH, value="inherited", prev="invisible") omni.kit.commands.execute("ChangeProperty", prop_path="/CylinderLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "4_one_light_off_two_lights_on.png")
6,132
Python
48.861788
133
0.664547
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_picking.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.usd import carb from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update class TestRtxPicking(RtxTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings and stage. await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) async def test_picking_queue(self): """ Verify picking/query requests are successfully queued """ super().add_floor() await wait_for_update() # OM-80470: Verify all picking requests requested in consecutive frames are all queued and executed successfully counter = 0 def query_complete(path, pos, *args, **kwargs): nonlocal counter counter += 1 import omni.kit.viewport viewport = omni.kit.viewport.utility.get_active_viewport() if hasattr(viewport, 'legacy_window'): return # Queue multiple query requests interrupted by a pick center = [int(v * 0.5) for v in viewport.resolution] viewport.request_query(center, query_complete, query_name="test_1") viewport.request_query(center, query_complete, query_name="test_2") viewport.request_pick(center, center, omni.usd.PickingMode.RESET_AND_SELECT) viewport.request_query(center, query_complete, query_name="test_3") viewport.request_query(center, query_complete, query_name="test_4") await wait_for_update(wait_frames=40) # All queries should complete self.assertEqual(counter, 4)
2,268
Python
39.517856
130
0.694444
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_materials.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from sys import path import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline import carb.settings from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest from .test_common import testSettings, postLoadTestSettings, wait_for_update, USD_DIR from pxr import Gf, Sdf, UsdGeom, UsdRender, UsdShade import shutil, os, pathlib class RtxHydraMaterialTest(RtxHydraTest): TEST_PATH = "hydra/materials" PRIM_PATH = "/World/box" DATA_PATH = "hydra/materials/reload" TEST_CLASS = "" # need to use the real path in order to have the filewatching work properly # -> client library ticket: https://nvidia-omniverse.atlassian.net/browse/CC-168 def getDataPath(self, relativePath) -> str: data_path : str = USD_DIR.joinpath(self.DATA_PATH, relativePath) return pathlib.Path(os.path.normpath(data_path)).resolve() # helper to override the test files # in case we want to do more or use another function def copyTestFile(self, source : str, target : str): shutil.copy(self.getDataPath(source), self.getDataPath(target)) # delete the temporary file created def cleanupTestFile(self, target : str): os.remove(self.getDataPath(target)) # basic structure of a test case init async def initTest(self, caseName: str): goldenImage = f"reload-{self.TEST_CLASS}-{caseName}.png" # compare await wait_for_update(wait_frames=10) await self.capture_and_compare(self.TEST_PATH, goldenImage) # basic structure of a test case async def changeMdlAndTest(self, caseName: str, moduleToChange: str, threshold=None): sourceFile = f"{self.TEST_CLASS}/{caseName}.mdl" targetFile = f"{self.TEST_CLASS}/{moduleToChange}.mdl" goldenImage = f"reload-{self.TEST_CLASS}-{caseName}.png" if threshold is None: threshold = self.THRESHOLD # change MDL self.copyTestFile(sourceFile, targetFile) # compare await wait_for_update(wait_frames=10) await self.capture_and_compare(self.TEST_PATH, goldenImage, threshold) class TestRtxHydraMaterialsReloadBasic(RtxHydraMaterialTest): MEDIUM_THRESHOLD = 3.0e-5 async def setUp(self): self.TEST_CLASS = "basic" await self.setUp_internal() self.set_settings(testSettings) # prepare initial MDL module self.copyTestFile("basic/A_init.mdl", "basic/A.mdl") # load the test scene scenePath = self.getDataPath("basic/XYZ.usda") print(f"Scene Path: {scenePath}") super().open_usd(scenePath) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_touch_no_change(self): """ Test hydra materials - reload basic - touch, no change """ # make sure we start with the right material await self.initTest("A_init") # touch the file by copying the same file again await self.changeMdlAndTest("A_init", "A", self.MEDIUM_THRESHOLD) # remove the temp file self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl") async def test_change_body(self): """ Test hydra materials - reload basic - change body """ # make sure we start with the right material await self.initTest("A_init") # make multiple changes in a row await self.changeMdlAndTest("A_change_body_1", "A", self.MEDIUM_THRESHOLD) await self.changeMdlAndTest("A_change_body_2", "A", self.MEDIUM_THRESHOLD) # remove the temp file self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl") class TestRtxHydraMaterialsReloadSignature(RtxHydraMaterialTest): async def setUp(self): self.TEST_CLASS = "signature" await self.setUp_internal() self.set_settings(testSettings) # prepare initial MDL module self.copyTestFile("signature/A_init.mdl", "signature/A.mdl") # load the test scene scenePath = self.getDataPath("signature/A.usda") print(f"Scene Path: {scenePath}") super().open_usd(scenePath) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_change_signature(self): """ Test hydra materials - reload signature - change signature """ # make sure we start with the right material await self.initTest("A_init") # run test cases await self.changeMdlAndTest("A_add_parameter", "A") await self.changeMdlAndTest("A_rename_parameter", "A") await self.changeMdlAndTest("A_move_parameter", "A") await self.changeMdlAndTest("A_change_parameter_default", "A") await self.changeMdlAndTest("A_change_parameter_type", "A") await self.changeMdlAndTest("A_remove_parameter", "A") # remove the temp file self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl") class TestRtxHydraMaterialsReloadGraph(RtxHydraMaterialTest): async def setUp(self): self.TEST_CLASS = "graph" await self.setUp_internal() self.set_settings(testSettings) # prepare initial MDL module self.copyTestFile("graph/A_init.mdl", "graph/A.mdl") # load the test scene scenePath = self.getDataPath("graph/GraphA.usda") print(f"Scene Path: {scenePath}") super().open_usd(scenePath) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) # Unstable via OM-53607 async def test_UNSTABLE_change_function_body_UNSTABLE(self): """ Test hydra materials - reload graph - change function body """ # make sure we start with the right material await self.initTest("A_init") # run test cases await self.changeMdlAndTest("A_change_function_body", "A") await self.changeMdlAndTest("A_change_function_param_defaults", "A") await self.changeMdlAndTest("A_add_function_param", "A") await self.changeMdlAndTest("A_move_function_param", "A") await self.changeMdlAndTest("A_remove_function_param", "A") # remove the temp file self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl") class TestRtxHydraMaterialsDebugMode(RtxHydraMaterialTest): async def setUp(self): self.TEST_CLASS = "debugMode" await self.setUp_internal() self.set_settings(testSettings) async def test_whiteMode(self): """ Test hydra materials - toggling white mode """ super().open_usd("hydra/materials/two_spheres.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_off.png", 1e-4) self.set_settings({"/rtx/debugMaterialType": 0}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_on.png", 1e-4) shader = self.ctx.get_stage().GetPrimAtPath("/World/Looks/PreviewSurface/Shader") attr = shader.GetAttribute("inputs:excludeFromWhiteMode") attr.Set(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_on_withExclude.png", 1e-4) attr.Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_on_withoutExclude.png", 1e-4) self.set_settings({"/rtx/debugMaterialType": -1}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_off_again.png", 1e-4) class TestRtxHydraMaterialStdModules(RtxHydraTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) super().open_usd("hydra/materials/stdmodules/test_std_modules.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_load_stdmodules(self): await wait_for_update(wait_frames=10) await self.capture_and_compare("hydra/materials", "stdmodules.png")
8,611
Python
37.446428
105
0.66926
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_basis_curves.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.timeline from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest from .test_common import wait_for_update, postLoadTestSettings from pxr import Sdf, Vt, UsdGeom, UsdShade simplePts = [(0, -100, 0), (50, -50, 0), (-50, 50, 0), (0, 100, 0)] simpleCnt = len(simplePts) linearPts = [(0, -100, 0), (50, 0, 0), (0, 100, 0)] linearCnt = len(linearPts) bezierPts = [(0, -100, 0), (25, -25, 0), (50, 0, 0), (0, 25, 0), (-50, 50, 0), (-25, 75, 0), (0, 100, 0)] bezierCnt = len(bezierPts) bsplinePts = [(0, -200, 0), (25, -25, 0), (-25, 0, 0), (50, 25, 0), (0, 200, 0)] bsplineCnt = len(bsplinePts) catromPts = [(0, -200, 0), (25, -50, 0), (-25, -15, 0), (-25, 15, 0), (50, 50, 0), (0, 200, 0)] catromCnt = len(catromPts) periodicPts = [(-200, -200, 0), (200, -200, 0), (200, 200, 0), (-200, 200, 0)] periodicCnt = len(periodicPts) bezierPeriodicPts = [(0, -200, 0), (-100, -200, 0), (-200, -100, 0), (-200, 0, 0), (-200, 100, 0), (-100, 200, 0), (0, 200, 0), (100, 200, 0), (200, 100, 0)] bezierPeriodicCnt = len(bezierPeriodicPts) class TestRtxHydraBasisCurves(RtxHydraTest): TEST_PATH = "hydra/basisCurves" PRIM_PATH = "/World/curve" async def setUp(self): await super().setUp() timeline = omni.timeline.get_timeline_interface() self.set_settings({"/rtx/hydra/curves/enabled": True, "/rtx/hydra/curves/splits": 1}) def _create_geometry(self, cnt, v, widthInterpolation="constant", width=None, basis="bezier", type="cubic", wrap="nonperiodic", name=PRIM_PATH): curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), name) curve.CreateCurveVertexCountsAttr(cnt) curve.CreatePointsAttr(v) curve.SetWidthsInterpolation(widthInterpolation) curve.CreateWidthsAttr(width if width else [20]) curve.CreateBasisAttr(basis) curve.CreateTypeAttr(type) curve.CreateWrapAttr(wrap) return curve async def create_geometry_and_test(self, golden, *args, **kwargs): self._create_geometry(*args, **kwargs) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, golden) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def create_geometry_and_test_primvar(self, golden, pvName, pvType, pvInterp, pvData, *args, **kwargs): self._create_geometry(*args, **kwargs) prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) attr = UsdGeom.PrimvarsAPI(prim).CreatePrimvar(pvName, pvType, pvInterp) attr.Set(pvData) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, golden) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) def create_geometry(self, name=PRIM_PATH): curve = self._create_geometry([simpleCnt], simplePts, name=name) return curve async def test_visibility(self): """ Test hydra basis curves - visibility """ await self.visibility() async def test_doNotCastShadow(self): """ Test hydra basis curves - doNotCastShadow toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "doNotCastShadows") async def test_matteObject(self): """ Test hydra basis curves - isMatteObject toggle """ self.create_geometry_with_floor() await self.matte() async def test_hideForCamera(self): """ Test hydra basis curves - hideForCamera toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "hideForCamera") async def test_transform(self): """ Test hydra basis curves - tranform """ await self.transform_all() async def test_display_color(self): """ Test hydra basis curves - change display color """ # Constant geom = self.create_geometry() geom.CreateDisplayColorPrimvar("constant").Set([(0, 1, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorConstant.png") return geom async def test_widths(self): """ Test hydra basis curves - change width """ await self.create_geometry_and_test("bezier.png", [bezierCnt], bezierPts, "constant", [20, 19]) await self.create_geometry_and_test("widthDefault.png", [bezierCnt], bezierPts, "constant", []) await self.create_geometry_and_test("widthLinear.png", [linearCnt], linearPts, "vertex", [0, 30, 0], type="linear") await self.create_geometry_and_test("widthVertex.png", [bezierCnt], bezierPts, "vertex", [0, 10, 20, 30, 20, 10, 0]) await self.create_geometry_and_test("widthBsplineVertex.png", [bsplineCnt], bsplinePts, "vertex", [0, 10, 30, 10, 0], "bspline") await self.create_geometry_and_test("widthLinear.png", [linearCnt], linearPts, "varying", [0, 30, 0], type="linear") await self.create_geometry_and_test("widthVarying.png", [bezierCnt], bezierPts, "varying", [10, 30, 50]) await self.create_geometry_and_test("widthBsplineVarying.png", [bsplineCnt], bsplinePts, "varying", [10, 30, 10], "bspline") pts2 = bezierPts + [(p[0], p[1], 50) for p in bezierPts] await self.create_geometry_and_test("widthConstant.png", [bezierCnt, bezierCnt], pts2, "constant", [30]) await self.create_geometry_and_test("widthUniform.png", [bezierCnt, bezierCnt], pts2, "uniform", [10, 30]) lPts2 = linearPts + [(p[0], p[1], 50) for p in linearPts] await self.create_geometry_and_test("widthLinear2.png", [linearCnt, linearCnt], lPts2, "varying", [10, 30, 50, 5, 35, 5], type="linear") await self.create_geometry_and_test("widthVarying2.png", [bezierCnt, bezierCnt], pts2, "varying", [10, 30, 50, 5, 35, 5]) bsPts2 = bsplinePts + [(p[0], p[1], 50) for p in bsplinePts] await self.create_geometry_and_test("widthBsplineVarying2.png", [bsplineCnt, bsplineCnt], bsPts2, "varying", [10, 30, 50, 5, 35, 5], "bspline") async def test_points(self): """ Test hydra basis curves - update points """ pts = [simplePts, simplePts.copy()] pts[1][1] = (-50, -50, 0) pts[1][2] = (50, 50, 0) await self.attribute_test_case(self.create_geometry, "points", Sdf.ValueTypeNames.Point3f, pts, ["geom.png", "points.png"]) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # TODO fix curves for delayed points assignments # curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), self.PRIM_PATH) # curve.CreateWidthsAttr([20]) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "empty.png") # curve.CreateCurveVertexCountsAttr([simpleCnt]) # curve.CreatePointsAttr(simplePts) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "empty.png") async def test_skip_processing(self): """ Test hydra basis curves - skipProcessing attribute """ geom = self.create_geometry() geom.GetPrim().CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool).Set(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "empty.png") async def test_topology_wrap(self): """ Test hydra basis curves - wrap """ # bspline: await self.create_geometry_and_test("bsplinePinned.png", [bsplineCnt], bsplinePts, "constant", [20], "bspline", "cubic", "pinned") await self.create_geometry_and_test("bsplinePinned2.png", [bsplineCnt, bsplineCnt], bsplinePts + [(p[0], p[1], 50) for p in bsplinePts], "constant", [20], "bspline", "cubic", "pinned") # catmullRom await self.create_geometry_and_test("catmullRomPinned.png", [catromCnt], catromPts, "constant", [20], "catmullRom", "cubic", "pinned") await self.create_geometry_and_test("catmullRomPinned2.png", [catromCnt, catromCnt], catromPts + [(p[0], p[1], 50) for p in catromPts], "constant", [20], "catmullRom", "cubic", "pinned") # bspline: await self.create_geometry_and_test("bsplinePeriodic.png", [periodicCnt], periodicPts, "constant", [20], "bspline", "cubic", "periodic") await self.create_geometry_and_test("bsplinePeriodic2.png", [periodicCnt, periodicCnt], periodicPts + [(p[0], p[1], 50) for p in periodicPts], "constant", [20], "bspline", "cubic", "periodic") # catmullRom await self.create_geometry_and_test("catmullRomPeriodic.png", [periodicCnt], periodicPts, "constant", [20], "catmullRom", "cubic", "periodic") await self.create_geometry_and_test("catmullRomPeriodic2.png", [periodicCnt, periodicCnt], periodicPts + [(p[0], p[1], 50) for p in periodicPts], "constant", [20], "catmullRom", "cubic", "periodic") # bezier await self.create_geometry_and_test("bezierPeriodic.png", [bezierPeriodicCnt], bezierPeriodicPts, "constant", [20], "bezier", "cubic", "periodic") # linear await self.create_geometry_and_test("linearPeriodic.png", [periodicCnt], periodicPts, type="linear", wrap="periodic") async def test_topology_basis(self): """ Test hydra basis curves - topology basis """ # linear: 2 + (n - 1) await self.create_geometry_and_test("linear.png", [linearCnt], linearPts, type="linear") await self.create_geometry_and_test("linear2.png", [linearCnt, linearCnt], linearPts + [(p[0], p[1], 50) for p in linearPts], type="linear", wrap="nonperiodic") # bezier: 4 + 3 * (n - 1) pts await self.create_geometry_and_test("bezier.png", [bezierCnt], bezierPts, "constant", [20], "bezier", "cubic", "nonperiodic") # # more points than needed, but this is ok await self.create_geometry_and_test("bezier.png", [bezierCnt], bezierPts + [(0, 0, 0)]) # # indices - ibychkov: is this supported? How it can be set? # bspline: 4 + (n - 1) pts await self.create_geometry_and_test("bspline.png", [bsplineCnt], bsplinePts, "constant", [20], "bspline", "cubic", "nonperiodic") # catmullRom await self.create_geometry_and_test("catmullRom.png", [catromCnt], catromPts, "constant", [20], "catmullRom", "cubic", "nonperiodic") # Ribbons - Not supported - OM-36882 async def test_topology_incorrect(self): """ Test hydra basis curves - incorrect topology """ efn = "empty.png" # test incorrect number of points # linear await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], type="linear") await self.create_geometry_and_test(efn, [2], [(0, -100, 0), (-100, 0, 0)], type="linear", wrap="periodic") # bezier await self.create_geometry_and_test(efn, [0], []) await self.create_geometry_and_test(efn, [4], []) await self.create_geometry_and_test(efn, [1], [(0, -100, 0), (50, -50, 0), (0, 0, 0), (-50, 50, 0), (0, 100, 0)]) await self.create_geometry_and_test(efn, [1], [(0, -100, 0)]) await self.create_geometry_and_test(efn, [2], [(0, -100, 0), (50, -50, 0)]) await self.create_geometry_and_test(efn, [3], [(0, -100, 0), (50, -50, 0), (0, 0, 0)]) await self.create_geometry_and_test(efn, [4], [(0, -100, 0)]) await self.create_geometry_and_test(efn, [5], [(0, -100, 0), (50, -50, 0), (0, 0, 0), (-50, 50, 0), (0, 100, 0), (50, 150, 0)]) await self.create_geometry_and_test(efn, [7], [(0, -100, 0), (25, -25, 0), (50, 0, 0), (0, 25, 0), (-50, 50, 0), (-25, 75, 0), (0, 100, 0)], "constant", [20], "bezier", "cubic", "periodic") await self.create_geometry_and_test(efn, [7, 7], [(0, -100, 0), (25, -25, 0), (50, 0, 0), (0, 25, 0), (-50, 50, 0), (-25, 75, 0), (0, 100, 0)]) # bspline await self.create_geometry_and_test(efn, [3], [(0, -100, 0), (50, -50, 0), (0, 0, 0)], basis="bspline") await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "bspline", "cubic", "periodic") await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "bspline", "cubic", "pinned") # catmullRom await self.create_geometry_and_test(efn, [3], [(0, -100, 0), (50, -50, 0), (0, 0, 0)], basis="catmullRom") await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "catmullRom", "cubic", "periodic") await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "catmullRom", "cubic", "pinned") # pinned wrap, bezier await self.create_geometry_and_test("empty.png", [bezierCnt], bezierPts, "constant", [20], "bezier", "cubic", "pinned") # test incorrect number of widths pts2 = bezierPts + [(p[0], p[1], 50) for p in bezierPts] await self.create_geometry_and_test(efn, [bezierCnt], bezierPts, "vertex", [0, 10, 20, 30, 20, 10]) await self.create_geometry_and_test(efn, [bezierCnt], bezierPts, "varying", [20]) await self.create_geometry_and_test(efn, [bezierCnt, bezierCnt], pts2, "uniform", [20]) # test incorrect number of display color async def test_normal_and_tangents(self): """ Test hydra basis curves - normal and tangents """ self.set_settings({"/rtx/debugView/target": "normal"}) await self.create_geometry_and_test("normalLinear.png", [linearCnt], linearPts, "constant", [40], type="linear") await self.create_geometry_and_test("normal.png", [bezierCnt], bezierPts, "constant", [40]) await self.create_geometry_and_test("normalBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline") await self.create_geometry_and_test("normalCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom") self.set_settings({"/rtx/debugView/target": "tangentu"}) await self.create_geometry_and_test("tangentuLinear.png", [linearCnt], linearPts, "constant", [40], type="linear") await self.create_geometry_and_test("tangentu.png", [bezierCnt], bezierPts, "constant", [40]) await self.create_geometry_and_test("tangentuBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline") await self.create_geometry_and_test("tangentuCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom") self.set_settings({"/rtx/debugView/target": "tangentv"}) await self.create_geometry_and_test("tangentvLinear.png", [linearCnt], linearPts, "constant", [40], type="linear") await self.create_geometry_and_test("tangentv.png", [bezierCnt], bezierPts, "constant", [40]) await self.create_geometry_and_test("tangentvBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline") await self.create_geometry_and_test("tangentvCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom") async def test_texCoords(self): """ Test hydra basis curves - texCoords (UVs) """ self.set_settings({"/rtx/debugView/target": "texcoord0"}) await self.create_geometry_and_test("texCoordsLinear.png", [linearCnt], linearPts, "vertex", [10, 30, 50], type="linear") await self.create_geometry_and_test("texCoords.png", [bezierCnt], bezierPts, "varying", [10, 30, 50]) await self.create_geometry_and_test("texCoordsBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline") await self.create_geometry_and_test("texCoordsCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom") async def test_texCoords2(self): """ Test hydra basis curves - texCoords (UVs) set 2. Defined by asset. """ self.set_settings({"/rtx/debugView/target": "texcoord1"}) await self.create_geometry_and_test_primvar("texCoords2Vertex.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex, [(0, 0), (0.15, 0), (0.3, 0), (0.5, 0), (0.7, 0), (0.85, 0), (1, 0)], [bezierCnt], bezierPts, "varying", [10, 30, 50]) await self.create_geometry_and_test_primvar("texCoords2Uniform.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.uniform, [(0, 0.5), (1, 0)], [bezierCnt, bezierCnt], bezierPts + [(p[0], p[1], 50) for p in bezierPts]) # Pinned wrap await self.create_geometry_and_test_primvar("texCoords2VertexPinned.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex, [(0, 0), (0.3, 0), (0.5, 0), (0.7, 0), (1, 0)], [bsplineCnt], bsplinePts, "constant", [30], "bspline", "cubic", "pinned") await self.create_geometry_and_test_primvar("texCoords2UniformPinned.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.uniform, [(0, 0.5), (1, 0)], [bsplineCnt, bsplineCnt], bsplinePts + [(p[0], p[1], 50) for p in bsplinePts], "constant", [20], "bspline", "cubic", "pinned") # Peropdic wrap await self.create_geometry_and_test_primvar("texCoords2VertexPeriodic.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex, [(0, 0), (0.3, 0), (0.5, 0), (1, 0)], [periodicCnt], periodicPts, "constant", [30], "bspline", "cubic", "periodic") await self.create_geometry_and_test_primvar("texCoords2UniformPeriodic.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.uniform, [(0, 0.5), (1, 0)], [periodicCnt, periodicCnt], periodicPts + [(p[0], p[1], 50) for p in periodicPts], "constant", [20], "bspline", "cubic", "periodic") async def test_endcaps(self): """ Test hydra basis curves - endcaps. For cubic curves - flat and open For linear curves - only round """ self._create_geometry([bezierCnt], bezierPts, "varying", [30, 30, 50]) prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) pv = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("endcaps", Sdf.ValueTypeNames.Int) # Flat pv.Set(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "endcapFlat.png") # Open pv.Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "endcapOpen.png") # OM-55978: Discontinuity along curves or hair fibers when the endcaps option set to open self.set_camera((1.25, 1.25, 1.25), (0, 0, 0)) self.set_settings({"/rtx/debugView/target": "normal"}) self._create_geometry([4], [(0, -10, 0), (0, 0, 0), (0, 10, 0), (0, 20, 0)], "constant", [1], "bspline", "cubic", "pinned") prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) pv = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("endcaps", Sdf.ValueTypeNames.Int) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "om55978.png") async def test_numsplits(self): """ Test hydra basis curves - numSplits. For cubic curves only """ self.set_settings({"/rtx/wireframe/enabled": True}) self.set_settings({"/rtx/wireframe/wireframeThickness": 5}) self.set_settings({"/rtx/wireframe/mode": 2}) # Global setting self._create_geometry([bezierCnt], bezierPts, "constant", [20]) self.set_settings({"/rtx/hydra/curves/splits": 4}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bezier4Splits.png") # Update global setting self.set_settings({"/rtx/hydra/curves/splits": 1}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bezier1Splits.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Primvar with overrided self._create_geometry([bezierCnt], bezierPts, "constant", [20]) prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplitsOverride", Sdf.ValueTypeNames.Bool).Set(True) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplits", Sdf.ValueTypeNames.Int).Set(2) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bezier2Splits.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Primvar without override (it should get num splits from global setting == 1) self._create_geometry([bezierCnt], bezierPts, "constant", [20]) prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplits", Sdf.ValueTypeNames.Int).Set(2) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bezier1Splits.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Bspline self._create_geometry([bsplineCnt], bsplinePts, "constant", [20], "bspline") prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplits", Sdf.ValueTypeNames.Int).Set(2) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplitsOverride", Sdf.ValueTypeNames.Bool).Set(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bspline2Splits.png") async def test_timeSampled(self): """ Test hydra basis curves - verify time sample animation works. """ super().open_usd("hydra/curves_timeSampled_001.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) timeline = omni.timeline.get_timeline_interface() # Regression test for OM-96462, where time-sampled xform was impairing update of time-sampled points await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "curves_timeSampled_frame0.png") # Advance a few frames and capture another frame for t in range(12): timeline.forward_one_frame() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "curves_timeSampled_frame12.png") class TestRtxHydraBasisCurvesInstancer(RtxHydraInstancerTest): # TODO full cover scene instancer with tests TEST_PATH = "hydra/basisCurves/instancer" GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/curve" def create_geometry(self, name=GEOM_PATH): curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), name) curve.CreateCurveVertexCountsAttr([simpleCnt]) curve.CreatePointsAttr(simplePts) curve.CreateWidthsAttr([0, 20, 20, 0]) return curve async def test_sceneInstancer(self): """ Test hydra basis curves - scene instancer """ await self.si_all() async def test_pointInstancer(self): """ Test hydra basis curves - point instancer """ await self.pi_all() class TestRtxHydraBasisCurvesMaterials(RtxHydraMaterialsTest): TEST_PATH = "hydra/basisCurves/material" PRIM_PATH = "/World/curve" def create_geometry(self, name=PRIM_PATH): curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), name) curve.CreateCurveVertexCountsAttr([simpleCnt]) curve.CreatePointsAttr(simplePts) curve.CreateWidthsAttr([10, 30, 30, 10]) return curve # Unstable via OM-53604 async def test_UNSTABLE_materials_UNSTABLE(self): """ Test hydra basis curves - materials """ materials = ["Green", "Red"] looksPath = "/World/Looks/" # Set and change material geomPrim = self.create_geometry().GetPrim() for m in materials: self.bind_material(geomPrim, looksPath + m) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_{}.png".format(m)) # Unbind material it should fallback to basic material UsdShade.MaterialBindingAPI(geomPrim).UnbindAllBindings() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_base.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
24,695
Python
50.665272
197
0.626443
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_common.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline from .test_common import RtxTest, testSettings, postLoadTestSettings, set_transform_helper, wait_for_update from pxr import Sdf, Gf, UsdGeom, UsdShade class RtxHydraTest(RtxTest): """ Base class for hydra tests """ # override resolution WINDOW_SIZE = (512, 512) TEST_PATH = "hydra" PRIM_PATH = "" async def setUp(self): await self.setUp_internal() self.set_settings(testSettings) omni.usd.get_context().new_stage() self.add_dir_light() await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) def create_geometry(self, name=PRIM_PATH): pass def create_geometry_with_floor(self): self.add_floor() self.create_geometry() set_transform_helper(self.PRIM_PATH, translate=Gf.Vec3d(0, 100, 0)) async def geometry_with_attribute(self, attrName, attrType, attrVal, shouldWait=False): geom = self.create_geometry() if shouldWait: await wait_for_update() attr = geom.GetPrim().CreateAttribute(attrName, attrType) self.assertTrue(attr) attr.Set(attrVal) await wait_for_update() return geom async def set_attribute_timesampled(self, geom, attrName, attrType, attrVals, goldens): attr = geom.GetPrim().CreateAttribute(attrName, attrType) self.assertTrue(attr) for i, v in enumerate(attrVals): attr.Set(v, i) self.assertTrue(len(attrVals) == len(goldens)) timeline = omni.timeline.get_timeline_interface() timeline.set_target_framerate(timeline.get_time_codes_per_seconds()) timeline.play() timeline.set_auto_update(False) for i, g in enumerate(goldens): timeline.set_current_time(i) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, g) timeline.set_auto_update(True) timeline.stop() async def attribute_test_case(self, createGeom, attrName, attrType, attrVals, goldens): self.assertTrue(len(attrVals) > 1) self.assertTrue(len(attrVals) == len(goldens)) geom = createGeom() attr = geom.GetPrim().CreateAttribute(attrName, attrType) self.assertTrue(attr) # Test updating attribute for i, g in enumerate(goldens): attr.Set(attrVals[i]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, g) # Test timesampled attribute self.ctx.get_stage().RemovePrim(self.PRIM_PATH) geom = createGeom() await self.set_attribute_timesampled(geom, attrName, attrType, attrVals, goldens) async def toggle_primvar(self, geomPath, primvarName, primvarType=Sdf.ValueTypeNames.Bool, primvarVal=True, baseGoldenName="boxAndFloor.png", threshould=1e-5): prim = self.ctx.get_stage().GetPrimAtPath(geomPath) attr = UsdGeom.PrimvarsAPI(prim).CreatePrimvar(primvarName, primvarType) self.assertTrue(attr) await wait_for_update() self.assertFalse(attr.Get() == primvarVal) await self.capture_and_compare(self.TEST_PATH, baseGoldenName) attr.Set(primvarVal) await wait_for_update() self.assertTrue(attr.Get() == primvarVal) await self.capture_and_compare(self.TEST_PATH, primvarName + ".png", threshould) async def visibility(self): prim = self.create_geometry() attr = prim.GetVisibilityAttr() self.assertTrue(attr) for i in range(2): attr.Set(UsdGeom.Tokens.inherited) await wait_for_update() self.assertTrue(attr.Get() == UsdGeom.Tokens.inherited) await self.capture_and_compare(self.TEST_PATH, "geom.png") attr.Set(UsdGeom.Tokens.invisible) await wait_for_update() self.assertTrue(attr.Get() == UsdGeom.Tokens.invisible) await self.capture_and_compare(self.TEST_PATH, "empty.png") async def cull_style(self): # Not yet supported by hydra pass async def double_sided(self): pass async def single_sided(self): self.set_settings({"/rtx/debugView/target": "normal", "/rtx/hydra/faceCulling/enabled": True}) geom = self.create_geometry() attr = geom.GetPrim().CreateAttribute("singleSided", Sdf.ValueTypeNames.Bool) self.assertTrue(attr) self.set_camera(cameraPos=(0, 0, 0), targetPos=(-500, -500, -500)) await wait_for_update() self.assertFalse(attr.Get()) await self.capture_and_compare(self.TEST_PATH, "doubleSided.png") attr.Set(True) await wait_for_update() self.assertTrue(attr.Get()) await self.capture_and_compare(self.TEST_PATH, "singleSided.png") async def matte(self): self.set_settings({"/rtx/matteObject/enabled": True, "/rtx/post/backgroundZeroAlpha/enabled": True, "/rtx/post/backgroundZeroAlpha/backgroundComposite": True, "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor": (0, 0, 0)}) await self.toggle_primvar("/World/Floor", "isMatteObject") async def is_picked(self): # This is not worked when kit is not focused. Skip tests while solution wouldn't be found self.skipTest("Test is not worked correctly yet!") #viewport = omni.kit.viewport_legacy.acquire_viewport_interface().get_viewport_window(None) #isPicked = False # for i in range(10): # set_cursor_position((int(self.WINDOW_SIZE[0] / 2), int(self.WINDOW_SIZE[1] / 2))) # await omni.kit.app.get_app().next_update_async() # ret = viewport.get_hovered_world_position() # isPicked |= ret[0] #return isPicked async def pickable(self): geom = self.create_geometry() self.assertTrue(await self.is_picked()) self.ctx.set_pickable(self.PRIM_PATH, False) # set_pickable is not catched correctly by hydra yet. So we need to update any primvar to force update instance attr = geom.GetPrim().CreateAttribute("singleSided", Sdf.ValueTypeNames.Bool) attr.Set(True) await wait_for_update() self.assertFalse(await self.is_picked()) async def transform_translate(self): self.create_geometry() set_transform_helper(self.PRIM_PATH, translate=Gf.Vec3d(0, 0, 150)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "translateZ.png") async def transform_rotate(self): self.create_geometry() set_transform_helper(self.PRIM_PATH, euler=Gf.Vec3d(0, 45, 0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "rotateY.png") async def transform_scale(self): self.create_geometry() set_transform_helper(self.PRIM_PATH, scale=Gf.Vec3d(2, 1, 1)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "scaleX.png") async def transform_combined(self, shouldWait=False): self.create_geometry() if shouldWait: await wait_for_update() set_transform_helper(self.PRIM_PATH, translate=Gf.Vec3d(0, 0, 150), euler=Gf.Vec3d(0, 45, 0), scale=Gf.Vec3d(2, 1, 1)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tranlateZrotateYscaleX.png") async def transform_all(self): await self.transform_translate() self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await self.transform_rotate() self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await self.transform_scale() self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await self.transform_combined(shouldWait=True) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await wait_for_update() await self.transform_combined(shouldWait=False) class RtxHydraMaterialsTest(RtxHydraTest): TEST_PATH = "" PRIM_PATH = "" async def setUp(self): await self.setUp_internal() self.set_settings(testSettings) super().open_usd("hydra/UsdShade.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) def create_geometry(self, name): pass def bind_material(self, geom, material_path): binding_api = UsdShade.MaterialBindingAPI(geom) material_prim = self.ctx.get_stage().GetPrimAtPath(material_path) material = UsdShade.Material(material_prim) binding_api.Bind(material, UsdShade.Tokens.weakerThanDescendants) class RtxHydraInstancerTest(RtxHydraTest): # TODO full cover scene instancer with tests TEST_PATH = "" GEOM_PATH = "" PRIM_PATH = "/World/instance" PRIM1_PATH = "/World/instance1" PRIM2_PATH = "/World/instance2" def create_geometry(self, name): pass def create_scene_instancer(self): prim = UsdGeom.Xform.Define(self.ctx.get_stage(), self.PRIM_PATH).GetPrim() self.create_geometry(self.GEOM_PATH) prim1 = UsdGeom.Xform.Define(self.ctx.get_stage(), self.PRIM1_PATH).GetPrim() prim1.GetReferences().AddInternalReference(self.PRIM_PATH) prim1.SetInstanceable(True) omni.kit.commands.execute("CopyPrimCommand", path_from=self.PRIM1_PATH, path_to=self.PRIM2_PATH) self.ctx.get_selection().clear_selected_prim_paths() prim2 = self.ctx.get_stage().GetPrimAtPath(self.PRIM2_PATH) set_transform_helper(self.PRIM2_PATH, translate=Gf.Vec3d(0, 200, 0)) return prim, prim2 def remove_scene_instancer(self): # Teardown in reverse order of creation, to avoid temporarily leaving dangling references. # Alternatively, we could implement this in Sdf with a change block to batch all the removals. self.ctx.get_stage().RemovePrim(self.PRIM2_PATH) self.ctx.get_stage().RemovePrim(self.PRIM1_PATH) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) self.ctx.get_stage().RemovePrim(self.GEOM_PATH) def create_point_instancer(self): instancer = UsdGeom.PointInstancer.Define(self.ctx.get_stage(), self.PRIM_PATH) instancer.CreatePositionsAttr([(-150, 0, 0), (150, 0, 0)]) instancer.CreateProtoIndicesAttr([0, 0]) self.create_geometry(self.GEOM_PATH) attr = instancer.CreatePrototypesRel() attr.AddTarget(self.GEOM_PATH) return instancer def remove_point_instancer(self): self.ctx.get_stage().RemovePrim(self.GEOM_PATH) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def si_create(self): self.create_scene_instancer() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "sceneinstancer.png", 1e-4) async def si_rotate(self): self.create_scene_instancer() set_transform_helper(self.GEOM_PATH, euler=Gf.Vec3d(0, 0, 45)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "si_rotate_mesh.png", 1e-4) async def si_all(self): await self.si_create() self.remove_scene_instancer() await self.si_rotate() self.remove_scene_instancer() async def pi_create(self): self.create_point_instancer() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pointinstancer.png", 1e-4) async def pi_protoIndices(self): instancer = self.create_point_instancer() sphere = UsdGeom.Sphere.Define(self.ctx.get_stage(), self.PRIM_PATH + "/sphere") sphere.CreateRadiusAttr(50) instancer.GetPrototypesRel().AddTarget(self.PRIM_PATH + "/sphere") instancer.GetProtoIndicesAttr().Set([1, 0]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_2meshes.png", 1e-4) # Regression test for OM-32503 instancer.GetProtoIndicesAttr().Set([1, 0, 1]) instancer.GetPositionsAttr().Set([(-150, 0, 0), (0, 0, 0), (150, 0, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_3meshes.png", 1e-4) async def pi_invisibleIds(self): instancer = self.create_point_instancer() attr = instancer.CreateInvisibleIdsAttr() attr.Set([0]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_invisibleIds.png", 1e-4) attr.Set([]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pointinstancer.png", 1e-4) async def pi_orientations(self): instancer = self.create_point_instancer() attr = instancer.CreateOrientationsAttr() attr.Set([Gf.Quath(0., 0., 0.5, 1), Gf.Quath(0., 0.5, 0., 1)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_orientations.png", 1e-4) async def pi_scales(self): instancer = self.create_point_instancer() attr = instancer.CreateScalesAttr() attr.Set([(1., 2., 1), (1., 1., 2)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_scales.png", 1e-4) # OM-30814 - verify proper refresh when authoring xforms on prototype gprims and ancestors async def pi_protoXform(self): instancer = self.create_point_instancer() await wait_for_update() # TODO: Figure out why the bug does not repro via scripting, only via TransformGizmo; # even scripting the entire operation within an Sdf.ChangeBlock does not trigger the # bug, with the fixes reverted. set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(2, 1, 2)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_protoXform.png", 1e-4) set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(1, 1, 1)) await wait_for_update() geomPath = Sdf.Path(self.GEOM_PATH) xformPath = geomPath.GetParentPath().AppendChild('Xform') UsdGeom.Xform.Define(self.ctx.get_stage(), xformPath) newGeomPath = xformPath.AppendChild(geomPath.name) omni.kit.commands.execute("MovePrimCommand", path_from=self.GEOM_PATH, path_to=newGeomPath) instancer.GetPrototypesRel().ClearTargets(removeSpec=True) instancer.GetPrototypesRel().AddTarget(xformPath) await wait_for_update() set_transform_helper(xformPath, scale=Gf.Vec3d(1, 2, 1)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_ancestralProtoXform.png", 1e-4) omni.kit.commands.execute("MovePrimCommand", path_from=newGeomPath, path_to=self.GEOM_PATH) instancer.GetPrototypesRel().ClearTargets(removeSpec=True) instancer.GetPrototypesRel().AddTarget(geomPath) self.ctx.get_stage().RemovePrim(xformPath) # OM-81682 - verify the prototype transform does not include the transform above the prototype root set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(1, 1, 1)) await wait_for_update() parentXformPath = geomPath.GetParentPath().AppendChild('Parent') UsdGeom.Xform.Define(self.ctx.get_stage(), parentXformPath) newXformPath = parentXformPath.AppendChild('Xform') UsdGeom.Xform.Define(self.ctx.get_stage(), newXformPath) newGeomPath = newXformPath.AppendChild(geomPath.name) omni.kit.commands.execute("MovePrimCommand", path_from=self.GEOM_PATH, path_to=newGeomPath) set_transform_helper(newXformPath, scale=Gf.Vec3d(1, 2, 1)) set_transform_helper(parentXformPath, scale=Gf.Vec3d(2, 2, 2)) instancer.GetPrototypesRel().ClearTargets(removeSpec=True) instancer.GetPrototypesRel().AddTarget(newXformPath) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_ancestralProtoXform.png") omni.kit.commands.execute("MovePrimCommand", path_from=newGeomPath, path_to=self.GEOM_PATH) self.ctx.get_stage().RemovePrim(parentXformPath) set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(2, 1, 2)) instancer.GetPrototypesRel().ClearTargets(removeSpec=True) instancer.GetPrototypesRel().AddTarget(self.GEOM_PATH) async def pi_all(self): await self.pi_create() self.remove_point_instancer() await self.pi_protoIndices() self.remove_point_instancer() await self.pi_invisibleIds() self.remove_point_instancer() # Transforms await self.pi_orientations() self.remove_point_instancer() await self.pi_scales() self.remove_point_instancer() self.create_point_instancer() await self.transform_translate() self.remove_point_instancer() self.create_point_instancer() await self.transform_rotate() self.remove_point_instancer() self.create_point_instancer() await self.transform_scale() self.remove_point_instancer() await self.pi_protoXform() self.remove_point_instancer()
17,803
Python
41.901205
119
0.652587
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_points.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.timeline from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest from .test_common import wait_for_update, postLoadTestSettings from pxr import Sdf, UsdGeom, UsdShade DEFAULT_POINTS = [(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)] class TestRtxHydraPoints(RtxHydraTest): TEST_PATH = "hydra/points" PRIM_PATH = "/World/pts" async def display_color(self): # Constant geom = self.create_geometry() geom.CreateDisplayColorPrimvar("constant").Set([(0, 1, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorConstant.png") return geom async def widths(self): # Default geom = self.create_geometry() geom.GetWidthsAttr().Clear() self.set_settings({"/persistent/rtx/hydra/points/defaultWidth": 35}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "widthDefault.png") self.set_settings({"/persistent/rtx/hydra/points/defaultWidth": 45}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "widthDefault2.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Constant geom = self.create_geometry() geom.SetWidthsInterpolation("constant") geom.CreateWidthsAttr().Set([20]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "widthConstant.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Vertex geom = self.create_geometry() geom.CreateWidthsAttr().Set([20, 15, 10, 25, 30, 35, 40, 45]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "widthVertex.png") async def points(self): pts = [DEFAULT_POINTS, [(-50, -50, -50), (150, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]] await self.attribute_test_case(self.create_geometry, "points", Sdf.ValueTypeNames.Point3f, pts, ["geom.png", "points.png"]) async def skipProcessing(self): geom = self.create_geometry() geom.GetPrim().CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool).Set(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "empty.png") class TestRtxHydraPrimitiveDrawingPoints(TestRtxHydraPoints): TEST_PATH = "hydra/points/primitivedrawing" PRIM_PATH = "/World/pts" def create_geometry(self, name=PRIM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr(DEFAULT_POINTS) pts.CreateWidthsAttr([10, 10, 10, 10, 5, 5, 15, 15]) UsdGeom.PrimvarsAPI(pts).CreatePrimvar("usePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True) UsdGeom.PrimvarsAPI(pts).CreatePrimvar("screenSpacePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True) return pts async def test_visibility(self): """ Test hydra points - visibility """ await self.visibility() async def test_transform(self): """ Test hydra points - tranform """ await self.transform_all() async def test_displayColor(self): """ Test hydra points - change display color """ geom = await self.display_color() # Vertex geom.CreateDisplayColorPrimvar("vertex").Set([(0, 1, 0), (1, 1, 0), (0, 1, 1), (1, 0, 1), (1, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorVertex.png") async def test_widths(self): """ Test hydra points - change widths """ await self.widths() async def test_points(self): """ Test hydra points - update points """ await self.points() async def test_skipProcessing(self): """ Test hydra points - skipProcessing attribute """ await self.skipProcessing() class TestRtxHydraPrimitiveDrawingPointsInstancer(RtxHydraInstancerTest): # TODO full cover scene instancer with tests TEST_PATH = "hydra/points/primitivedrawing/instancer" GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/pts" def create_geometry(self, name=GEOM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr(DEFAULT_POINTS) pts.CreateWidthsAttr([10, 10, 10, 10, 5, 5, 15, 15]) UsdGeom.PrimvarsAPI(pts).CreatePrimvar("usePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True) UsdGeom.PrimvarsAPI(pts).CreatePrimvar("screenSpacePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True) return pts async def test_sceneInstancer(self): """ Test hydra points scene instancer """ await self.si_all() async def test_pointInstancer(self): """ Test hydra points point instancer """ await self.pi_all() class UNSTABLE_TestRtxHydraProceduralPoints_UNSTABLE(TestRtxHydraPoints): TEST_PATH = "hydra/points/procedural" PRIM_PATH = "/World/pts" def create_geometry(self, name=PRIM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr(DEFAULT_POINTS) pts.CreateWidthsAttr([40, 30, 30, 20, 15, 15, 35, 35]) return pts async def test_visibility(self): """ Test hydra points - visibility """ await self.visibility() async def test_doNotCastShadow(self): """ Test hydra points - doNotCastShadow toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "doNotCastShadows") async def test_matteObject(self): """ Test hydra points - isMatteObject toggle """ self.create_geometry_with_floor() await self.matte() async def test_hideForCamera(self): """ Test hydra points - hideForCamera toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "hideForCamera") async def test_transform(self): """ Test hydra points - tranform """ await self.transform_all() async def test_displayColor(self): """ Test hydra points - change display color """ await self.display_color() async def test_widths(self): """ Test hydra points - change widths """ await self.widths() async def test_points(self): """ Test hydra points - update points """ await self.points() self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # OM-45604, OM-43655 # Delayed points assignment geom = UsdGeom.Points.Define(self.ctx.get_stage(), self.PRIM_PATH) geom.CreateWidthsAttr([40, 30, 30, 20, 15, 15, 35, 35]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "empty.png", 1e-4) attr = geom.CreatePointsAttr(DEFAULT_POINTS) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "geom.png", 1e-4) # OM-43655 - remove point attr.Set(DEFAULT_POINTS[:-1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pointsRemovedOne.png", 1e-4) async def test_skip_processing(self): """ Test hydra points - skipProcessing attribute """ await self.skipProcessing() async def test_texCoords(self): self.set_settings({"/rtx/debugView/target": "texcoord1"}) self.create_geometry() prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) attr = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex) uvVertexSet = [(1, 0), (0.15, 0.5), (0.3, 0.5), (0.5, 0.5), (0.7, 0.5), (0.85, 0.5), (1, 0.5), (1, 1)] attr.Set(uvVertexSet) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "texCoords.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def test_timeSampled(self): """ Test hydra points - verify time sample animation works. """ super().open_usd("hydra/points_timeSampled_001.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) timeline = omni.timeline.get_timeline_interface() # Regression test for OM-96462, where time-sampled xform was impairing update of time-sampled points await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "points_timeSampled_frame0.png") # Advance a few frames and capture another frame for t in range(12): timeline.forward_one_frame() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "points_timeSampled_frame12.png") class UNSTABLE_TestRtxHydraProceduralPointsInstancer_UNSTABLE(RtxHydraInstancerTest): # TODO full cover scene instancer with tests TEST_PATH = "hydra/points/procedural/instancer" GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/pts" def create_geometry(self, name=GEOM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr(DEFAULT_POINTS) pts.CreateWidthsAttr([40, 30, 30, 20, 15, 15, 35, 35]) return pts async def test_sceneInstancer(self): """ Test hydra points - scene instancer """ await self.si_all() async def test_pointInstancer(self): """ Test hydra points - point instancer """ await self.pi_all() class UNSTABLE_TestRtxHydraProceduralPointsMaterials_UNSTABLE(RtxHydraMaterialsTest): TEST_PATH = "hydra/points/procedural/material" PRIM_PATH = "/World/pts" def create_geometry(self, name=PRIM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr([(-50, 0, 0), (50, 0, 0)]) pts.CreateWidthsAttr([50, 25]) return pts async def test_materials(self): """ Test hydra points - materials """ materials = ["Green", "Red"] looksPath = "/World/Looks/" # Set and change material geomPrim = self.create_geometry().GetPrim() for m in materials: self.bind_material(geomPrim, looksPath + m) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_{}.png".format(m)) # Unbind material it should fallback to basic material UsdShade.MaterialBindingAPI(geomPrim).UnbindAllBindings() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_base.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
11,487
Python
35.820513
142
0.630278
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_volume.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_hydra_common import RtxHydraTest from .test_common import set_transform_helper, wait_for_update from pxr import Gf, UsdVol class TestRtxHydraVolume(RtxHydraTest): TEST_PATH = "hydra/volume" PRIM_PATH = "/World/volume" def create_geometry(self, name=PRIM_PATH): open_vdb_asset = UsdVol.OpenVDBAsset.Define(self.ctx.get_stage(), name + "/OpenVDBAsset") open_vdb_asset.GetFilePathAttr().Set(self.get_volumes_path("sphere.vdb")) open_vdb_asset.GetFieldNameAttr().Set("density") volume = UsdVol.Volume.Define(self.ctx.get_stage(), name) volume.CreateFieldRelationship("density", open_vdb_asset.GetPath()) set_transform_helper(volume.GetPath(), translate=Gf.Vec3d(0, 150, 0), scale=Gf.Vec3d(20.0, 20.0, 20.0)) return volume # simple test, create a volume with a OpenVDB asset # Unstable via OM-54845 async def test_UNSTABLE_create_UNSTABLE(self): self.add_floor() self.create_geometry() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "create_sphere.png", threshold=1e-3) # test changing the OpenVDBAsset file path # Unstable via OM-54845 async def test_UNSTABLE_change_to_torus_UNSTABLE(self): self.add_floor() self.create_geometry() open_vdb_asset = UsdVol.OpenVDBAsset(self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH + "/OpenVDBAsset")) open_vdb_asset.GetFilePathAttr().Set(self.get_volumes_path("torus.vdb")) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "change_to_torus.png", threshold=1e-3)
2,088
Python
44.413043
114
0.70977
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_example.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom class TestRtxExample1(RtxTest): """ Example of rtx test which creates box and capture screenshot Hints: for python debug insert line below and attach to kit process in VS Code omni.kit.debug.python.breakpoint() """ # override resolution WINDOW_SIZE = (512, 512) async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings and stage. self.add_dir_light() await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) def create_mesh(self): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), "/World/box") box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box # Unstable via OM-58681 async def test_UNSTABLE_rtx_example_create_mesh_UNSTABLE(self): """ Test example - create mesh """ self.create_mesh() await wait_for_update() await self.capture_and_compare("example", "mesh.png") async def test_rtx_example_check_mesh(self): """ Test example - check mesh """ box = self.create_mesh() points = box.GetPointsAttr().Get() face_indices = box.GetFaceVertexIndicesAttr().Get() unique_indices = set(face_indices) self.assertTrue(len(points) == len(unique_indices)) class TestRtxExample2(RtxTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) self.open_usd("bunny.obj.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) self.set_camera((6.969233739993722, 6.969233739993723, 6.969233739993719), (0, 0, 0)) async def test_UNSTABLE_rtx_example_open_usd_UNSTABLE(self): """ Test example - open usd file """ await wait_for_update() await self.capture_and_compare("example", "usd.png", 1e-4)
3,058
Python
37.721519
130
0.642904
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_usdlux_schema_compat.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom, UsdLux class TestUsdLuxSchemaCompat(RtxTest): TEST_PATH = "hydra/usdlux" async def test_usdlux_inputs_prefix(self): """ Test that the compatibility workaround for UsdLux schema changes that requires an inputs: prefix on attributes works. """ test_file_path = "hydra/simpleSphereLightUnprefixed.usda" super().open_usd(test_file_path) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "lightAttributes.png") async def test_usdlux_light_with_both_attributes(self): """ Test that the delegate chooses inputs: attributes when both inputs and non-inputs are authored. The usda for this test has these properties defined: float inputs:intensity = 30000 float intensity = 90000000 """ test_file_path = "hydra/simpleSphereLightBothAttributes.usda" super().open_usd(test_file_path) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "lightAttributes.png")
1,633
Python
44.388888
125
0.71831
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_mesh.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline import carb.settings from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest from .test_common import postLoadTestSettings, set_transform_helper, wait_for_update from pxr import Vt, Gf, Sdf, UsdGeom, UsdShade cubePts = [(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)] cubeFaceVCount = [4, 4, 4, 4, 4, 4] cubeIndices = [0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5] class TestRtxHydraMesh(RtxHydraTest): TEST_PATH = "hydra/mesh" PRIM_PATH = "/World/box" async def setUp(self): await super().setUp() timeline = omni.timeline.get_timeline_interface() timeline.set_target_framerate(timeline.get_time_codes_per_seconds()) def create_geometry(self, name=PRIM_PATH): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) box.CreatePointsAttr(cubePts) box.CreateFaceVertexCountsAttr(cubeFaceVCount) box.CreateFaceVertexIndicesAttr(cubeIndices) box.CreateSubdivisionSchemeAttr("none") return box # # Common tests for mesh # async def test_visibility(self): """ Test hydra mesh - visibility """ await self.visibility() # OM-34158 # Verify proper refresh when points are moved while the mesh is invisible. prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) mesh = UsdGeom.Mesh(prim) points = mesh.GetPointsAttr().Get() for idx, p in enumerate(points): points[idx] = p + Gf.Vec3f(100, 0, 0) mesh.GetPointsAttr().Set(points) await wait_for_update() mesh.GetVisibilityAttr().Set(UsdGeom.Tokens.inherited) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "boxPtsMovedWhileInvisible.png") async def test_doNotCastShadow(self): """ Test hydra mesh - doNotCastShadow toggle """ self.create_geometry_with_floor() # OM-58993: Properly cast shadows. await self.toggle_primvar(self.PRIM_PATH, "doNotCastShadows") # TODO setup scene which shows the difference # async def test_shadowTerminatorFix(self): # """ # Test hydra mesh - enableShadowTerminatorFix toggle # """ # self.create_geometry_with_floor() # await self.toggle_primvar(self.PRIM_PATH, "enableShadowTerminatorFix") async def test_matteObject(self): """ Test hydra mesh - isMatteObject toggle """ self.create_geometry_with_floor() await self.matte() async def test_hideForCamera(self): """ Test hydra mesh - hideForCamera toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "hideForCamera") async def test_wireframe(self): """ Test hydra mesh - wireframe toggle """ self.create_geometry() self.set_settings({"/rtx/wireframe/wireframeThickness": 10}) await self.toggle_primvar(self.PRIM_PATH, "wireframe", baseGoldenName="geom.png", threshould=1e-7) async def test_singleSided(self): """ Test hydra mesh - singleSided toggle """ await self.single_sided() async def test_pickable(self): """ Test hydra mesh - pickable flag toggle """ await self.pickable() # OM-3262 Verify proper refresh when authoring purpose async def test_purpose(self): """ Test hydra mesh - purpose toggle """ self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False}) self.create_geometry() geom = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) UsdGeom.Imageable(geom).CreatePurposeAttr().Set(UsdGeom.Tokens.guide) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "purpose.png") # OM-62070 # Verify mesh visibility updates when changing global setting self.set_settings({'/persistent/app/hydra/displayPurpose/guide': True}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "guideVisEnable.png") self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "guideVisDisable.png") # Verify inherited purpose authoring self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False}) super().open_usd("hydra/inheritedPurpose.usda") scope = self.ctx.get_stage().GetPrimAtPath('/World/Scope') UsdGeom.Imageable(scope).CreatePurposeAttr().Set(UsdGeom.Tokens.guide) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "inheritedGuidePurpose.png") UsdGeom.Imageable(scope).GetPurposeAttr().Clear() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "inheritedDefaultPurpose.png", 5e-5) # OM-32623 # Verify proper population of new repr when toggling saved guide purpose to default. self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False}) super().open_usd("hydra/guideRepr.usda") geom = self.ctx.get_stage().GetPrimAtPath('/World/Cube') UsdGeom.Imageable(geom).GetPurposeAttr().Clear() await wait_for_update() # Allow for a bit of noise between local run and TC await self.capture_and_compare(self.TEST_PATH, "guideRepr.png", 1e-4) async def test_transform(self): """ Test hydra mesh - tranform """ await self.transform_all() # OM-26055 # Verify that fallback xform values are properly initialized. super().open_usd("hydra/OM-26055_scene.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "OM-26055_scene.png") # OM-34447 # Verify that xforms properly resync when initially present with no value. super().open_usd("hydra/empty_xform_mtx.usda") stage = self.ctx.get_stage() set_transform_helper("/World/Mesh", translate=Gf.Vec3d(200, 0, 0)) await wait_for_update() # Looser threshold, as the test is somewhat noisy on Linux TC await self.capture_and_compare(self.TEST_PATH, "resync-empty_xform_mtx.png", 1e-4) # Verify that ancestral xforms properly affect invisible geometry. super().open_usd("hydra/simpleCubeAncestralXforms.usda") stage = self.ctx.get_stage() await wait_for_update() intermediateXform = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Xform/Xform_01")) intermediateXform.MakeVisible(False) await wait_for_update() ancestralXform = UsdGeom.XformCommonAPI(stage.GetPrimAtPath("/World/Xform")) ancestralXform.SetTranslate((100,0,0)) await wait_for_update() intermediateXform.MakeVisible(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "postVisAncestralXform.png") async def test_backfaceCulling(self): """ Test hydra mesh - verify toggling of backface culling is correctly propagated """ # Scene loads without backface culling: a green place partially covers a gray sphere super().open_usd("hydra/backFaceCulling.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "backfaceCulling_off.png") self.set_settings({"/rtx/hydra/faceCulling/enabled": True}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "backfaceCulling_on.png") stage = self.ctx.get_stage() prim = stage.GetPrimAtPath("/World/Plane") attr = prim.GetAttribute("singleSided") attr.Set(False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "backfaceCulling_doublesided.png") async def test_displayColor(self): """ Test hydra mesh - change display color """ await self.geometry_with_attribute("primvars:displayColor", Sdf.ValueTypeNames.Color3f, [(0, 1, 0)]) await self.capture_and_compare(self.TEST_PATH, "displayColor.png") # OM-58993 - Changing only display color should work prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) mesh = UsdGeom.Mesh(prim) displayColorAttr = mesh.GetDisplayColorAttr() displayColorAttr.Set([(0, 0, 1)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorChange.png") stage = self.ctx.get_stage() prim = stage.GetPrimAtPath(self.PRIM_PATH) mesh = UsdGeom.Mesh(prim) attr = prim.GetAttribute("primvars:displayColor") primvar = UsdGeom.Primvar(attr) primvar.SetInterpolation(UsdGeom.Tokens.uniform) colors = [(1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 1), (0, 0, 1), (1, 0, 1)] attr.Set(colors) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorUniform.png") primvar.SetInterpolation(UsdGeom.Tokens.vertex) colors = [(1, 0, 0), (1, 0, 1), (1, 1, 1), (1, 1, 0), (0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0)] attr.Set(colors) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorVertex.png") async def test_primvarBinding(self): """ Test hydra mesh - varify effects of material edits to geometry primvar binding """ # OM-83102 - the file should open with a material lookup pointing to no primvar. It should render # a default magenta color super().open_usd("hydra/primvars_edit.usda") await self.capture_and_compare(self.TEST_PATH, "primvarNotFound_magenta.png") # changing the default lookup color to yellow prim = self.ctx.get_stage().GetPrimAtPath("/World/Looks/mtl_emissive/data_lookup_color") attr = prim.GetAttribute("inputs:default_value") attr.Set((1, 1, 0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarNotFound_yellow.png") # specify an existing primvar to lookup attr = prim.GetAttribute("inputs:name") attr.Set("blue") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarFound_blue.png") # change to a different existing primvar to lookup attr = prim.GetAttribute("inputs:name") attr.Set("green") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarFound_green.png") # change the default value to red now should have no effect attr = prim.GetAttribute("inputs:default_value") attr.Set((1, 0, 0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarFound_still_green.png") # change to a different not-existing primvar to lookup, now it should render the default color set in previous step attr = prim.GetAttribute("inputs:name") attr.Set("foo_bar") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarNotFound_red.png") # # Mesh specific tests # async def test_topology(self): """ Test hydra mesh - topology changes - transform cube to wedge """ box = self.create_geometry() await wait_for_update() # Wait 5 frames to be sure that we update topology box.CreateFaceVertexCountsAttr([4, 3, 4, 3, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 1, 0, 2, 7, 4, 2, 3, 7, 1, 4, 7, 3]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "topology.png") async def subdiv_default(self, shouldWait=False): box = self.create_geometry() if shouldWait: await wait_for_update() subdivAttr = box.GetSubdivisionSchemeAttr() subdivAttr.Set("catmullClark") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivDefault.png") async def test_subdiv(self): """ Test hydra mesh - subdiv """ await self.subdiv_default(shouldWait=True) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await wait_for_update() await self.subdiv_default(shouldWait=False) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Set refinement level with setting self.set_settings({"/rtx/hydra/subdivision/refinementLevel": 2}) geom = self.create_geometry() subdivAttr = geom.GetSubdivisionSchemeAttr() subdivAttr.Set("catmullClark") geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivRefinementLevel.png", 1e-4) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Set refinement level override from usd self.set_settings({"/rtx/hydra/subdivision/refinementLevel": 0}) geom = self.create_geometry() subdivAttr = geom.GetSubdivisionSchemeAttr() subdivAttr.Set("catmullClark") geom.GetPrim().CreateAttribute("refinementEnableOverride", Sdf.ValueTypeNames.Bool).Set(True) geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(2) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivRefinementLevel.png", 1e-4) # OM-21340 Verify that load of refined geometry does not crash. super().open_usd("hydra/cone_sbdv.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "cone_sbdv.png", 1e-4) async def test_subdiv_toggle(self): """ Test hydra mesh - subdiv toggle on/off, this test verifies that change between regular polygons and subdiv geometry doesn't leave the mesh in a corrupt internal state. """ # OM-88053: toggle on/off sudivision surfaces on a mesh *with authored normals*. # Begin with checking the input geometry: a primitve cube with authored normals. super().open_usd("hydra/cube_subdiv.usda") geom = self.ctx.get_stage().GetPrimAtPath("/World/Cube") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_off.png", 1e-4) # Enabling Catmull-Clark subdivision without changing any other option would simply # discard the authored normals, but still render the polygonal cage. subdivAttr = geom.GetAttribute("subdivisionScheme") subdivAttr.Set("catmullClark") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_smoothNormals.png", 1e-4) # This should produce a subdivided smooth mesh. geom.CreateAttribute("refinementEnableOverride", Sdf.ValueTypeNames.Bool).Set(True) geom.CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(2) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_subdivided.png", 1e-4) # Deform by moving a point. mesh = UsdGeom.Mesh(geom) points = mesh.GetPointsAttr().Get() points[7] = points[7] + Gf.Vec3f(0, 40, 0) mesh.GetPointsAttr().Set(points) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_deformed.png", 1e-4) # Also test bilinear subdivision subdivAttr.Set("bilinear") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_bilinear.png", 1e-4) # Finally this should go back to the original mesh with authored normals. subdivAttr.Set("none") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_off_again.png", 1e-4) async def test_handedness(self): """ Test hydra mesh - toggle orintation between right and left handed, in a combination of triangulated mesh and quadrangulated mesh, with and without subdivision surfaces. """ # OM-113941: toggle handedness. A custom material front-facing green and back-facing red. super().open_usd("hydra/handedness_001.usda") await wait_for_update() self.set_settings(postLoadTestSettings) # This triangulated mesh is left-handed and has subdivision surface on. It also has broken normals # (a vector of zero entries) that would have resulted in a crash when toggling subdivision surfaces off. geomT = self.ctx.get_stage().GetPrimAtPath("/World/glasst_mod/SH000254198100001_Tube/SH000254198100001_Tube") # This is a mesh made of quads and right-handed geomQ = self.ctx.get_stage().GetPrimAtPath("/World/glassq/SH000254198100001_Tube/SH000254198100001_Tube") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "handedness_001_subdiv_green.png", 1e-4) # Toggle handedness geomT.GetAttribute("orientation").Set("leftHanded") # This edit would not render red in OM-113941 geomQ.GetAttribute("orientation").Set("rightHanded") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "handedness_001_subdiv_red.png", 1e-4) # Toggle subdivision surface geomT.GetAttribute("subdivisionScheme").Set("none") # This edit would crash OM-113941 geomQ.GetAttribute("subdivisionScheme").Set("catmullClark") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "handedness_001_mesh_red.png", 1e-4) # Toggle handedness again geomT.GetAttribute("orientation").Set("rightHanded") geomQ.GetAttribute("orientation").Set("leftHanded") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "handedness_001_mesh_green.png", 1e-4) async def test_points(self): """ Test hydra mesh - update points """ pts = [cubePts, cubePts.copy()] pts[1][1] = (150, -50, -50) await self.attribute_test_case(self.create_geometry, "points", Sdf.ValueTypeNames.Point3f, pts, ["geom.png", "points.png"]) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # OM-76321: this set of tests [interleavedPointsEdit_*] verifies intermittent primvar edits during # regular points edit. Special care is due because of the minimal updates we do to mesh VBs # Interleaved points edit - initial state, this should render a blue cube. geom = self.create_geometry() mesh = UsdGeom.Mesh(geom) displayColorAttr = mesh.GetDisplayColorAttr() displayColorAttr.Set([(0, 0, 1)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_0.png", 1e-4) # Interleaved points edit - first edit, the cube is slightly deformed and still blue. # This first edit goes through full mesh update to create mutable buffers (not deduplicated). pts[1][1] = (60, -50, -50) geom.GetPointsAttr().Set(pts[1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_1.png", 1e-4) # Interleaved points edit - second edit, the cube is deformed again and is now set to green # The second edit goes through meshUpdateVertices and creates a second VB. pts[1][1] = (70, -50, -50) geom.GetPointsAttr().Set(pts[1]) displayColorAttr.Set([(0, 1, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_2.png", 1e-4) # Interleaved points edit - third edit, the cube is more deformed and should still be green # The last edit verifies that the previous edit to primvars need to be propagated to The # VB ping-pong swap. If this fails the cube will be blue (as in previous frame) instead of green. pts[1][1] = (80, -50, -50) geom.GetPointsAttr().Set(pts[1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_3.png", 1e-4) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def test_normals(self): """ Test hydra mesh - update normals """ self.set_settings({"/rtx/debugView/target": "normal"}) # Authored face varying interpolation normals = [[(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1), (1, 0, 0), (1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)], [(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0.5, 0.5, 0), (0.5, 0.5, 0), (0.5, 0.5, 0), (0.5, 0.5, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)]] def createGeom(): geom = self.create_geometry() geom.CreateNormalsAttr() geom.SetNormalsInterpolation("faceVarying") return geom await self.attribute_test_case(createGeom, "normals", Sdf.ValueTypeNames.Point3f, normals, ["normals.png", "normalsAuthoredFaceVarying.png"]) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Authored vertex interpolation geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)]) geom.SetNormalsInterpolation("vertex") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsAuthoredVertex.png", 1e-4) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Authored uniform interpolation geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, -1, 0), (0, 0, -1), (1, 0, 0), (0, 0, 1), (-1, 0, 0), (0, 1, 0)]) geom.SetNormalsInterpolation("uniform") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normals.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Authored constant interpolation geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, 1, 0)]) geom.SetNormalsInterpolation("constant") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsAuthoredConstant.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Generated smooth geom = self.create_geometry() geom.GetSubdivisionSchemeAttr().Set("catmullClark") geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsGeneratedSmooth.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Generated flat self.create_geometry() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normals.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # TBN Frame mode - generate normals on gpu self.set_settings({"/rtx/hydra/TBNFrameMode": 2}) geom = self.create_geometry() geom.GetSubdivisionSchemeAttr().Set("catmullClark") geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsGeneratedSmooth-gpu.png", 5e-5) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # OM-94303: Unstable due to golden image mismatch async def test_UNSTABLE_gpu_normals(self): """ Test hydra mesh - gpu normals """ super().open_usd("hydra/normals_gen_001.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) self.set_settings({"/rtx/hydra/TBNFrameMode": 2}) self.set_settings({"/rtx/debugView/target": "materialGeometryNormal"}) await self.capture_and_compare(self.TEST_PATH, "gpu_normals_creation.png") # Generated on GPU with reference normals stage = self.ctx.get_stage() prim = stage.GetPrimAtPath("/World/pSphere2") mesh = UsdGeom.Mesh(prim) points = mesh.GetPointsAttr().Get() # By moving a point we force the generation of normals. Regression test for OM-90364 / MR !24845 points[16] = Gf.Vec3f(0, 11, 0) mesh.GetPointsAttr().Set(points) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "gpu_normals_editing.png") async def test_texCoords(self): """ Test hydra mesh - update tex coords """ self.set_settings({"/rtx/debugView/target": "texcoord0"}) # faceVarying geom = self.create_geometry() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "texCoordsFaceVarying.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # vertex or varying (they are the same for a mesh geometry) geom = self.create_geometry() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set( [(0, 0), (0.1, 0), (0.2, 0), (0.3, 0), (0.4, 0), (0.5, 0), (0.6, 0), (0.7, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "texCoordsVertex.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # uniform geom = self.create_geometry() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.uniform).Set( [(0, 0), (0, 0.1), (0, 0.2), (0, 0.3), (0, 0.4), (0, 0.5)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "texCoordsUniform.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def test_tangents(self): """ Test hydra mesh - update tangents """ self.set_settings({"/rtx/debugView/target": "tangentu"}) # default - gpu geom = self.create_geometry() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsU.png") self.set_settings({"/rtx/debugView/target": "tangentv"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsV.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # cpu - uniform geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, -1, 0), (0, 0, -1), (1, 0, 0), (0, 0, 1), (-1, 0, 0), (0, 1, 0)]) geom.SetNormalsInterpolation("uniform") # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) self.set_settings({"/rtx/debugView/target": "tangentu"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsU.png") self.set_settings({"/rtx/debugView/target": "tangentv"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsV.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # cpu - vertex geom = self.create_geometry() geom.GetNormalsAttr().Set([(-0.57735, -0.57735, -0.57735), (0.57735, -0.57735, -0.57735), (-0.57735, -0.57735, 0.57735), (0.57735, -0.57735, 0.57735), (-0.57735, 0.57735, -0.57735), (0.57735, 0.57735, -0.57735), (0.57735, 0.57735, 0.57735), (-0.57735, 0.57735, 0.57735)]) geom.SetNormalsInterpolation("vertex") # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) self.set_settings({"/rtx/debugView/target": "tangentu"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsVertexU.png") self.set_settings({"/rtx/debugView/target": "tangentv"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsVertexV.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # cpu - facevarying geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1), (1, 0, 0), (1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)]) geom.SetNormalsInterpolation("faceVarying") # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) self.set_settings({"/rtx/debugView/target": "tangentu"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsFacevaryingU.png") self.set_settings({"/rtx/debugView/target": "tangentv"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsFacevaryingV.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def test_skeleton(self): """ Test hydra mesh - skeleton """ super().open_usd("hydra/skelcylinder.usda") # self.set_settings(postLoadTestSettings) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) # create timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "skeleton0.png") timeline.set_current_time(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "skeleton1.png") timeline.set_auto_update(True) timeline.stop() # TODO remove, update # create many instances # SkinningMethod: eDualQuaternion, eClassicLinear, eWeightedBlend async def test_mesh_with_api_schemas(self): """ Verify proper population and refresh when apiSchemas are present """ # OM-24223: Verify proper mesh population when duplicating with apiSchemas present stage = self.ctx.get_stage() cube = UsdGeom.Cube.Define(stage, "/Cube") cube.GetSizeAttr().Set(50.0) # Doesn't matter which API schema is applied, just use one from core, to avoid depending on physics. # https://github.com/PixarAnimationStudios/USD/commit/6f0ce585bf5d06ca929584b515cd3bdf05d78eb3 # https://github.com/PixarAnimationStudios/USD/commit/1222ea7cd2478e576f4fc32936f781d2a7f61cd5 # https://github.com/PixarAnimationStudios/USD/commit/61fcc34d8555bb269fae49af90eab5154989392c if hasattr(UsdGeom, 'VisibilityAPI'): UsdGeom.VisibilityAPI.Apply(cube.GetPrim()) else: from pxr import UsdRender UsdRender.SettingsAPI.Apply(cube.GetPrim()) await wait_for_update() omni.kit.commands.execute("CopyPrim", path_from="/Cube", path_to="/DupeCube") self.ctx.get_selection().clear_selected_prim_paths() set_transform_helper("/DupeCube", translate=Gf.Vec3d(200, 0, 0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "dupeWithApiSchema.png") self.ctx.get_stage().RemovePrim("/Cube") self.ctx.get_stage().RemovePrim("/DupeCube") await wait_for_update() # OM-29819: Verify proper normals after applying an API schema super().open_usd("hydra/torus_mesh.usda") await wait_for_update() stage = self.ctx.get_stage() # Doesn't matter which API schema is applied, just use one from core, to avoid depending on physics. # https://github.com/PixarAnimationStudios/USD/commit/6f0ce585bf5d06ca929584b515cd3bdf05d78eb3 # https://github.com/PixarAnimationStudios/USD/commit/1222ea7cd2478e576f4fc32936f781d2a7f61cd5 # https://github.com/PixarAnimationStudios/USD/commit/61fcc34d8555bb269fae49af90eab5154989392c if hasattr(UsdGeom, 'VisibilityAPI'): UsdGeom.VisibilityAPI.Apply(stage.GetPrimAtPath("/World/Torus")) else: from pxr import UsdRender UsdRender.SettingsAPI.Apply(stage.GetPrimAtPath("/World/Torus")) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsWithApiSchema.png", 3e-4) async def test_UNSTABLE_tetMesh_UNSTABLE(self): """ Test hydra tetmesh """ # Eventually this should live in the physics repo, when omni hydra supports plugin adapters. super().open_usd("hydra/tetmesh_teddy.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tetmesh_teddy.png", 3e-4) async def test_mesh_dedup(self): """ Verify hash collisions in mesh dedup do not crash """ # OM-64181: Verify hash collisions in mesh dedup do not crash timeline = omni.timeline.get_timeline_interface() timeline.set_current_time(0) super().open_usd("hydra/AlternatingCubePlane.usda") await wait_for_update() N = 50 while N > 0: N = N - 1 timeline.forward_one_frame() await wait_for_update() timeline.rewind_one_frame() await wait_for_update() class TestRtxHydraMeshMaterials(RtxHydraMaterialsTest): TEST_PATH = "hydra/mesh/material" PRIM_PATH = "/World/box" def create_geometry(self, name=PRIM_PATH): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box async def test_materials(self): """ Test hydra mesh - materials """ materials = ["Green", "Red"] looksPath = "/World/Looks/" # Set and change material geomPrim = self.create_geometry().GetPrim() for m in materials: self.bind_material(geomPrim, looksPath + m) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_{}.png".format(m)) # Unbind material it should fallback to basic material UsdShade.MaterialBindingAPI(geomPrim).UnbindAllBindings() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_base.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Subsets subsetPath = self.PRIM_PATH + "/subset" geomPrim = self.create_geometry().GetPrim() subset = UsdGeom.Subset.Define(self.ctx.get_stage(), subsetPath) # https://github.com/PixarAnimationStudios/USD/commit/c1cdbbaa8a2dd8ecbb9722de517ef44c1a680352 # Family name required for subset material bindingas as of USD 21.11+; # has been available on subsets from the firsrt public release of USD. subset.CreateFamilyNameAttr().Set(UsdShade.Tokens.materialBind) attr = subset.CreateIndicesAttr() attr.Set([5]) self.bind_material(geomPrim, looksPath + materials[0]) self.bind_material(subset.GetPrim(), looksPath + materials[1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_subsets.png") # Update subset attr.Set([3]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_subsets2.png") # Remove subset self.ctx.get_stage().RemovePrim(subsetPath) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_Green.png") class TestRtxHydraMeshInstancer(RtxHydraInstancerTest): # TODO full cover scene instancer with tests TEST_PATH = "hydra/mesh/instancer" GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/box" def create_geometry(self, name=GEOM_PATH): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box async def test_sceneInstancer(self): """ Test hydra mesh scene instancer """ await self.si_all() sgInstSettingsKey = "/persistent/omnihydra/useSceneGraphInstancing" useSceneGraphInstancing = carb.settings.get_settings().get_as_bool(sgInstSettingsKey) try: async def nest_ptinst_in_sginst_test(self, enableOmniHydraScenegraphInstancing): carb.settings.get_settings().set_bool(sgInstSettingsKey, enableOmniHydraScenegraphInstancing) # OM-34669 # Verify that turning on instanceable on a hierarchy that contains # a point instancer does not corrupt parent xforms. super().open_usd("hydra/ptinst_inside_sginst.usda") await wait_for_update() stage = self.ctx.get_stage() instance = stage.GetPrimAtPath('/World/Instance') instance.SetInstanceable(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "ptinst_inside_sginst.png") # Verify that authoring xforms on instances over internal references refreshes properly. set_transform_helper(instance.GetPath(), translate=Gf.Vec3d(200,0,0), euler=Gf.Vec3f(0, 0, -120)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "ptinst_inside_sginst_rotated.png") # Verify that authoring xforms on instances over external references refreshes properly. super().open_usd("hydra/ref_ptinst_inside_sginst.usda") await wait_for_update() stage = self.ctx.get_stage() instance = stage.GetPrimAtPath('/World/Instance') set_transform_helper(instance.GetPath(), euler=Gf.Vec3f(0, 0, -30)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "ref_ptinst_inside_sginst_rotated.png") await nest_ptinst_in_sginst_test(self, False) await nest_ptinst_in_sginst_test(self, True) finally: carb.settings.get_settings().set_bool(sgInstSettingsKey, useSceneGraphInstancing) # OM-35643 # Verify xforms above scenegraph instance roots are honored by omni hydra scenegraph instancing. try: carb.settings.get_settings().set_bool(sgInstSettingsKey, True) super().open_usd("hydra/CubeWorld.usda") await wait_for_update() stage = self.ctx.get_stage() cubeInstance = stage.GetPrimAtPath("/CubeWorld/CubeInstance") cubeInstance.SetInstanceable(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "sginst_parent_xform.png", 1e-4) cubeInstance.SetInstanceable(False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "sginst_parent_xform.png", 1e-4) finally: carb.settings.get_settings().set_bool(sgInstSettingsKey, useSceneGraphInstancing) # OM-36724 # Verify xforms in the presence of nested scenegraph instancing with omni hydra scenegraph instancing enabled for testFile in ["hydra/nestedScenegraphInstances.usda", "hydra/nestedScenegraphInstancesOff.usda"]: try: carb.settings.get_settings().set_bool(sgInstSettingsKey, True) super().open_usd(testFile) await wait_for_update() stage = self.ctx.get_stage() cubeInstance = stage.GetPrimAtPath("/World/threeCubes") cubeInstance.SetInstanceable(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "nested_sginst_toggle.png", 1e-4) cubeInstance.SetInstanceable(False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "nested_sginst_toggle.png", 1e-4) set_transform_helper(cubeInstance.GetPath(), translate=Gf.Vec3d(200,0,0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "nested_sginst_xform_refresh.png", 1e-4) finally: carb.settings.get_settings().set_bool(sgInstSettingsKey, useSceneGraphInstancing) async def test_pointInstancer(self): """ Test hydra mesh point instancer """ await self.pi_all() # OM-30658 Verify proper population when prototype is not nested under point instancer super().open_usd("hydra/ptinst_unnested_proto.usda") await wait_for_update() # Raise threshold a bit to account for noise between local runs and TC await self.capture_and_compare(self.TEST_PATH, "ptinst_unnested_proto.png", 3e-4) # OM-32571 Verify proper population after creating an empty instancer. super().open_usd("hydra/cube_ptinst_unpopulated.usda") await wait_for_update() stage = self.ctx.get_stage() p = stage.GetPrimAtPath('/World/output') pos = p.GetAttribute('positions1').Get() ori = p.GetAttribute('orientations1').Get() scl = p.GetAttribute('scales1').Get() pi = p.GetAttribute('protoIndices1').Get() with Sdf.ChangeBlock(): p.GetAttribute('positions').Set(pos) p.GetAttribute('orientations').Set(ori) p.GetAttribute('scales').Set(scl) p.GetAttribute('protoIndices').Set(pi) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "cube_ptinst_unpopulated.png") # OM-35779 Verify proper refresh of nested point instancers super().open_usd("hydra/nested_ptinst.usda") await wait_for_update() stage = self.ctx.get_stage() prim = stage.GetPrimAtPath("/World/PointInstancer_parent") pos = prim.GetAttribute('positions').Get() new_pos = list(pos) new_pos[0] = Gf.Vec3d(300,300,0) prim.GetAttribute('positions').Set(new_pos) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "nested_ptinst.png") # OM-38291 Verify no crash with full update from Nucleus super().open_usd("hydra/OM-38291-one_ptinst.usda") await wait_for_update() stage = self.ctx.get_stage() # Mock a full update from Nucleus live edit by clearing and reloading the layer. stage.GetRootLayer().Clear() await wait_for_update() stage.GetRootLayer().Reload(True) await wait_for_update() # OM-110897 Verify no crash with nested point instancers with different dimensions super().open_usd("hydra/nested_ptinst_extradim.usda") await wait_for_update() stage = self.ctx.get_stage() await wait_for_update()
47,596
Python
46.980847
158
0.631272
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_selectionoutline.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom spherePath = '/World/Sphere' cylinderPath = '/World/Cylinder' defaultColor0 = [0, 0, 0, 0] defaultColor1 = [0.7, 0.7, 0, 1] defaultColor2 = [0.7, 0, 1, 1] displayOptionSetting = "/persistent/app/viewport/displayOptions" outlineWidthSetting = "/persistent/app/viewport/outline/width" outlineColorSetting = "/persistent/app/viewport/outline/color" shadeColorSetting = "/persistent/app/viewport/outline/shadeColor" intersectionColorSetting = "/persistent/app/viewport/outline/intersection/color" outlineEnabledSetting = "/app/viewport/outline/enabled" class TestRtxSelectionOutline(RtxTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) self.set_settings({displayOptionSetting: (1 << 7)}) omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings # and stage. await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) self.set_settings({ outlineWidthSetting: 2, outlineColorSetting: defaultColor0, shadeColorSetting: defaultColor0, intersectionColorSetting: defaultColor0, "/app/transform/operation": "select" }) self.create_scene() self.ctx.set_selection_group_outline_color(255, defaultColor1) def set_selected(self, path, select=True): self.ctx.get_selection().set_prim_path_selected(path, select, True, False, True) def create_scene(self): stage = self.ctx.get_stage() sphere = UsdGeom.Sphere.Define(stage, spherePath) sphere.CreateRadiusAttr(100) cylinder = UsdGeom.Cylinder.Define(stage, cylinderPath) cylinder.CreateHeightAttr(200) cylinder.CreateRadiusAttr(75) async def test_rtx_selectionoutline_outline1(self): """ Test SelectionOutline - Outline sphere """ self.set_selected(spherePath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Outline1.png") async def test_rtx_selectionoutline_outline2(self): """ Test SelectionOutline - Outline cylinder """ self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Outline2.png") async def test_rtx_selectionoutline_outline12(self): """ Test SelectionOutline - Outline sphere & cylinder """ self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Outline12.png") async def test_rtx_selectionoutline_intersection(self): """ Test SelectionOutline - Intersection """ self.set_settings({intersectionColorSetting: defaultColor2}) self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Intersection.png", 4e-5) async def test_UNSTABLE_rtx_selectionoutline_thick(self): """ Test SelectionOutline - Outline sphere & cylinder, thick """ self.set_settings({outlineWidthSetting: 15}) self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Thick.png") async def test_rtx_selectionoutline_blend(self): """ Test SelectionOutline - Outline cylinder with blended color """ self.set_settings({outlineWidthSetting: 15}) c = defaultColor1[:3] c.append(0.5) self.ctx.set_selection_group_outline_color(255, c) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Blend.png") async def test_rtx_selectionoutline_multicolored(self): """ Test SelectionOutline - Outline sphere & cylinder with different colors """ self.set_settings({outlineWidthSetting: 4}) self.ctx.set_selection_group(1, spherePath) self.ctx.set_selection_group(2, cylinderPath) self.ctx.set_selection_group_outline_color(1, defaultColor1) self.ctx.set_selection_group_outline_color(2, defaultColor2) self.ctx.set_selection_group_shade_color(1, defaultColor0) self.ctx.set_selection_group_shade_color(2, defaultColor0) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Multicolored.png") async def test_rtx_selectionoutline_shade(self): """ Test SelectionOutline - Shade sphere """ self.set_settings({outlineWidthSetting: 4}) self.ctx.set_selection_group(1, spherePath) self.ctx.set_selection_group(2, cylinderPath) self.ctx.set_selection_group_shade_color(1, defaultColor1) self.ctx.set_selection_group_shade_color(2, defaultColor0) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Shade.png") async def test_UNSTABLE_rtx_selectionoutline_shade_multicolored_UNSTABLE(self): """ Test SelectionOutline - Shade sphere & cylinder with different colors """ self.set_settings({outlineWidthSetting: 4}) self.ctx.set_selection_group(1, spherePath) self.ctx.set_selection_group(2, cylinderPath) self.ctx.set_selection_group_shade_color(1, defaultColor1) self.ctx.set_selection_group_shade_color(2, defaultColor2) await wait_for_update() await self.capture_and_compare("SelectionOutline", "ShadeMulticolored.png") async def test_rtx_selectionoutline_disabled(self): """ Test SelectionOutline - Disabled """ self.set_settings({outlineEnabledSetting: False, displayOptionSetting: 0}) self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Disabled.png") # OM-102267 - unreliable in 105.1 branch async def test_UNSTABLE_rtx_selectionoutline_disabledByMetadata_UNSTABLE(self): """ Test SelectionOutline - Disabled by metadata. OM-34048 """ self.ctx.get_stage().GetPrimAtPath(spherePath).SetMetadata('no_selection_outline', True) self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Outline2.png", 2e-5) # OM-102267 - unreliable in 105.1 branch async def test_UNSTABLE_rtx_selectionoutline_instances_UNSTABLE(self): """ Test Selection Outline - Instances """ self.open_usd("hydra/CubeWorld.usda") PRIM_PATH = '/CubeWorld/CubeInstance' cubeInstance = self.ctx.get_stage().GetPrimAtPath(PRIM_PATH) cubeInstance.SetInstanceable(False) self.set_selected(PRIM_PATH) await wait_for_update() await self.capture_and_compare("SelectionOutline", "InstanceableFalse.png", 4e-5) self.set_selected(PRIM_PATH, False) # Unselect cubeInstance.SetInstanceable(True) self.set_selected(PRIM_PATH) await wait_for_update() await self.capture_and_compare("SelectionOutline", "InstanceableTrue.png", 4e-5) async def test_rtx_selectionoutline_mouse_select(self): """Test mouse selection works in Viewport.""" from omni.kit import ui_test from omni.kit.ui_test.vec2 import Vec2 self.open_usd("hydra/CubeInstance.usda") omni.usd.get_context().get_selection().set_selected_prim_paths([], True) await wait_for_update() await ui_test.emulate_mouse_move_and_click(Vec2(256, 256)) await wait_for_update() await self.capture_and_compare("SelectionOutline", "MouseSelect.png", 4e-5) async def test_rtx_selectionoutline_mouse_select_aov_changed(self): """Test mouse selection works in Viewport before and after AOV change.""" from omni.kit import ui_test from omni.kit.ui_test.vec2 import Vec2 mouse_pos = Vec2(256, 256) self.open_usd("hydra/CubeInstance.usda") usd_context = omni.usd.get_context() usd_context.get_selection().set_selected_prim_paths([], True) await wait_for_update() await ui_test.emulate_mouse_move_and_click(mouse_pos) await wait_for_update() await self.capture_and_compare("SelectionOutline", "MouseSelectAOVA.png", 4e-5) # Reset selection to nothing usd_context.get_selection().set_selected_prim_paths([], True) # Add additional AOVs from omni.kit.viewport.utility import get_active_viewport from pxr import Sdf, Usd, UsdRender stage = usd_context.get_stage() render_product_path = Sdf.Path(get_active_viewport().render_product_path) render_product = UsdRender.Product(stage.GetPrimAtPath(render_product_path)) ordered_vars_rel = render_product.GetOrderedVarsRel() start_aov_len = len(ordered_vars_rel.GetForwardedTargets()) # Targets need to be adde don session-layer as other prims live there with Usd.EditContext(stage, stage.GetSessionLayer()): aov_name = "Depth" render_var = UsdRender.Var.Define(stage, Sdf.Path(f"/Render/Vars/{aov_name}")) render_var.GetSourceNameAttr().Set(aov_name) render_var.GetDataTypeAttr().Set("float") ordered_vars_rel.AddTarget(render_var.GetPath()) end_aov_len = len(render_product.GetOrderedVarsRel().GetForwardedTargets()) self.assertNotEqual(start_aov_len, end_aov_len) # Re-select the object await ui_test.emulate_mouse_move_and_click(mouse_pos) await wait_for_update() await self.capture_and_compare("SelectionOutline", "MouseSelectAOVB.png", 4e-5)
10,699
Python
40.960784
119
0.670904
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_scene_delegate_omni_imaging.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from sys import path import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline import carb.settings from .test_hydra_common import RtxHydraTest from .test_common import testSettings, postLoadTestSettings, wait_for_update from pxr import Gf, UsdShade import shutil, os, pathlib class TestRtxHydraSceneDelegateOmniImagingSetEmissionColor(RtxHydraTest): # OM-73180 # Prior to the update in this ticket the OmniImagingDelegate ignored # certain parameters, "emission_color" being one of them. This test # validates that is no longer the case. async def setUp(self): await super().setUp() self.set_settings(testSettings) super().open_usd("hydra/scene_delegate/emission_color/test.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_set_emission_color(self): ''' Test OmniImagingDelegate don't ignore 'emission_color' ''' await wait_for_update(wait_frames=10) prim = self.ctx.get_stage().GetPrimAtPath("/World/Looks/mtl_emission/emission") shader_prim = UsdShade.Shader(prim) shader_prim.GetInput("emission_color").Set(Gf.Vec3f(1.0, 0.0, 0.0)) await wait_for_update(wait_frames=10) await self.capture_and_compare("hydra/scene_delegate", "set_emission_color.png")
1,865
Python
40.466666
88
0.723324
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_scenedb.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom, Sdf import numpy as np class TestRtxSceneDb(RtxTest): TEST_PATH = "scenedb" async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings and stage. self.add_dir_light() await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) def create_geometry(self, name): sphere = UsdGeom.Sphere.Define(self.ctx.get_stage(), name) sphere.CreateRadiusAttr(10) def create_instancer(self, name, N): pts = [] indices = [] sp = 250. dx = 500. / N[0] dy = 500. / N[1] dz = 500. / N[2] for i in np.arange(-sp, sp, dx): for j in np.arange(-sp, sp, dy): for k in np.arange(-sp, sp, dz): pts.append((i, j, k)) indices.append(0) print("Generated points: ", len(indices)) lyr = self.ctx.get_stage().GetRootLayer() with Sdf.ChangeBlock(): instancer = lyr.GetPrimAtPath("/World/Instancer") or \ Sdf.PrimSpec(lyr.GetPrimAtPath("/World"), "Instancer", Sdf.SpecifierDef, "PointInstancer") pos = lyr.GetAttributeAtPath("/World/Instancer.positions") or \ Sdf.AttributeSpec(instancer, "positions", Sdf.ValueTypeNames.Point3fArray) pos.default = pts protoIndices = lyr.GetAttributeAtPath("/World/Instancer.protoIndices") or \ Sdf.AttributeSpec(instancer, "protoIndices", Sdf.ValueTypeNames.IntArray) protoIndices.default = indices rel = lyr.GetRelationshipAtPath("/World/Instancer.prototypes") or \ Sdf.RelationshipSpec(instancer, "prototypes") rel.targetPathList.prependedItems = [name] async def test_sphere_PI_1M(self): id = "/World/Sphere" self.create_geometry(id) self.create_instancer(id, (100, 100, 100)) await wait_for_update(self.ctx, 25) # Wait 25 frames before capture. await self.capture_and_compare(self.TEST_PATH, "sphere1M.png", threshold=5e-5) # Unstable due to crashes in SceneDB: OM-49598 async def test_UNSTABLE_sphere_PI_1M_Recreate_UNSTABLE(self): id = "/World/Sphere" self.create_geometry(id) self.create_instancer(id, (100, 100, 100)) await wait_for_update(self.ctx, 25) # Wait 25 frames before capture. self.ctx.get_stage().RemovePrim("/World/instancer") self.create_instancer(id, (100, 100, 100)) await self.capture_and_compare(self.TEST_PATH, "sphere1M.png")
3,313
Python
43.783783
130
0.644431
omniverse-code/kit/exts/omni.rtx.tests/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.rtx.tests`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [Unreleased] ### Added ### Changed ### Removed ## [0.1.4] - 2022-10-19 ### Changed - Flagged test_light_collection_lightvistoggle as UNSTABLE. ## [0.1.3] - 2022-06-05 ### Fixed - Added one missing dependency and a couple small fixes ## [0.1.2] - 2022-06-02 ### Changed - Capture from Viewport texture directly instead of UI / Window ## [0.1.1] - 2022-05-23 ### Changed - Add missing explicit dependencies ## [0.1.0] - 2021-04-20 ### Added - Initial Release
629
Markdown
16.5
74
0.675676
omniverse-code/kit/exts/omni.rtx.tests/docs/README.md
# The RTX Renderer Test Framework [omni.rtx.tests] This extensions contains python tests for RTX renderer. This tests is based on kit python tests. See `omni.kit.tests` documentation. # How-to run tets There is few ways to run tets. 1) Run script `_build/{build}/{config}/tests-omni.rtx.tests.{bat|sh}` 2) Run `kit`. Open `Window -> Test Runner`. Select and run tests you want to run. # How-to add new tests: 1) Create new py file. See `test_example.py` as template. 2) Derive you test class from `class RtxTests` from `test_common.py` 3) Add your test by adding method started from `test_` 4) Improt your test class in __init__.py # How-to write tests You may use any methods from `omni.kit.tests`. For example to assert use `self.assertTrue({condition})`. Default directory for placing usd files is `{ext_path}/data/usd` ## Settings It is not recommended to use `carb.settings` directly as tests might be executed by user in kit and overwrite user's settings config. There is way to deal with it - use next method for settings. ``` self.set_settings({"/app/setting1": "val1", "/app/setting2": (0, 0), "/app/setting3": True})) ``` `set_settings` remembers previous value of setting that changed first time and set this value on `tearDown()` ### Default rtx test settings See `testSettings` and `postLoadTestSettings`. `testSettings` is set on test startup before stage loading. `postLoadTestSettings`is set after stage loading. You can load this settings in your tests without changes or create your own setup based on it. ## Capture and compare screenshots with golden Rendering is drawn screen with few frames delay. So after any changes has done it is needed to wait few frames before capture. Use `wait_for_update(wait_frames=4)` for waiting next few frames. For capturing use `capture_and_compare` function. Generated images are placed in `{kit}/kit/outputs/omni.rtx.tests/{image_subdir}`. Goldens for compare are placed in `{ext_path}/data/goldens/{image_subdir}`. ### Generating goldens Tests is not interrupted if golden is missed in goloden directory. So if it is needed to generate goldens it shold be removed from golden directory. Then run the tests and copy new goldens from output directory. ## Helper functions `set_transform_helper` - set transform for specified prim path `add_dir_light` - add directional light `/World/Light` to scene `add_floor` - add floor plane `/World/Floor` to scene `open_usd` - open usd file `set_camera` - set camera position and target
2,556
Markdown
35.014084
126
0.735915
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/peer_user_shared_data.py
import carb import omni.usd import omni.kit.usd.layers as layers from pxr import Sdf, Usd, Tf, UsdGeom from typing import List from .constants import * from .utils import ( get_user_shared_root_path, get_bound_camera_property_path, get_following_user_property_path, get_selection_property_path ) class PeerUserSharedData: """ Data abstraction to manage peer user data inside presence layer. """ def __init__( self, usd_context: omni.usd.UsdContext, shared_stage: Usd.Stage, user_info: layers.LiveSessionUser ): # Shared stage is the one in the live session folder with name users.live that holds all # shared data for all users. Peer users camera will be replicated into the local session layer # with path self.session_layer_camera_path if peer user is bound to the builtin camera. self.shared_stage = shared_stage self.user_info = user_info self.usd_context = usd_context user_name_identifier = Tf.MakeValidIdentifier(user_info.user_name.split('@')[0]) self.__replication_root_path = LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH.AppendElementString( f"{user_name_identifier}_{user_info.user_id}" ) self.__replication_camera_path = self.__replication_root_path.AppendElementString( f"{user_name_identifier}_Camera_{user_info.user_id}" ) # Creates corresponding replication inside local session layer. stage = self.usd_context.get_stage() target_layer = stage.GetSessionLayer() with Usd.EditContext(stage, target_layer): prim = stage.DefinePrim(self.__replication_root_path, "Scope") omni.usd.editor.set_hide_in_stage_window(prim, True) omni.usd.editor.set_hide_in_ui(prim, True) # Creates user namespace inside shared stage self.shared_root_path = get_user_shared_root_path(self.user_id) prim_spec = Sdf.CreatePrimInLayer(self.shared_stage.GetRootLayer(), SESSION_SHARED_LAYER_ROOT_PATH) prim_spec.specifier = Sdf.SpecifierDef prim_spec = Sdf.CreatePrimInLayer(self.shared_stage.GetRootLayer(), self.shared_root_path) prim_spec.specifier = Sdf.SpecifierDef # The property that can be used to check which camera the user is bound to. # Every user can bind two kinds of cameras: # 1. Builtin cameras. # 2. Cameras in the USD. # If it's builtin cameras, the property value must be in the list of SHARED_BUILT_IN_CAMERA_LIST. # If it's camera in the USD, the property value points to the camera path in the stage. self.__bound_camera_property_path = get_bound_camera_property_path(self.user_id) self.__selections_property_path = get_selection_property_path(self.user_id) self.__following_user_property_path = get_following_user_property_path(self.user_id) self.__shared_stage_builtin_camera_paths = {} for camera_name in SHARED_BUILT_IN_CAMERA_LIST: self.__shared_stage_builtin_camera_paths[camera_name] = self.shared_root_path.AppendElementString(camera_name) self.__current_bound_camera_property_value: str = None self.__current_selection_paths: List[Sdf.Path] = [] self.__current_following_user: str = None self.update_bound_camera() @property def user_id(self): return self.user_info.user_id @property def user_name(self): return self.user_info.user_name def destroy(self): if self.usd_context.get_stage(): layers.LayerUtils.remove_prim_spec( self.usd_context.get_stage().GetSessionLayer(), self.__replication_root_path ) self.shared_stage = None self.usd_context = None def update_bound_camera(self): latest_bound_camera_path = self.__get_bound_camera_path_from_usd() if latest_bound_camera_path != self.__current_bound_camera_property_value: self.__current_bound_camera_property_value = latest_bound_camera_path if not self.is_bound_to_builtin_camera(): layers.LayerUtils.remove_prim_spec( self.usd_context.get_stage().GetSessionLayer(), self.__replication_camera_path ) else: self.replicate_bound_camera_to_local() with Sdf.ChangeBlock(): self.__hide_prim_and_set_display_name() return True return False def update_selections(self): latest_selections = self.__get_selections_from_usd() if latest_selections != self.__current_selection_paths: self.__current_selection_paths = latest_selections return True return False def update_following_user(self): latest_following_user = self.__get_following_user_from_usd() if latest_following_user != self.__current_following_user: self.__current_following_user = latest_following_user return True return False @carb.profiler.profile def replicate_bound_camera_to_local(self, property_names: List[str] = []): builtin_camera_name = self.__bound_camera_property_value path = self.__shared_stage_builtin_camera_paths.get(builtin_camera_name, None) if not path: return shared_data_stage = self.shared_stage stage = self.usd_context.get_stage() bound_camera_prim = self.shared_stage.GetPrimAtPath(path) if not bound_camera_prim: return bound_camera_path = bound_camera_prim.GetPath() target_path = self.__replication_camera_path target_layer = stage.GetSessionLayer() with Sdf.ChangeBlock(): Sdf.CreatePrimInLayer(target_layer, target_path) if property_names: for property_name in property_names: source_property_path = bound_camera_path.AppendProperty(property_name) target_property_path = target_path.AppendProperty(property_name) Sdf.CopySpec( shared_data_stage.GetRootLayer(), source_property_path, target_layer, target_property_path ) else: Sdf.CopySpec(shared_data_stage.GetRootLayer(), bound_camera_path, target_layer, target_path) def is_bound_to_builtin_camera(self): if self.__current_following_user: return False builtin_camera_name = self.__bound_camera_property_value path = self.__shared_stage_builtin_camera_paths.get(builtin_camera_name, None) return path is not None def is_bound_camera_property_affected(self, changed_path: Sdf.Path): changed_path = Sdf.Path(changed_path) return changed_path == self.__bound_camera_property_path def is_selection_property_affected(self, changed_path: Sdf.Path): changed_path = Sdf.Path(changed_path) return changed_path == self.__selections_property_path def is_following_user_property_affected(self, changed_path: Sdf.Path): changed_path = Sdf.Path(changed_path) return changed_path == self.__following_user_property_path def is_builtin_camera_affected(self, changed_path: Sdf.Path): """Checkes if the changes to path will influence the builtin camera prim if user is bound to builtin camera.""" changed_path = Sdf.Path(changed_path) builtin_camera_name = self.__bound_camera_property_value path = self.__shared_stage_builtin_camera_paths.get(builtin_camera_name, None) # Not bound to builtin camera if not path: return False return changed_path.GetPrimPath() == path def get_bound_camera_prim(self) -> Usd.Prim: """Returns the bound camera in the local stage. It will return None if it's following other user.""" if self.__current_following_user: return None if self.is_bound_to_builtin_camera(): camera_path = self.__replication_camera_path elif Sdf.Path.IsValidPathString(self.__bound_camera_property_value): camera_path = Sdf.Path(self.__bound_camera_property_value) else: camera_path = None if not camera_path: return None stage = self.usd_context.get_stage() return stage.GetPrimAtPath(camera_path) @property def __bound_camera_property_value(self) -> str: """ Returns property value of bound camera path in shared stage. In order to support binding to both builtin cameras and non-builtin cameras. The property value can be builtin camera name listed in the SHARED_BUILT_IN_CAMERA_LIST, or the prim path in the local stage. """ if self.__current_bound_camera_property_value is None: self.__current_bound_camera_property_value = self.__get_bound_camera_path_from_usd() return self.__current_bound_camera_property_value @property def following_user_id(self) -> str: """The user id that this user is currently following.""" if self.__current_following_user is None: self.__current_following_user = self.__get_following_user_from_usd() return self.__current_following_user @property def selections(self) -> List[Sdf.Path]: if self.__current_selection_paths is None: self.__current_selection_paths = self.__get_selections_from_usd() return self.__current_selection_paths def __get_following_user_from_usd(self): following_user_property = self.shared_stage.GetRootLayer().GetAttributeAtPath(self.__following_user_property_path) if not following_user_property: return "" return str(following_user_property.default).strip() def __get_bound_camera_path_from_usd(self): camera_path_property = self.shared_stage.GetRootLayer().GetAttributeAtPath(self.__bound_camera_property_path) if not camera_path_property: return "" return str(camera_path_property.default).strip() def __get_selections_from_usd(self): selections_property = self.shared_stage.GetRootLayer().GetAttributeAtPath(self.__selections_property_path) if not selections_property: return [] selections = selections_property.default selections = [Sdf.Path(selection) for selection in selections if Sdf.Path.IsValidPathString(str(selection))] return selections def __hide_prim_and_set_display_name(self): stage = self.usd_context.get_stage() prim = self.get_bound_camera_prim() if not prim: return prim = prim.GetPrim() with Sdf.ChangeBlock(): with Usd.EditContext(stage, stage.GetSessionLayer()): omni.usd.editor.set_hide_in_stage_window(prim, True) omni.usd.editor.set_hide_in_ui(prim, True) omni.usd.editor.set_display_name(prim, self.user_info.user_name) prim.CreateAttribute("omni:kit:cameraLock", Sdf.ValueTypeNames.Bool).Set(True)
11,222
Python
39.225806
122
0.642132
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/event.py
__all__ = ["PresenceLayerEventType", "PresenceLayerEventPayload", "get_presence_layer_event_payload"] import carb from enum import IntEnum from typing import Set, List EVENT_PAYLOAD_KEY = "payload" class PresenceLayerEventType(IntEnum): # Emitted when local user enters/quits follow mode to other peer users. # REMIND: this event only applies to local user. In order to get the following status of other peer user, # you need to listen for BOUND_CAMERA_CHANGED below and PresenceLayerAPI.is_in_following_mode to check # if peer user is following other users. LOCAL_FOLLOW_MODE_CHANGED = carb.events.type_from_string("omni.kit.collaboration.presence_layer@local_follow_mode") # Emitted when peer user switched its bound camera or the the user that is following switches the bound camera. BOUND_CAMERA_CHANGED = carb.events.type_from_string("omni.kit.collaboration.presence_layer@bound_camera") # Emitted when peer user switched its selections. SELECTIONS_CHANGED = carb.events.type_from_string("omni.kit.collaboration.presence_layer@selections") # Emitted when the bound camera if peer user is builtin camera, and its properties are changed. BOUND_CAMERA_PROPERTIES_CHANGED = carb.events.type_from_string( "omni.kit.collaboration.presence_layer@bound_camera_properties" ) # Emitted when the bound camera of peer user is resynced. This is the same as prim resync of USD. BOUND_CAMERA_RESYNCED = carb.events.type_from_string( "omni.kit.collaboration.presence_layer@bound_camera_resynced" ) class PresenceLayerEventPayload: def __init__(self, event: carb.events.IEvent) -> None: carb_dict = carb.dictionary.get_dictionary() if event.type and event.type in iter(PresenceLayerEventType): self.event_type = PresenceLayerEventType(event.type) if self.event_type == PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED: self.__changed_users = carb_dict.get_dict_copy(event.payload) elif EVENT_PAYLOAD_KEY in event.payload: self.__changed_users = {}.fromkeys(event.payload[EVENT_PAYLOAD_KEY]) else: self.__changed_users = {} else: self.event_type = None self.__changed_users = {} @property def changed_user_ids(self) -> List[str]: return self.__changed_users.keys() def get_changed_camera_properties(self, user_id: str) -> Set[str]: """Gets the changed properties of bound builtin camera if event_type is BOUND_CAMERA_PROPERTIES_CHANGED.""" return self.__changed_users.get(user_id, set()) def __str__(self): return f"Event Type: {str(self.event_type)}, Changes: {self.__changed_users}" def get_presence_layer_event_payload(event: carb.events.IEvent) -> PresenceLayerEventPayload: try: return PresenceLayerEventPayload(event) except Exception as e: carb.log_error(f"Failed to convert event: {str(e)}") return None
3,026
Python
42.869565
119
0.697951
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/constants.py
from pxr import Sdf SESSION_SHARED_USER_LAYER = "shared_data/users.live" SESSION_SHARED_LAYER_ROOT_PATH = Sdf.Path("/__session_shared_data__") SESSION_SHARED_PERSPECTIVE_CAMERA_NAME = "perspective" SESSION_SHARED_FRONT_CAMERA_NAME = "front" SESSION_SHARED_LEFT_CAMERA_NAME = "left" SESSION_SHARED_RIGHT_CAMERA_NAME = "right" SESSION_SHARED_BOUND_CAMERA_PROPERTY_NAME = "bound_camera" SESSION_SHARED_FOLLOWING_USER_PROPERTY_NAME = "following_user" SESSION_SHARED_SELECTION_PROPERTY_NAME = "selected_prim_paths" SHARED_BUILT_IN_CAMERA_LIST = [ SESSION_SHARED_PERSPECTIVE_CAMERA_NAME, SESSION_SHARED_FRONT_CAMERA_NAME, SESSION_SHARED_LEFT_CAMERA_NAME, SESSION_SHARED_RIGHT_CAMERA_NAME ] LOCAL_BUILT_IN_CAMERA_PATH_TO_SHARED_NAME = { Sdf.Path("/OmniverseKit_Persp"): SESSION_SHARED_PERSPECTIVE_CAMERA_NAME, Sdf.Path("/OmniverseKit_Top"): SESSION_SHARED_FRONT_CAMERA_NAME, Sdf.Path("/OmniverseKit_Front"): SESSION_SHARED_LEFT_CAMERA_NAME, Sdf.Path("/OmniverseKit_Right"): SESSION_SHARED_RIGHT_CAMERA_NAME, } SHARED_NAME_TO_LOCAL_BUILT_IN_CAMERA_PATH = { SESSION_SHARED_PERSPECTIVE_CAMERA_NAME: Sdf.Path("/OmniverseKit_Persp"), SESSION_SHARED_FRONT_CAMERA_NAME: Sdf.Path("/OmniverseKit_Top"), SESSION_SHARED_LEFT_CAMERA_NAME: Sdf.Path("/OmniverseKit_Front"), SESSION_SHARED_RIGHT_CAMERA_NAME: Sdf.Path("/OmniverseKit_Right"), } LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH = Sdf.Path("/OmniverseLiveSessionSharedData") LAYER_SUBSCRIPTION_ORDER = -1 << 31 # make sure this runs before anything else
1,544
Python
40.756756
87
0.750648
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["PresenceLayerAPI", "get_presence_layer_interface", "PresenceLayerExtension"] import carb import omni.ext import omni.usd from .presence_layer_manager import PresenceLayerManager, PresenceLayerAPI from typing import Dict, Union, List __all_presence_layer_apis: Dict[omni.usd.UsdContext, PresenceLayerAPI] = {} __all_presence_managers: List[PresenceLayerManager] = [] def shutdown_all(): global __all_presence_layer_apis global __all_presence_managers for presence_layer in __all_presence_managers: presence_layer.stop() __all_presence_layer_apis.clear() __all_presence_managers.clear() def get_presence_layer_interface( context_name_or_instance: Union[str, omni.usd.UsdContext] = "" ) -> Union[PresenceLayerAPI, None]: """ Gets PresenceLayerAPI interface bound to the context. For each UsdContext, it has unique PresenceLayerAPI instance, through which, you can access all the interfaces supported. PresenceLayerAPI provides the APIs that serve for easy access to data of presence layer, where presence layer is the transport layer that works for exchange persistent data for all users in the Live Session of the bound UsdContext. It only supports Live Session of root layer for now. """ global __all_presence_layer_apis if not context_name_or_instance: context_name_or_instance = "" if isinstance(context_name_or_instance, str): usd_context = omni.usd.get_context(context_name_or_instance) elif isinstance(context_name_or_instance, omni.usd.UsdContext): usd_context = context_name_or_instance else: carb.log_warn("Failed to get presence layer interface since the param must be name or instance of UsdContext.") return None if not usd_context: carb.log_warn("Failed to query presence layer interface since UsdContext cannot be found.") return None presence_layer_api = __all_presence_layer_apis.get(usd_context, None) if not presence_layer_api: presence_layer = PresenceLayerManager(usd_context) presence_layer.start() __all_presence_managers.append(presence_layer) presence_layer_api = PresenceLayerAPI(presence_layer) __all_presence_layer_apis[usd_context] = presence_layer_api return presence_layer_api class PresenceLayerExtension(omni.ext.IExt): def on_startup(self): # Initialize presence layer for default context. get_presence_layer_interface() def on_shutdown(self): shutdown_all()
2,979
Python
36.25
119
0.728432
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/utils.py
import carb from .constants import * from pxr import Sdf, Usd, UsdGeom class CarbProfilerScope: # pragma: no cover def __init__(self, id, name): self._id = id self._name = name def __enter__(self): carb.profiler.begin(self._id, self._name) def __exit__(self, type, value, trace): carb.profiler.end(self._id) @carb.profiler.profile def get_user_id_from_path(path: Sdf.Path): prefixes = path.GetPrefixes() if len(prefixes) < 2: return None # "/{SESSION_SHARED_LAYER_ROOT_NAME}/_{self.user_id}" # Premove the prefix _ to get real user id. user_id = prefixes[1].name[1:] return user_id def is_local_builtin_camera(path: Sdf.Path): """ Checkes if it's local builtin camera. If so, it will return the corresponding builtin camera name for bound camera property. """ path = Sdf.Path(path) return LOCAL_BUILT_IN_CAMERA_PATH_TO_SHARED_NAME.get(path, None) def get_user_shared_root_path(user_id: str) -> Sdf.Path: # The prefix "_" is used to make sure the id is valid for identifier return SESSION_SHARED_LAYER_ROOT_PATH.AppendElementString(f"_{user_id}") def get_bound_camera_property_path(user_id: str) -> Sdf.Path: shared_root_path = get_user_shared_root_path(user_id) return shared_root_path.AppendProperty(SESSION_SHARED_BOUND_CAMERA_PROPERTY_NAME) def get_selection_property_path(user_id: str) -> Sdf.Path: shared_root_path = get_user_shared_root_path(user_id) return shared_root_path.AppendProperty(SESSION_SHARED_SELECTION_PROPERTY_NAME) def get_following_user_property_path(user_id: str) -> Sdf.Path: shared_root_path = get_user_shared_root_path(user_id) return shared_root_path.AppendProperty(SESSION_SHARED_FOLLOWING_USER_PROPERTY_NAME) def get_or_create_property_spec(layer, property_path, typename, is_custom=True): property_spec = layer.GetAttributeAtPath(property_path) if property_spec and property_spec.typeName != typename: carb.log_verboase(f"Type of property {property_spec} does not match: {property_spec.typeName}, {typename}.") prim_spec = layer.GetPrimAtPath(property_path.GetPrimPath()) if prim_spec: prim_spec.RemoveProperty(property_spec) property_spec = None if not property_spec: Sdf.JustCreatePrimAttributeInLayer( layer, property_path, typename, isCustom=is_custom ) property_spec = layer.GetAttributeAtPath(property_path) return property_spec
2,521
Python
30.135802
116
0.686632
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/presence_layer_manager.py
import asyncio import carb import time import omni.client import omni.usd import omni.kit.usd.layers as layers import omni.kit.app from omni.kit.async_engine import run_coroutine from pxr import Sdf, Usd, UsdGeom, Tf, Trace, Gf from typing import Dict, List, Union, Set from .utils import ( get_user_id_from_path, get_bound_camera_property_path, get_following_user_property_path, get_selection_property_path, get_user_shared_root_path, get_or_create_property_spec, is_local_builtin_camera ) from .event import PresenceLayerEventType, EVENT_PAYLOAD_KEY from .constants import * from .peer_user_shared_data import PeerUserSharedData class PresenceLayerChanges: def __init__(self) -> None: self.clear() def clear(self): self.bound_camera_changed_ids = set() self.selection_changed_ids = set() self.following_user_changed_ids = set() self.camera_info_changes = {} self.resynced_camera_ids = set() def is_empty(self): return ( not self.bound_camera_changed_ids and not self.selection_changed_ids and not self.following_user_changed_ids and not self.camera_info_changes and not self.resynced_camera_ids ) def add_camera_info_change(self, user_id, path): changes = self.camera_info_changes.get(user_id, None) if changes is None: self.camera_info_changes[user_id] = set() # Changed property name self.camera_info_changes[user_id].add(path.name) def __str__(self): return (f"Bound Camera Changed: {self.bound_camera_changed_ids}, " f"Seletion Changed: {self.selection_changed_ids}, " f"Following User Changed: {self.following_user_changed_ids}, " f"Camera Info Changed: {self.camera_info_changes}, " f"Camera Resynced: {self.resynced_camera_ids}") class PresenceLayerManager: def __init__(self, usd_context): self.__usd_context = usd_context self.__live_syncing = layers.get_live_syncing(self.__usd_context) self.__layers = layers.get_layers(self.__usd_context) self.__shared_data_stage = None self.__peer_users: Dict[str, PeerUserSharedData] = {} # Fast access to query the follow relationship. Key is the # user id that's followed, and values are the user ids that # are currently following this user. self.__user_following_map: Dict[str, Set[str]] = {} self.__layers_event_subscriptions = [] self.__stage_event_subscription = None self.__shared_stage_objects_changed = None self.__delayed_changes_handle_task = None self.__local_following_user_id = None self.__pending_changed_paths = set() def start(self): for event in [ layers.LayerEventType.LIVE_SESSION_STATE_CHANGED, layers.LayerEventType.LIVE_SESSION_USER_JOINED, layers.LayerEventType.LIVE_SESSION_USER_LEFT, layers.LayerEventType.LIVE_SESSION_MERGE_ENDED, ]: layers_event_sub = self.__layers.get_event_stream().create_subscription_to_pop_by_type( event, self.__on_layers_event, name=f"Layers event: omni.kit.collaboration.presence_layer {str(event)}", order=LAYER_SUBSCRIPTION_ORDER ) self.__layers_event_subscriptions.append(layers_event_sub) self.__stage_event_subscription = self.__usd_context.get_stage_event_stream().create_subscription_to_pop( self.__on_stage_event, name="Stage event: omni.kit.collaboration.presence_layer" ) stage_url = self.__usd_context.get_stage_url() if not stage_url.startswith("omniverse:"): return self.__on_session_state_changed() def __on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self.__on_selection_changed() elif event.type == int(omni.usd.StageEventType.CLOSING): self.__stop_subscription() def __on_selection_changed(self): if not self.__shared_data_stage: return selection = self.__usd_context.get_selection() selected_prim_paths = selection.get_selected_prim_paths() or [] current_session = self.__live_syncing.get_current_live_session() if not current_session: return logged_user_id = current_session.logged_user_id selection_property_path = get_selection_property_path(logged_user_id) with Sdf.ChangeBlock(): property_spec = get_or_create_property_spec( self.__shared_data_stage.GetRootLayer(), selection_property_path, Sdf.ValueTypeNames.StringArray ) property_spec.default = selected_prim_paths def __start_subscription(self): # Skip it if one of its sublayer is in live session already. if self.__shared_data_stage: return current_session = self.__live_syncing.get_current_live_session() if not current_session: return self.__shared_data_stage = self.__create_or_open_shared_stage(current_session) if not self.__shared_data_stage: return self.__shared_stage_objects_changed = Tf.Notice.Register( Usd.Notice.ObjectsChanged, self.__on_shared_usd_changed, self.__shared_data_stage ) stage = self.__usd_context.get_stage() target_layer = stage.GetSessionLayer() with Usd.EditContext(stage, target_layer): prim = stage.DefinePrim(LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH, "Scope") omni.usd.editor.set_hide_in_stage_window(prim, True) omni.usd.editor.set_hide_in_ui(prim, True) for peer_user in current_session.peer_users: self.__track_new_user(peer_user.user_id) def __stop_subscription(self): for peer_user in self.__peer_users.values(): peer_user.destroy() self.__peer_users.clear() self.__pending_changed_paths.clear() self.__shared_data_stage = None if self.__shared_stage_objects_changed: self.__shared_stage_objects_changed.Revoke() self.__shared_stage_objects_changed = None if self.__delayed_changes_handle_task: self.__delayed_changes_handle_task.cancel() self.__delayed_changes_handle_task = None local_stage = self.__usd_context.get_stage() if local_stage: layers.LayerUtils.remove_prim_spec( local_stage.GetSessionLayer(), LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH ) self.__user_following_map.clear() def stop(self): self.__stop_subscription() self.__layers_event_subscriptions = [] self.__stage_event_subscription = None @carb.profiler.profile def __notify_changes(self, pending_changes): if pending_changes.is_empty(): return event_stream = layers.get_layers(self.__usd_context).get_event_stream() if not event_stream: return def __check_and_send_events(event_type, changed_ids, lambda_filter): valid_users = [] for user_id in changed_ids: peer_user = self.__peer_users.get(user_id, None) if not peer_user or not lambda_filter(peer_user): continue valid_users.append(user_id) if valid_users: event_stream.push(int(event_type), 0, {EVENT_PAYLOAD_KEY: valid_users}) return valid_users all_bound_camera_changed_ids = set() for user_id in pending_changes.following_user_changed_ids: peer_user = self.__peer_users.get(user_id, None) if not peer_user or not peer_user.update_following_user(): continue old_following_user_id = peer_user.following_user_id if old_following_user_id: self.__remove_following_user(user_id, old_following_user_id) new_following_user_id = peer_user.following_user_id if new_following_user_id: self.__track_following_user(user_id, new_following_user_id) all_bound_camera_changed_ids.add(user_id) for user_id in pending_changes.bound_camera_changed_ids: peer_user = self.__peer_users.get(user_id, None) if not peer_user or not peer_user.update_bound_camera(): continue all_bound_camera_changed_ids.add(user_id) # Updates all users that are currently following this user also. all_bound_camera_changed_ids.update(self.get_all_following_users(user_id)) if all_bound_camera_changed_ids: event_stream.push( int(PresenceLayerEventType.BOUND_CAMERA_CHANGED), 0, {EVENT_PAYLOAD_KEY: list(all_bound_camera_changed_ids)} ) __check_and_send_events( PresenceLayerEventType.BOUND_CAMERA_RESYNCED, pending_changes.resynced_camera_ids, lambda user: True ) __check_and_send_events( PresenceLayerEventType.SELECTIONS_CHANGED, pending_changes.selection_changed_ids, lambda user: user.update_selections() ) camera_info_changes = pending_changes.camera_info_changes if camera_info_changes: # FIXME: WA to make sure changes can be serialized to event stream. camera_changes_payload = {} with Sdf.ChangeBlock(): for user_id, property_names in camera_info_changes.items(): peer_user = self.__peer_users.get(user_id, None) if property_names: peer_user.replicate_bound_camera_to_local(property_names) camera_changes_payload[user_id] = list(property_names) event_stream.push( int(PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED), payload=camera_changes_payload ) @carb.profiler.profile async def __handling_pending_changes(self): pending_changes = PresenceLayerChanges() pending_changed_paths = self.__pending_changed_paths self.__pending_changed_paths = set() for path in pending_changed_paths: if path == SESSION_SHARED_LAYER_ROOT_PATH or path == Sdf.Path.absoluteRootPath: pending_changes.bound_camera_changed_ids.update(self.__peer_users.keys()) pending_changes.following_user_changed_ids.update(self.__peer_users.keys()) pending_changes.selection_changed_ids.update(self.__peer_users.keys()) pending_changes.resynced_camera_ids.update(self.__peer_users.keys()) break user_id = get_user_id_from_path(path) peer_user = self.__peer_users.get(user_id) if not peer_user: continue if path == peer_user.shared_root_path: pending_changes.bound_camera_changed_ids.add(user_id) pending_changes.following_user_changed_ids.add(user_id) pending_changes.selection_changed_ids.add(user_id) pending_changes.resynced_camera_ids.add(user_id) continue # Checkes bound_camera property under user root if peer_user.is_following_user_property_affected(path): pending_changes.following_user_changed_ids.add(user_id) elif peer_user.is_selection_property_affected(path): pending_changes.selection_changed_ids.add(user_id) elif peer_user.is_bound_camera_property_affected(path): pending_changes.bound_camera_changed_ids.add(user_id) elif peer_user.is_builtin_camera_affected(path): # Only sync properties that are under camera prim. if path.IsPropertyPath(): pending_changes.add_camera_info_change(user_id, path) else: pending_changes.resynced_camera_ids.add(user_id) self.__notify_changes(pending_changes) self.__delayed_changes_handle_task = None @carb.profiler.profile def __on_shared_usd_changed(self, notice, sender): if not sender or sender != self.__shared_data_stage: return self.__pending_changed_paths.update(notice.GetResyncedPaths()) self.__pending_changed_paths.update(notice.GetChangedInfoOnlyPaths()) if not self.__pending_changed_paths: return if not self.__delayed_changes_handle_task or self.__delayed_changes_handle_task.done(): self.__delayed_changes_handle_task = run_coroutine(self.__handling_pending_changes()) def __create_or_open_shared_stage(self, session: layers.LiveSession): session_url = session.url if not session_url.endswith("/"): session_url += "/" shared_data_layer_path = omni.client.combine_urls(session_url, SESSION_SHARED_USER_LAYER) layer = Sdf.Layer.FindOrOpen(shared_data_layer_path) if not layer: layer = Sdf.Layer.CreateNew(shared_data_layer_path) if not layer: carb.log_warn(f"Failed to open shared data layer {shared_data_layer_path}.") return None Sdf.CreatePrimInLayer(layer, SESSION_SHARED_LAYER_ROOT_PATH) stage = Usd.Stage.Open(layer) return stage @property def shared_data_stage(self) -> Usd.Stage: return self.__shared_data_stage def __on_session_state_changed(self): if not self.__live_syncing.is_in_live_session(): self.__stop_subscription() else: self.__start_subscription() def __track_new_user(self, user_id): if user_id in self.__peer_users: return if not self.__shared_data_stage: return current_session = self.__live_syncing.get_current_live_session() if not current_session: return user_info = current_session.get_peer_user_info(user_id) if not user_info: return peer_user = PeerUserSharedData(self.__usd_context, self.__shared_data_stage, user_info) self.__peer_users[user_id] = peer_user following_user_id = peer_user.following_user_id if following_user_id: self.__track_following_user(user_id, following_user_id) def __track_following_user(self, user_id, following_user_id): user_ids = self.__user_following_map.get(following_user_id, None) if not user_ids: user_ids = set() self.__user_following_map[following_user_id] = user_ids user_ids.add(user_id) def __untrack_followed_user(self, user_id): for following_users in self.__user_following_map.values(): following_users.discard(user_id) self.__user_following_map.pop(user_id, None) def __remove_following_user(self, user_id, followed_user_id): """Removes user_id from list that are currently following followed_user_id.""" user_list = self.__user_following_map.get(followed_user_id, None) if not user_list: return False if user_id in user_list: user_list.discard(user_id) return True return False def __untrack_user(self, user_id): self.__untrack_followed_user(user_id) peer_user = self.__peer_users.pop(user_id, None) if peer_user: peer_user.destroy() def __on_layers_event(self, event): payload = layers.get_layer_event_payload(event) if not payload: return interested_events = [ layers.LayerEventType.LIVE_SESSION_STATE_CHANGED, layers.LayerEventType.LIVE_SESSION_USER_JOINED, layers.LayerEventType.LIVE_SESSION_USER_LEFT, layers.LayerEventType.LIVE_SESSION_MERGE_ENDED ] if payload.event_type not in interested_events: return if not payload.is_layer_influenced(self.__usd_context.get_stage_url()): return if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED: self.__on_session_state_changed() elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED: # Creates user shared data # Try to copy camera info and add widgets for the bound camera. self.__track_new_user(payload.user_id) elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT: self.__untrack_user(payload.user_id) elif payload.event_type == layers.LayerEventType.LIVE_SESSION_MERGE_ENDED: if payload.success: self.__shared_data_stage.GetRootLayer().Clear() def get_all_following_users(self, followed_user_id): """Get all user ids that are currently following followed_user_id.""" return self.__user_following_map.get(followed_user_id, set()) def get_bound_camera_prim(self, user_id) -> Union[Usd.Prim, None]: live_syncing = self.__live_syncing current_session = live_syncing.get_current_live_session() accessed_user_ids = set() usd_prim = None while True: # To avoid A follows B and B follows A if user_id in accessed_user_ids: break accessed_user_ids.add(user_id) peer_user = self.__peer_users.get(user_id, None) if not peer_user: break usd_prim = peer_user.get_bound_camera_prim() if usd_prim: break # It's following other users. user_id = self.get_following_user_id(user_id) # If it's following me. if user_id == current_session.logged_user_id: accessed_user_ids.add(user_id) shared_data_stage = self.__shared_data_stage current_stage = self.__usd_context.get_stage() my_bound_camera_property_path = get_bound_camera_property_path(user_id) camera_path_property = shared_data_stage.GetRootLayer().GetAttributeAtPath( my_bound_camera_property_path ) if camera_path_property: bound_camera_path = str(camera_path_property.default).strip() # Maps builin camera binding to local path or keep it intact. bound_camera_path = SHARED_NAME_TO_LOCAL_BUILT_IN_CAMERA_PATH.get( bound_camera_path, bound_camera_path ) if bound_camera_path: usd_prim = current_stage.GetPrimAtPath(bound_camera_path) break # Otherwise, checking local Kit is following other user to pass the ball. my_following_user_property_path = get_following_user_property_path(user_id) following_user_property = shared_data_stage.GetRootLayer().GetAttributeAtPath( my_following_user_property_path ) if not following_user_property: break user_id = str(following_user_property.default).strip() if not user_id or not current_session.get_peer_user_info(user_id): break return usd_prim def is_bound_to_builtin_camera(self, user_id): peer_user = self.__peer_users.get(user_id, None) if not peer_user: return False return peer_user.is_bound_to_builtin_camera() def get_following_user_id(self, user_id: str = None) -> str: """Gets the user id that the specific user is currently following.""" live_syncing = self.__live_syncing current_session = live_syncing.get_current_live_session() if not current_session: return None if user_id is None: user_id = current_session.logged_user_id # Local user is handled differently as peer users. if user_id == current_session.logged_user_id: following_user_property_path = get_following_user_property_path(current_session.logged_user_id) following_user_property = self.__shared_data_stage.GetRootLayer().GetAttributeAtPath( following_user_property_path ) if following_user_property: following_user_id = str(following_user_property.default).strip() if following_user_id and following_user_id in self.__peer_users: return following_user_id peer_user = self.__peer_users.get(user_id, None) if not peer_user: return None # Ensure the following user id is currently in the live session. following_user = self.__peer_users.get(peer_user.following_user_id, None) logged_user_id = current_session.logged_user_id if following_user or peer_user.following_user_id == logged_user_id: return peer_user.following_user_id return None def is_user_followed_by(self, user_id: str, followed_by_user_id: str) -> str: following_user_id = self.get_following_user_id(followed_by_user_id) return following_user_id == user_id def get_selections(self, user_id: str) -> List[Sdf.Path]: peer_user = self.__peer_users.get(user_id, None) if not peer_user: return None return peer_user.selections def broadcast_local_bound_camera(self, local_camera_path: Sdf.Path): if not local_camera_path: local_camera_path = Sdf.Path.emptyPath else: local_camera_path = Sdf.Path(local_camera_path) shared_data_stage = self.__shared_data_stage if not shared_data_stage: return live_syncing = self.__live_syncing current_session = live_syncing.get_current_live_session() if not current_session: return # If camera does not exist if local_camera_path: current_stage = self.__usd_context.get_stage() camera_prim = current_stage.GetPrimAtPath(local_camera_path) if not camera_prim or not UsdGeom.Camera(camera_prim): carb.log_error(f"Cannot sync camera {local_camera_path} to presence layer as it does not exist.") return logged_user_id = current_session.logged_user_id bound_camera_property_path = get_bound_camera_property_path(logged_user_id) following_user_property_path = get_following_user_property_path(logged_user_id) local_builtin_camera = is_local_builtin_camera(local_camera_path) camera_path = local_builtin_camera or local_camera_path # It's local builtin camera path or stage camera. camera_path = str(camera_path) if camera_path else "" with Sdf.ChangeBlock(): # Only synchronizes builtin camera as non-builtin cameras are visible to all users already. if local_builtin_camera: user_shared_root = get_user_shared_root_path(logged_user_id) shared_camera_prim_path = user_shared_root.AppendElementString(local_builtin_camera) Sdf.CreatePrimInLayer(shared_data_stage.GetRootLayer(), shared_camera_prim_path) Sdf.CopySpec( current_stage.GetSessionLayer(), local_camera_path, shared_data_stage.GetRootLayer(), shared_camera_prim_path ) property_spec = get_or_create_property_spec( shared_data_stage.GetRootLayer(), bound_camera_property_path, Sdf.ValueTypeNames.String ) property_spec.default = camera_path property_spec = get_or_create_property_spec( shared_data_stage.GetRootLayer(), following_user_property_path, Sdf.ValueTypeNames.String ) property_spec.default = "" # Notify all users that are currently following the local user. event_stream = layers.get_layers(self.__usd_context).get_event_stream() all_bound_camera_changed_ids = set() all_bound_camera_changed_ids.update(self.get_all_following_users(logged_user_id)) if all_bound_camera_changed_ids: event_stream.push( int(PresenceLayerEventType.BOUND_CAMERA_CHANGED), 0, {EVENT_PAYLOAD_KEY: list(all_bound_camera_changed_ids)} ) def __set_following_user_id_property(self, following_user_id): """Broadcasts local user's following id.""" shared_data_stage = self.__shared_data_stage if not shared_data_stage: return False live_syncing = self.__live_syncing current_session = live_syncing.get_current_live_session() if not current_session: return False logged_user_id = current_session.logged_user_id following_user_property_path = get_following_user_property_path(logged_user_id) bound_camera_property_path = get_bound_camera_property_path(logged_user_id) with Sdf.ChangeBlock(): property_spec = get_or_create_property_spec( shared_data_stage.GetRootLayer(), bound_camera_property_path, Sdf.ValueTypeNames.String ) if following_user_id: property_spec.default = "" else: # Quits to perspective camera by default. property_spec.default = "/OmniverseKit_Persp" property_spec = get_or_create_property_spec( shared_data_stage.GetRootLayer(), following_user_property_path, Sdf.ValueTypeNames.String ) property_spec.default = following_user_id if self.__local_following_user_id: self.__remove_following_user(logged_user_id, self.__local_following_user_id) self.__local_following_user_id = following_user_id if following_user_id: self.__track_following_user(logged_user_id, following_user_id) return True def enter_follow_mode(self, following_user_id: str): live_syncing = self.__live_syncing current_session = live_syncing.get_current_live_session() if not current_session: carb.log_warn(f"Cannot follow user {following_user_id} as it's not in a live session.") return False if current_session.logged_user_id == following_user_id: carb.log_warn("Cannot follow myself.") return False following_user = self.__peer_users.get(following_user_id, None) if not following_user: carb.log_warn(f"Cannot follow user {following_user_id} as the user does not exist in the session.") return False if not self.get_bound_camera_prim(following_user_id): message = f"Cannot follow user {following_user.user_name} as the user does not share bound camera." 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 False # If user is already following me or other users, reports errors. if ( following_user.following_user_id and ( following_user.following_user_id == current_session.logged_user_id or following_user.following_user_id in self.__peer_users ) ): carb.log_warn(f"Cannot follow user {following_user.user_name} as the user is in following mode.") return False if self.get_following_user_id() == following_user_id: return True event_stream = layers.get_layers(self.__usd_context).get_event_stream() if self.__set_following_user_id_property(following_user_id): event_stream.dispatch(PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED) return True return False def quit_follow_mode(self): live_syncing = self.__live_syncing current_session = live_syncing.get_current_live_session() if not current_session: return False if self.is_in_following_mode(current_session.logged_user_id): event_stream = layers.get_layers(self.__usd_context).get_event_stream() if self.__set_following_user_id_property(""): event_stream.dispatch(PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED) def can_follow(self, user_id): following_user = self.__peer_users.get(user_id, None) return not following_user or following_user.following_user_id def is_in_following_mode(self, user_id: str = None) -> bool: """ Checkes if the user is following other user. user_id (str): The user id to check. By default, it's None, which means to check if local user is in follow mode. """ live_syncing = self.__live_syncing current_session = live_syncing.get_current_live_session() if not current_session: return False if user_id is None: user_id = current_session.logged_user_id following_user_id = self.get_following_user_id(user_id) if following_user_id: return True else: return False class PresenceLayerAPI: """ Presence layer is the transport layer that works for exchange persistent data for all users in the same Live Session. PresenceLayerAPI provides the APIs that serve for easy access to data of presence layer. """ def __init__(self, presence_layer_instance: PresenceLayerManager) -> None: self.__presence_layer_instance = presence_layer_instance def is_bound_to_builtin_camera(self, user_id): """ Checkes if peer user is bound to builtin camera. If peer user is following other user, it will always return False. """ return self.__presence_layer_instance.is_bound_to_builtin_camera(user_id) @carb.profiler.profile def get_bound_camera_prim(self, user_id) -> Union[Usd.Prim, None]: """ Gets the bound camera of the peer user in the local stage. If peer user is following other user, it will return the bound camera of the following user. """ return self.__presence_layer_instance.get_bound_camera_prim(user_id) def get_following_user_id(self, user_id: str = None) -> str: """ Gets the user id that the specific user is currently following. user_id (str): User id, includes both local and peer users. If it's None, it will return the user id that local user is currently following. """ return self.__presence_layer_instance.get_following_user_id(user_id) def is_user_followed_by(self, user_id: str, followed_by_user_id: str) -> str: """ Checkes if user is followed by other specific user. Args: user_id (str): The user id to query. followed_by_user_id (str): The user that's following the one has user_id. """ return self.__presence_layer_instance.is_user_followed_by(user_id, followed_by_user_id) def get_selections(self, user_id: str) -> List[Sdf.Path]: """Gets the prim paths that the user selects.""" return self.__presence_layer_instance.get_selections(user_id) @carb.profiler.profile def broadcast_local_bound_camera(self, local_camera_path: Sdf.Path): """ Broadcasts local bound camera to presence layer. Local application can be either in bound camera mode or following user mode. Switching bound camera will quit following user mode. """ return self.__presence_layer_instance.broadcast_local_bound_camera(local_camera_path) @carb.profiler.profile def enter_follow_mode(self, following_user_id: str): """ Try to follow user from local. Local application can be either in bound camera mode or following user mode. Switching bound camera will quit following user mode. If the user specified by following_user_id is in following mode already, this function will return False. Args: following_user_id (str): The user id that local user is trying to follow. """ return self.__presence_layer_instance.enter_follow_mode(following_user_id) def quit_follow_mode(self): self.__presence_layer_instance.quit_follow_mode() def can_follow(self, user_id): """If the specified peer user can be followed.""" return self.__presence_layer_instance.can_follow(user_id) def is_in_following_mode(self, user_id: str = None): """ Checkes if the user is following other user. user_id (str): User id, including both the local and peer users. By default, it's None, which means to check if local user is in follow mode. """ return self.__presence_layer_instance.is_in_following_mode(user_id) def get_shared_data_stage(self): return self.__presence_layer_instance.shared_data_stage
33,571
Python
38.589623
121
0.613446
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/tests/__init__.py
from .test_presence_layer import *
34
Python
33.999966
34
0.794118
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/tests/test_presence_layer.py
import carb import omni.kit.test import omni.usd import omni.client import unittest import omni.kit.app import carb.settings import omni.kit.collaboration.presence_layer as pl import omni.kit.collaboration.presence_layer.utils as pl_utils import omni.kit.usd.layers as layers from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi from pxr import Usd, Sdf from typing import List class TestPresenceLayer(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self.app = omni.kit.app.get_app() self.usd_context = omni.usd.get_context() self.layers = layers.get_layers(self.usd_context) self.live_syncing = layers.get_live_syncing(self.usd_context) self.local_builtin_cameras = [ "/OmniverseKit_Persp", "/OmniverseKit_Front", "/OmniverseKit_Top", "/OmniverseKit_Right" ] await omni.usd.get_context().new_stage_async() self.simulated_user_name = "test" self.simulated_user_id = "abcde" self.simulated_user_name2 = "test2" self.simulated_user_id2 = "abcdef" async def tearDown(self): pass async def wait(self, frames=10): for i in range(frames): await self.app.next_update_async() async def __create_session_and_simulate_users(self): session = self.live_syncing.find_live_session_by_name(self.stage_url, "test") if not session: session = self.live_syncing.create_live_session("test", self.stage_url) self.assertTrue(session, "Failed to create live session.") self.assertTrue(self.live_syncing.join_live_session(session)) await self.wait() # Access private variable to simulate user login. user = layers.LiveSessionUser(self.simulated_user_name, self.simulated_user_id, "Create") user2 = layers.LiveSessionUser(self.simulated_user_name2, self.simulated_user_id2, "Create") current_session = self.live_syncing.get_current_live_session() session_channel = current_session._session_channel() session_channel._peer_users[self.simulated_user_id] = user session_channel._peer_users[self.simulated_user_id2] = user2 session_channel._send_layer_event( layers.LayerEventType.LIVE_SESSION_USER_JOINED, {"user_name": self.simulated_user_name, "user_id": self.simulated_user_id} ) session_channel._send_layer_event( layers.LayerEventType.LIVE_SESSION_USER_JOINED, {"user_name": self.simulated_user_name2, "user_id": self.simulated_user_id2} ) await self.wait() def __get_shared_stage(self, current_session: layers.LiveSession): shared_data_stage_url = current_session.url + "/shared_data/users.live" layer = Sdf.Layer.FindOrOpen(shared_data_stage_url) if not layer: layer = Sdf.Layer.CreateNew(shared_data_stage_url) return Usd.Stage.Open(layer) async def __bound_camera(self, shared_stage: Usd.Stage, user_id: str, camera_path: Sdf.Path): if not camera_path: camera_path = Sdf.Path.emptyPath camera_path = Sdf.Path(camera_path) bound_camera_property_path = pl_utils.get_bound_camera_property_path(user_id) property_spec = pl_utils.get_or_create_property_spec( shared_stage.GetRootLayer(), bound_camera_property_path, Sdf.ValueTypeNames.String ) builtin_camera_name = pl_utils.is_local_builtin_camera(camera_path) if not builtin_camera_name: property_spec.default = str(camera_path) else: property_spec.default = builtin_camera_name if builtin_camera_name: persp_camera = pl_utils.get_user_shared_root_path(user_id).AppendChild(builtin_camera_name) camera_prim = shared_stage.DefinePrim(persp_camera, "Camera") await self.wait() async def __select_prims(self, shared_stage: Usd.Stage, user_id: str, selections: List[str]): selection_property_path = pl_utils.get_selection_property_path(user_id) property_spec = pl_utils.get_or_create_property_spec( shared_stage.GetRootLayer(), selection_property_path, Sdf.ValueTypeNames.StringArray ) property_spec.default = selections await self.wait() async def __follow_user( self, shared_stage: Usd.Stage, user_id: str, following_user_id: str ): following_user_property_path = pl_utils.get_following_user_property_path(user_id) property_spec = pl_utils.get_or_create_property_spec( shared_stage.GetRootLayer(), following_user_property_path, Sdf.ValueTypeNames.String ) property_spec.default = following_user_id await self.wait() @MockLiveSyncingApi async def test_api(self): self.stage_url = "omniverse://__faked_omniverse_server__/test/test.usd" format = Sdf.FileFormat.FindByExtension(".usd") layer = Sdf.Layer.New(format, self.stage_url) stage = Usd.Stage.Open(layer) await self.usd_context.attach_stage_async(stage) self.all_camera_paths = [] for i in range(10): camera_path = Sdf.Path(f"/Camera{i}") stage.DefinePrim(camera_path, "Camera") self.all_camera_paths.append(camera_path) # Simulated builtin cameras with Usd.EditContext(stage, stage.GetSessionLayer()): for camera_path in self.local_builtin_cameras: stage.DefinePrim(camera_path, "Camera") self.all_camera_paths.append(camera_path) def _on_layers_event(event): nonlocal payload p = pl.get_presence_layer_event_payload(event) if p.event_type: payload = p subscription = self.layers.get_event_stream().create_subscription_to_pop( _on_layers_event, name="omni.kit.collaboration.presence_layer.tests" ) await self.__create_session_and_simulate_users() current_live_session = self.live_syncing.get_current_live_session() shared_stage = self.__get_shared_stage(current_live_session) self.assertTrue(shared_stage) presence_layer = pl.get_presence_layer_interface(self.usd_context) # Simulated user has empty camera bound at start. self.assertFalse(presence_layer.is_bound_to_builtin_camera(self.simulated_user_id)) self.assertFalse(presence_layer.get_bound_camera_prim(self.simulated_user_id)) self.assertFalse(presence_layer.get_following_user_id(self.simulated_user_id)) self.assertFalse(presence_layer.get_selections(self.simulated_user_id)) # Bound to invalid camera for camera_path in ["/nonexisted", ""]: await self.__bound_camera(shared_stage, self.simulated_user_id, camera_path) self.assertTrue(payload) self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED) self.assertFalse(presence_layer.is_bound_to_builtin_camera(self.simulated_user_id)) self.assertFalse(presence_layer.get_bound_camera_prim(self.simulated_user_id)) payload = None # Bound to valid camera for camera_path in self.all_camera_paths: camera_path = Sdf.Path(camera_path) is_builtin_camera = pl_utils.is_local_builtin_camera(camera_path) is not None await self.__bound_camera(shared_stage, self.simulated_user_id, camera_path) self.assertTrue(payload) self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED, camera_path) self.assertEqual(presence_layer.is_bound_to_builtin_camera(self.simulated_user_id), is_builtin_camera, camera_path) self.assertTrue(presence_layer.get_bound_camera_prim(self.simulated_user_id), camera_path) # Selections for selections in [["/test", "/test2"], [], ["/test", "/test2", "test3"]]: payload = None await self.__select_prims(shared_stage, self.simulated_user_id, selections) self.assertTrue(payload) self.assertEqual(payload.event_type, pl.PresenceLayerEventType.SELECTIONS_CHANGED) self.assertEqual(presence_layer.get_selections(self.simulated_user_id), selections, selections) # Following user # Setups default camera logged_user_id = current_live_session.logged_user_id presence_layer.broadcast_local_bound_camera("/OmniverseKit_Persp") await self.__bound_camera(shared_stage, self.simulated_user_id2, self.all_camera_paths[0]) for user_id in [logged_user_id, self.simulated_user_id2]: payload = None await self.__follow_user(shared_stage, self.simulated_user_id, user_id) self.assertTrue(payload) self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED) self.assertEqual(presence_layer.get_following_user_id(self.simulated_user_id), user_id) self.assertTrue(presence_layer.is_user_followed_by(user_id, self.simulated_user_id)) self.assertTrue(presence_layer.get_bound_camera_prim(self.simulated_user_id)) user_id = "invalid_user_id" payload = None await self.__follow_user(shared_stage, self.simulated_user_id, user_id) self.assertTrue(payload) self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED) self.assertFalse(presence_layer.get_bound_camera_prim(self.simulated_user_id)) self.assertFalse(presence_layer.is_in_following_mode(self.simulated_user_id), user_id) self.assertFalse(presence_layer.is_user_followed_by(user_id, self.simulated_user_id)) await self.__follow_user(shared_stage, self.simulated_user_id, "") payload = None self.assertFalse(presence_layer.enter_follow_mode(logged_user_id)) self.assertTrue(presence_layer.enter_follow_mode(self.simulated_user_id)) await self.wait() self.assertTrue(payload) self.assertEqual(payload.event_type, pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED) self.assertEqual(presence_layer.get_following_user_id(), self.simulated_user_id) self.assertTrue(presence_layer.is_in_following_mode(logged_user_id)) self.assertTrue(presence_layer.is_user_followed_by(self.simulated_user_id, logged_user_id)) payload = None presence_layer.quit_follow_mode() await self.wait() self.assertTrue(payload) self.assertEqual(payload.event_type, pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED) self.assertFalse(presence_layer.get_following_user_id()) self.assertFalse(presence_layer.is_in_following_mode(logged_user_id)) self.assertFalse(presence_layer.is_user_followed_by(self.simulated_user_id, logged_user_id))
10,977
Python
45.12605
127
0.667213
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/docs/index.rst
omni.kit.collaboration.presence_layer ###################################### Live Session: Presence Layer Introduction ============ Presence Layer works for storage for exchanging persistent data for all users in the same Live Session. The theory behind uses .live layer as transport layer, on top of which all user data are structured as USD prim. It provides easy API to access the data without using raw USD API, and also event stream to subscribe the data changes. Currently, it's used for spatial awareness, which includes the following applications: * Bound Camera. * Selections. * User Following. User can exchange and synchronize their local states of the above applications into the Presence Layer for other users to be aware of. Presence Layer is bound to UsdContext. For each context, it has an unique presence layer.
833
reStructuredText
40.699998
118
0.755102
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/hotkeys.py
from typing import Optional import carb import omni.kit.app from omni.kit.actions.core import get_action_registry _HOTKEYS_EXT = "omni.kit.hotkeys.core" _DEFAULT_HOTKEY_MAP = { "perspective_camera": "ALT+P", "top_camera": "ALT+T", "front_camera": "ALT+F", "right_camera": "ALT+R", "toggle_grid_visibility": "G", "toggle_camera_visibility": "SHIFT+C", "toggle_light_visibility": "SHIFT+L", "toggle_global_visibility": "SHIFT+H", "toggle_wireframe": "SHIFT+W", } def register_hotkeys(extension_id: str, window_name: Optional[str] = None): ext_manager = omni.kit.app.get_app_interface().get_extension_manager() if not ext_manager.is_extension_enabled(_HOTKEYS_EXT): carb.log_info(f"{_HOTKEYS_EXT} is not enabled. Cannot register hotkeys.") return import omni.kit.hotkeys.core as hotkeys hotkey_registry = hotkeys.get_hotkey_registry() action_registry = get_action_registry() ext_actions = action_registry.get_all_actions_for_extension(extension_id) hotkey_filter = hotkeys.HotkeyFilter(windows=[window_name]) if window_name else None hotkey_map = _DEFAULT_HOTKEY_MAP.copy() # add UI hotkeys if carb.settings.get_settings().get("exts/omni.kit.viewport.actions/ui_hotkeys"): hotkey_map["toggle_ui"] = "F7" # check if IAppWindowImplOs has already registered F11 if not carb.settings.get_settings().get("/exts/omni.appwindow/listenF11"): hotkey_map["toggle_fullscreen"] = "F11" if carb.settings.get_settings().get_as_bool( "/app/window/showDpiScaleMenu"): hotkey_map["dpi_scale_increase"] = "EQUAL" hotkey_map["dpi_scale_decrease"] = "MINUS" for action in ext_actions: key = hotkey_map.get(action.id, None) # Not all Actions will have default hotkeys if not key: continue hotkey_registry.register_hotkey( hotkey_ext_id=extension_id, key=key, action_ext_id=action.extension_id, action_id=action.id, filter=hotkey_filter, ) def deregister_hotkeys(extension_id: str): ext_manager = omni.kit.app.get_app_interface().get_extension_manager() if not ext_manager.is_extension_enabled(_HOTKEYS_EXT): carb.log_info(f"{_HOTKEYS_EXT} is not enabled. No hotkeys to deregister.") return import omni.kit.hotkeys.core as hotkeys hotkey_registry = hotkeys.get_hotkey_registry() hotkey_registry.deregister_all_hotkeys_for_extension(extension_id)
2,546
Python
35.385714
88
0.661037
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportActionsExtension", "get_instance"] from .actions import register_actions, deregister_actions from .hotkeys import register_hotkeys, deregister_hotkeys import omni.ext import omni.kit.app from typing import Callable _extension_instance = None def get_instance(): global _extension_instance return _extension_instance class ViewportActionsExtension(omni.ext.IExt): """Actions and Hotkeys related to the Viewport""" def __init__(self): super().__init__() self._ext_name = None self._hotkey_extension_enabled_hook = None self._hotkey_extension_disabled_hook = None def on_startup(self, ext_id): global _extension_instance _extension_instance = self self._ext_name = omni.ext.get_extension_name(ext_id) # Hooks to hotkey extension enable/disable app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() hooks: omni.ext.IExtensionManagerHooks = ext_manager.get_hooks() self._hotkey_extension_enabled_hook = hooks.create_extension_state_change_hook( self._on_hotkey_ext_changed, omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE, ext_name="omni.kit.hotkeys.core", ) self._hotkey_extension_disabled_hook = hooks.create_extension_state_change_hook( self._on_hotkey_ext_changed, omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_DISABLE, ext_name="omni.kit.hotkeys.core", ) register_actions(self._ext_name) register_hotkeys(self._ext_name) def on_shutdown(self): global _extension_instance _extension_instance = None self._hotkey_extension_enabled_hook = None self._hotkey_extension_disabled_hook = None deregister_hotkeys(self._ext_name) deregister_actions(self._ext_name) self._ext_name = None del ViewportActionsExtension.__g_usd_context_streams def _on_hotkey_ext_changed(self, ext_id: str, ext_change_type: omni.ext.ExtensionStateChangeType): if ext_change_type == omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE: register_hotkeys(self._ext_name) if ext_change_type == omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_DISABLE: deregister_hotkeys(self._ext_name) __g_usd_context_streams = None @staticmethod def _watch_stage_open(usd_context_name: str, open_callback: Callable): if ViewportActionsExtension.__g_usd_context_streams is None: ViewportActionsExtension.__g_usd_context_streams = {} sub_id = ViewportActionsExtension.__g_usd_context_streams.get(usd_context_name, None) if sub_id is not None: return import omni.usd def on_stage_event(event): if event.type == int(omni.usd.StageEventType.OPENED): stage = omni.usd.get_context(usd_context_name).get_stage() if stage: open_callback(usd_context_name, stage) ViewportActionsExtension.__g_usd_context_streams[usd_context_name] = ( omni.usd.get_context(usd_context_name).get_stage_event_stream().create_subscription_to_pop( on_stage_event, name="omni.kit.viewport.actions.sticky_visibility" ) )
3,792
Python
35.825242
103
0.671677
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/actions.py
__all__ = ["register_actions", "deregister_actions"] import omni.kit.actions.core import omni.kit.viewport.utility import carb import omni.ui as ui from pxr import Sdf, UsdGeom from functools import partial from typing import List, Optional, Sequence, Tuple PERSP_CAM = "perspective_camera" TOP_CAM = "top_camera" FRONT_CAM = "front_camera" RIGHT_CAM = "right_camera" SHOW_ALL_PURPOSE = "toggle_show_by_purpose_all" SHOW_GUIDE = "toggle_show_by_purpose_guide" SHOW_PROXY = "toggle_show_by_purpose_proxy" SHOW_RENDER = "toggle_show_by_purpose_render" INERTIA_TOGGLE = "toggle_camera_inertia_enabled" FILL_VIEWPORT_TOGGLE = "toggle_fill_viewport" RENDERER_RTX_REALTIME = "set_renderer_rtx_realtime" RENDERER_RTX_PT = "set_renderer_rtx_pathtracing" RENDERER_RTX_TOGGLE = "toggle_rtx_rendermode" RENDERER_IRAY = "set_renderer_iray" RENDERER_PXR_STORM = "set_renderer_pxr_storm" RENDERER_WIREFRAME = "toggle_wireframe" PERSISTENT_SETTINGS_PREFIX = "/persistent" INERTIA_ENABLE_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/camInertiaEnabled" FILL_VIEWPORT_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/{viewport_api_id}/fillViewport" DISPLAY_GUIDE_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/hydra/displayPurpose/guide" DISPLAY_PROXY_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/hydra/displayPurpose/proxy" DISPLAY_RENDER_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/hydra/displayPurpose/render" SECTION_VISIBILE_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/{viewport_api_id}/{section}/visible" SHADING_MODE_SETTING = "/exts/omni.kit.viewport.menubar.render/shadingMode" SHOW_DPI_SCALE_MENU_SETTING = "/app/window/showDpiScaleMenu" DPI_SCALE_OVERRIDE_SETTING = "/app/window/dpiScaleOverride" DPI_SCALE_OVERRIDE_DEFAULT = -1.0 DPI_SCALE_OVERRIDE_MIN = 0.5 DPI_SCALE_OVERRIDE_MAX = 5.0 DPI_SCALE_OVERRIDE_STEP = 0.5 workspace_data = [] def register_actions(extension_id: str): action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "Viewport Camera Menu Actions" action_registry.register_action( extension_id, PERSP_CAM, partial(set_camera, "/OmniverseKit_Persp"), display_name="Perspective Camera", description="Switch to Perspective Camera", tag=actions_tag, ) action_registry.register_action( extension_id, TOP_CAM, partial(set_camera, "/OmniverseKit_Top"), display_name="Top Camera", description="Switch to Top Camera", tag=actions_tag, ) action_registry.register_action( extension_id, FRONT_CAM, partial(set_camera, "/OmniverseKit_Front"), display_name="Front Camera", description="Switch to Front Camera", tag=actions_tag, ) action_registry.register_action( extension_id, RIGHT_CAM, partial(set_camera, "/OmniverseKit_Right"), display_name="Right Camera", description="Switch to Right Camera", tag=actions_tag, ) actions_tag = "Viewport Display Menu Actions" action_registry.register_action( extension_id, SHOW_ALL_PURPOSE, partial( toggle_category_settings, DISPLAY_GUIDE_SETTING, DISPLAY_PROXY_SETTING, DISPLAY_RENDER_SETTING, ), display_name="Toggle Show All Purpose", description="Toggle Show By Purpose - All", tag=actions_tag, ) action_registry.register_action( extension_id, SHOW_GUIDE, partial(_toggle_setting, DISPLAY_GUIDE_SETTING), display_name="Toggle Show Guide Purpose", description="Toggle Show By Purpose - Guide", tag=actions_tag, ) action_registry.register_action( extension_id, SHOW_PROXY, partial(_toggle_setting, DISPLAY_PROXY_SETTING), display_name="Toggle Show Proxy Purpose", description="Toggle Show By Purpose - Proxy", tag=actions_tag, ) action_registry.register_action( extension_id, SHOW_RENDER, partial(_toggle_setting, DISPLAY_RENDER_SETTING), display_name="Toggle Show Render Purpose", description="Toggle Show By Purpose - Render", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_camera_visibility", toggle_camera_visibility, display_name="Toggle Show Cameras", description="Toggle Show By Type - Cameras", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_light_visibility", toggle_light_visibility, display_name="Toggle Show Lights", description="Toggle Show By Type - Lights", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_skeleton_visibility", toggle_skeleton_visibility, display_name="Toggle Show Skeletons", description="Toggle Show By Type - Skeletons", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_audio_visibility", toggle_audio_visibility, display_name="Toggle Show Audio", description="Toggle Show By Type - Audio", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_mesh_visibility", toggle_mesh_visibility, display_name="Toggle Show Meshes", description="Toggle Show By Type - Meshes", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_show_by_type_visibility", toggle_show_by_type_visibility, display_name="Toggle Show By Type", description="Toggle Show By Type - All Type Toggle", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_grid_visibility", toggle_grid_visibility, display_name="Toggle Grid", description="Toggle drawing of grid", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_axis_visibility", toggle_axis_visibility, display_name="Toggle Camera Axis", description="Toggle drawing of camera axis", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_selection_hilight_visibility", toggle_selection_hilight_visibility, display_name="Toggle Selection Outline", description="Toggle drawing of selection hilight", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_global_visibility", toggle_global_visibility, display_name="Toggle Global Visibility", description="Toggle drawing of grid, HUD, audio, light, camera, and skeleton gizmos", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_viewport_visibility", toggle_viewport_visibility, display_name="Toggle Viewport item visibility", description="Toggle drawing of Viewport items by key.", tag=actions_tag, ) actions_tag = "Viewport Settings Menu Actions" action_registry.register_action( extension_id, INERTIA_TOGGLE, partial(_toggle_setting, INERTIA_ENABLE_SETTING), display_name="Toggle Camera Inertia Enabled", description="Toggle Camera Inertia Mode Enabled", tag=actions_tag, ) action_registry.register_action( extension_id, FILL_VIEWPORT_TOGGLE, partial(_toggle_setting, FILL_VIEWPORT_SETTING), display_name="Toggle Fill Viewport", description="Toggle Fill Viewport Setting", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_lock_navigation_height", partial(_toggle_setting, "/persistent/exts/omni.kit.manipulator.camera/flyViewLock"), display_name="Toggle Lock Navigation Height", description="Toggle whether fly-mode forward/backward and up/down uses ore ignores the camera orientation.", tag=actions_tag, ) action_registry.register_action( extension_id, "set_viewport_resolution", set_viewport_resolution, display_name="Set Viewport Resolution", description="Set a Viewport's resolution with a tuple or named constant.", tag=actions_tag, ) carb.settings.get_settings().set_default_bool(SHOW_DPI_SCALE_MENU_SETTING, False) action_registry.register_action( extension_id, "toggle_ui", on_toggle_ui, display_name="Toggle Viewport UI Overlay", description="Toggle Viewport UI Overlay", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_fullscreen", on_fullscreen, display_name="Toggle Viewport Fullscreen", description="Toggle Viewport Fullscreen", tag=actions_tag, ) action_registry.register_action( extension_id, "dpi_scale_increase", on_dpi_scale_increase, display_name="DPI Scale Increase", description="DPI Scale Increase", tag=actions_tag, ) action_registry.register_action( extension_id, "dpi_scale_decrease", on_dpi_scale_decrease, display_name="DPI Scale Decrease", description="DPI Scale Decrease", tag=actions_tag, ) action_registry.register_action( extension_id, "dpi_scale_reset", on_dpi_scale_reset, display_name="DPI Scale Reset", description="DPI scale reset to default", tag=actions_tag, ) actions_tag = "Viewport Render Menu Actions" # TODO: these should maybe register dynamically as renderers are loaded/unloaded? settings = carb.settings.get_settings() available_engines = (settings.get('/renderer/enabled') or '').split(',') ignore_loaded_engined = True if ignore_loaded_engined or ('rtx' in available_engines): action_registry.register_action( extension_id, RENDERER_RTX_REALTIME, partial(set_renderer, "rtx", "RaytracedLighting"), display_name="Set Renderer to RTX Realtime", description="Set Renderer Engine to RTX Realtime", tag=actions_tag, ) action_registry.register_action( extension_id, RENDERER_RTX_PT, partial(set_renderer, "rtx", "PathTracing"), display_name="Set Renderer to RTX Pathtracing", description="Set Renderer Engine to RTX Pathtracing", tag=actions_tag, ) action_registry.register_action( extension_id, RENDERER_RTX_TOGGLE, toggle_rtx_rendermode, display_name="Toggle RTX render-mode", description="Toggle RTX render-mode between Realtime and Pathtracing", tag=actions_tag, ) if ignore_loaded_engined or ('iray' in available_engines): action_registry.register_action( extension_id, RENDERER_IRAY, partial(set_renderer, "iray", "iray"), display_name="Set Renderer to RTX Accurate (Iray)", description="Set Renderer Engine to RTX Accurate (Iray)", tag=actions_tag, ) if ignore_loaded_engined or ('pxr' in available_engines): action_registry.register_action( extension_id, RENDERER_PXR_STORM, partial(set_renderer, "pxr", "HdStormRendererPlugin"), display_name="Set Renderer to Pixar Storm", description="Set Renderer Engine to Pixar Storm", tag=actions_tag, ) action_registry.register_action( extension_id, RENDERER_WIREFRAME, toggle_wireframe, display_name="Toggle wireframe", description="Toggle wireframe", tag=actions_tag, ) # HUD visibility actions actions_tag = "Viewport HUD Visibility Actions" action_registry.register_action( extension_id, "toggle_hud_fps_visibility", partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/renderFPS"], action="toggle_hud_fps_visibility"), display_name="Toggle Render FPS HUD visibility", description="Toggle whether render fps item is visible in HUD or not.", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_hud_resolution_visibility", partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/renderResolution"], action="toggle_hud_resolution_visibility"), display_name="Toggle Render Resolution HUD visibility", description="Toggle whether render resolution item is visible in HUD or not.", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_hud_progress_visibility", partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/renderProgress"], action="toggle_hud_progress_visibility"), display_name="Toggle Render Progress HUD visibility", description="Toggle whether render progress item is visible in HUD or not.", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_hud_camera_speed_visibility", partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/cameraSpeed"], action="toggle_hud_camera_speed_visibility"), display_name="Toggle Camera Speed HUD visibility", description="Toggle whether camera speed HUD item is visible in HUD or not.", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_hud_memory_visibility", toggle_hud_memory_visibility, display_name="Toggle Memory Item HUD visibility", description="Toggle whether HUD memory items HUD are visible in HUD or not.", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_hud_visibility", toggle_hud_visibility, display_name="Toggle Gloabl HUD visiblity", description="Toggle whether any HUD items are visible or not.", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() if action_registry: action_registry.deregister_all_actions_for_extension(extension_id) def _get_viewport_argument(viewport_api, action: str): if not viewport_api: viewport_api = omni.kit.viewport.utility.get_active_viewport() if not viewport_api: carb.log_warn(f"There was no provided or active Viewport - not able to run viewport-specific action: {action}.") return None return viewport_api def set_camera(camera_str: str, viewport_api=None) -> bool: """Switch the camera in the active viewport based on the camera path. Args: camera_str (str): Camera Path in string form. ie "/OmniverseKit_Persp" viewport_api (viewport): Optional viewport in order to set the camera in a specific viewport. Returns: bool: True if successful, False if not. """ viewport = _get_viewport_argument(viewport_api, "set_camera") if not viewport: return False stage = viewport.stage if not stage: carb.log_warn("Viewport Stage does not exist, to switch cameras.") return False camera_path = Sdf.Path(camera_str) prim = stage.GetPrimAtPath(camera_path) if not prim: carb.log_warn(f"Prim for camera path: {camera_path} does not exist in the stage.") return False if not UsdGeom.Camera(prim): carb.log_warn(f"Camera: {camera_path} does not exist in the stage.") return False viewport.camera_path = camera_path return True def set_renderer(engine_name, render_mode, viewport_api=None) -> bool: viewport = _get_viewport_argument(viewport_api, "set_renderer") if not viewport: return False viewport.set_hd_engine(engine_name, render_mode) return True def toggle_rtx_rendermode(viewport_api=None) -> bool: viewport = _get_viewport_argument(viewport_api, "toggle_rtx_rendermode") if not viewport: return False # Toggle to PathTracing when already on RTX and using RaytracedLighting if viewport.hydra_engine == "rtx" and viewport.render_mode == "RaytracedLighting": render_mode = "PathTracing" else: render_mode = "RaytracedLighting" viewport.set_hd_engine("rtx", render_mode) return True def toggle_wireframe() -> str: settings = carb.settings.get_settings() mode = settings.get(SHADING_MODE_SETTING) if mode == "wireframe": # Set to default settings.set(SHADING_MODE_SETTING, "default") settings.set("/rtx/wireframe/mode", 0) return "default" else: # Set to wireframe settings.set(SHADING_MODE_SETTING, "wireframe") settings.set("/rtx/debugView/target", "") flat_shade = settings.get("/rtx/debugMaterialType") == 0 wire_mode = 2 if flat_shade else 1 settings.set("/rtx/wireframe/mode", wire_mode) return "wireframe" def toggle_category_settings(*setting_names): settings = carb.settings.get_settings() vals = [settings.get(setting_name) for setting_name in setting_names] value_for_all = False if all(vals) else True for setting_name in setting_names: settings.set(setting_name, value_for_all) def _toggle_setting(setting_name: str, viewport_api: Optional["ViewportAPI"] = None, visible: bool | None = None): viewport_api = _get_viewport_argument(viewport_api, "_toggle_setting") if not viewport_api: return setting_path = setting_name.format(viewport_api_id=viewport_api.id) settings = carb.settings.get_settings() if visible is None: visible = not bool(settings.get(setting_path)) settings.set(setting_path, visible) return visible _k_setting_to_prim_type = { "scene/cameras": {"Camera"}, "scene/skeletons": {"Skeleton"}, "scene/audio": {"Sound", "Listener"}, "scene/meshes": {"Mesh", "Cone", "Cube", "Cylinder", "Sphere", "Capsule"}, # "scene/lights" } def _stage_opened(usd_context_name: str, stage): if not stage: return settings = carb.settings.get_settings() reset_on_open = settings.get("/exts/omni.kit.viewport.actions/resetVisibilityOnOpen") def get_display_option_and_off(setting_key: str): vis_key = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}/visible" return (vis_key, not bool(settings.get(vis_key))) def is_display_option_off(setting_key: str): return get_display_option_and_off(setting_key)[1] types_to_hide = set() for setting_key, prim_types in _k_setting_to_prim_type.items(): vis_key, is_off = get_display_option_and_off(setting_key) if reset_on_open and setting_key in reset_on_open: if is_off: settings.set(vis_key, True) elif is_off: types_to_hide.update(prim_types) if not types_to_hide: return from omni.kit.viewport.actions.visibility import VisibilityEdit VisibilityEdit(stage, types_to_show=None, types_to_hide=types_to_hide).run() def _get_visible(visible: bool | Sequence[bool], index: int): """Utility function to get visibilty as a bool or from a bool or a list with index""" getitem = getattr(visible, "__getitem__", None) if getitem: return bool(getitem(index)) return bool(visible) def _toggle_legacy_display_visibility(viewport_api, visible: bool | Sequence[bool], setting_keys: Sequence[str], reduce_sequence: bool) -> List[str]: persitent_to_legacy_map = { "hud/renderFPS": (1 << 0, None), "guide/axis": (1 << 1, None), "hud/renderResolution": (1 << 3, None), "scene/cameras": (1 << 5, "/app/viewport/show/camera"), "guide/grid": (1 << 6, "/app/viewport/grid/enabled"), "guide/selection": (1 << 7, "/app/viewport/outline/enabled"), "scene/lights": (1 << 8, "/app/viewport/show/lights"), "scene/skeletons": (1 << 9, None), "scene/meshes": (1 << 10, None), "hud/renderProgress": (1 << 11, None), "scene/audio": (1 << 12, "/app/viewport/show/audio"), "hud/deviceMemory": (1 << 13, None), "hud/hostMemory": (1 << 14, None), } settings = carb.settings.get_settings() display_options = settings.get("/persistent/app/viewport/displayOptions") or 0 empty_tuple = (None, None) result = [] for i in range(len(setting_keys)): section, new_visible = setting_keys[i], _get_visible(visible, i) section_mask, section_key = persitent_to_legacy_map.get(section, empty_tuple) if section_mask is None: continue was_visible = bool(display_options & section_mask) if new_visible is None: display_options ^= section_mask # Make new_visible != was_visible comparison below correct for state transition new_visible = bool(display_options & section_mask) elif new_visible != was_visible: if new_visible: display_options |= section_mask else: display_options &= ~section_mask if new_visible != was_visible: result.append(section) if section_key: settings.set(section_key, new_visible) settings.set("/persistent/app/viewport/displayOptions", display_options) # Reduce the case of a single item sequence to the item or None if requested if reduce_sequence: result = result[0] if result else None return result def _toggle_viewport_visibility(viewport_api, visible: bool | Sequence[bool] | None, setting_keys: Sequence[str], action: str, reduce_sequence: bool = True) -> List[str] | str | None: viewport_api = _get_viewport_argument(viewport_api, action) if not viewport_api: return [] if hasattr(viewport_api, 'legacy_window'): return _toggle_legacy_display_visibility(viewport_api, visible, setting_keys, reduce_sequence) settings = carb.settings.get_settings() usd_context_name = viewport_api.usd_context_name def get_visibility(setting_key: str) -> Tuple[bool, str]: # Currently settings in "scene" correspond to a state change in the Usd stage if setting_key.startswith("scene"): setting_key = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}/visible" else: setting_key = f"/persistent/app/viewport/{viewport_api.id}/{setting_key}/visible" return bool(settings.get(setting_key)), setting_key if visible is None: # No explicit visiblity given, figure out what things to flip all_visible, any_visible = True, False for setting_key in setting_keys: # Get the current visibility cur_visibility, _ = get_visibility(setting_key) # If this any item is not visible, then the toggle is a transition to all items visible; early exit if not cur_visibility: all_visible = False else: any_visible = True # Transition to hidden if all were visible, otherwise transition to visible # All were visible => Nothing visible # Nothing was visible => All visible # Anything was visible => All visible if any_visible and not all_visible: visible = True else: visible = not all_visible stage = viewport_api.stage types_to_show, types_to_hide = set(), set() # Apply any visibility UsdAttribute changes to the types requested setting_to_prim_types = _k_setting_to_prim_type if stage else {} result = [] # Find all the objects that need to be toggled for i in range(len(setting_keys)): setting_key, new_visible = setting_keys[i], _get_visible(visible, i) cur_visibility, pref_key = get_visibility(setting_key) cur_visibility = bool(cur_visibility) if cur_visibility != new_visible: settings.set(pref_key, new_visible) prim_types = setting_to_prim_types.get(setting_key) if prim_types: if new_visible: types_to_show.update(prim_types) else: types_to_hide.update(prim_types) elif setting_key == "guide/selection": # Still need to special case this to forward correctly (its global) settings.set("/app/viewport/outline/enabled", new_visible) # If visibility was toggled, add to the key to the return value if new_visible != cur_visibility: result.append(setting_key) # Apply any visibility UsdAttribute changes to the types requested if types_to_show or types_to_hide: from .visibility import VisibilityEdit VisibilityEdit(stage, types_to_show=types_to_show, types_to_hide=types_to_hide).run() # The action is a toggle of state that is sticky across new stage's, so need to apply state to any new stage from omni.kit.viewport.actions.extension import get_instance get_instance()._watch_stage_open(usd_context_name, _stage_opened) # Reduce the case of a single item sequence to the item or None if requested if reduce_sequence: result = result[0] if result else None return result def toggle_grid_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None: return _toggle_viewport_visibility(viewport_api, visible, ["guide/grid"], "toggle_grid_visibility") def toggle_axis_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None: return _toggle_viewport_visibility(viewport_api, visible, ["guide/axis"], "toggle_axis_visibility") def toggle_selection_hilight_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None: return _toggle_viewport_visibility(viewport_api, visible, ["guide/selection"], "toggle_selection_hilight_visibility") def toggle_camera_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None: return _toggle_viewport_visibility(viewport_api, visible, ["scene/cameras"], "toggle_camera_visibility") def toggle_light_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None: return _toggle_viewport_visibility(viewport_api, visible, ["scene/lights"], "toggle_light_visibility") def toggle_skeleton_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None: return _toggle_viewport_visibility(viewport_api, visible, ["scene/skeletons"], "toggle_skeleton_visibility") def toggle_audio_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None: return _toggle_viewport_visibility(viewport_api, visible, ["scene/audio"], "toggle_audio_visibility") def toggle_mesh_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None: return _toggle_viewport_visibility(viewport_api, visible, ["scene/meshes"], "toggle_mesh_visibility") def toggle_show_by_type_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> List[str]: return _toggle_viewport_visibility(viewport_api, visible, ["scene/cameras", "scene/lights", "scene/skeletons", "scene/audio"], "toggle_show_by_type_visibility", False) def _get_toggle_types(settings, setting_path: str) -> List[str]: toggle_types = settings.get(setting_path) if toggle_types is None: return [] if isinstance(toggle_types, str): return toggle_types.split(",") return toggle_types def toggle_global_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> List[str]: viewport_api = _get_viewport_argument(viewport_api, "toggle_global_visibility") if viewport_api and hasattr(viewport_api, "legacy_window"): viewport_api.legacy_window.toggle_global_visibility_settings() return [] # Get the list of what to hide (defaulting to what legacy Viewport and toggle_global_visibility_settings did) settings = carb.settings.get_settings() toggle_types = _get_toggle_types(settings, "/exts/omni.kit.viewport.actions/visibilityToggle/globalTypes") toggle_types += _get_toggle_types(settings, "/exts/omni.kit.viewport.actions/visibilityToggle/hudTypes") return _toggle_viewport_visibility(viewport_api, visible, toggle_types, "toggle_global_visibility", False) def toggle_viewport_visibility(keys: Sequence[str], viewport_api=None, visible: bool | Sequence[bool] | None = None) -> List[str]: return _toggle_viewport_visibility(viewport_api, visible, keys, "toggle_viewport_visibility", False) def toggle_hud_memory_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None, host: bool = True, device: bool = True) -> str | None: items = [] if host: items.append("hud/hostMemory") if device: items.append("hud/deviceMemory") if items: return _toggle_viewport_visibility(viewport_api, visible, items, "toggle_hud_memory_visibility") return [] def toggle_hud_visibility(viewport_api=None, visible: bool | None = None, use_setting: bool = False): viewport = _get_viewport_argument(viewport_api, "toggle_hud_visibility") if not viewport: return # as_menu works around a defect in Viewport-menu modeling of settings, where top-level item will enable # or disable all child items only in the first grouping, but toggle_hud_visibility action should really mean # all HUD items, (the ui-layer that contains any "hud/children" items). if use_setting: settings = carb.settings.get_settings() toggle_types = _get_toggle_types(settings, "/exts/omni.kit.viewport.actions/visibilityToggle/hudTypes") toggled = _toggle_viewport_visibility(viewport, visible, toggle_types, "toggle_hud_visibility", reduce_sequence=False) any_vis = bool(visible) if not any_vis: for key in toggle_types: any_vis = settings.get(f"/persistent/app/viewport/{viewport.id}/{key}/visible") if any_vis: break # If any of the children are now visible, make sure the top-level parent is also visible if any_vis: _toggle_setting("/persistent/app/viewport/{viewport_api_id}/hud/visible", viewport, visible=True) return toggled return _toggle_setting("/persistent/app/viewport/{viewport_api_id}/hud/visible", viewport) def set_viewport_resolution(resolution, viewport_api=None): viewport_api = _get_viewport_argument(viewport_api, "set_viewport_resolution") if not viewport_api: return # Accept resolution as a named constant (str) as well as a tuple if isinstance(resolution, str): resolution_tuple = NAME_RESOLUTIONS = { "Icon": (512, 512), "Square": (1024, 1024), "SD": (1280, 960), "HD720P": (1280, 720), "HD1080P": (1920, 1080), "2K": (2048, 1080), "1440P": (2560, 1440), "UHD": (3840, 2160), "Ultra Wide": (3440, 1440), "Super Ultra Wide": (3840, 1440), "5K Wide": (5120, 2880), }.get(resolution) if resolution_tuple is None: carb.log_error("Resolution named {resolution} is not known.") return resolution = resolution_tuple viewport_api.resolution = resolution def set_ui_hidden(hide): global workspace_data if hide: # hide context_menu try: omni.kit.context_menu.close_menu() except: pass # windows are going to be hidden. Save workspace 1st workspace_data = ui.Workspace.dump_workspace() carb.settings.get_settings().set("/app/window/hideUi", hide) else: carb.settings.get_settings().set("/app/window/hideUi", hide) # windows are going to be restored from hidden. Re-load workspace # ui.Workspace.restore_workspace is async so it don't need to # wait for initial unhide of the window here ui.Workspace.restore_workspace(workspace_data, False) workspace_data = [] def is_ui_hidden(): return carb.settings.get_settings().get("/app/window/hideUi") def on_toggle_ui(): set_ui_hidden(not is_ui_hidden()) def on_fullscreen(): display_mode_lock = carb.settings.get_settings().get(f"/app/window/displayModeLock") if display_mode_lock: # Always stay in fullscreen_mode, only hide or show UI. set_ui_hidden(not is_ui_hidden()) else: # Only toggle fullscreen on/off when not display_mode_lock was_fullscreen = omni.appwindow.get_default_app_window().is_fullscreen() omni.appwindow.get_default_app_window().set_fullscreen(not was_fullscreen) # Always hide UI in fullscreen set_ui_hidden(not was_fullscreen) def step_and_clamp_dpi_scale_override(increase): import omni.ui as ui # Get the current value. dpi_scale = carb.settings.get_settings().get_as_float(DPI_SCALE_OVERRIDE_SETTING) if dpi_scale == DPI_SCALE_OVERRIDE_DEFAULT: dpi_scale = ui.Workspace.get_dpi_scale() # Increase or decrease the current value by the setp value. if increase: dpi_scale += DPI_SCALE_OVERRIDE_STEP else: dpi_scale -= DPI_SCALE_OVERRIDE_STEP # Clamp the new value between the min/max values. dpi_scale = max(min(dpi_scale, DPI_SCALE_OVERRIDE_MAX), DPI_SCALE_OVERRIDE_MIN) # Set the new value. carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, dpi_scale) def on_dpi_scale_increase(): step_and_clamp_dpi_scale_override(True) def on_dpi_scale_decrease(): step_and_clamp_dpi_scale_override(False) def on_dpi_scale_reset(): carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, DPI_SCALE_OVERRIDE_DEFAULT)
34,697
Python
35.71746
152
0.64484
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/visibility.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__ = ["VisibilityEdit"] import carb import omni.usd from pxr import Usd, UsdGeom, Sdf from typing import Callable, Optional, Sequence def _get_usd_rt_stage(stage: Usd.Stage): try: from pxr import UsdUtils from usdrt import Usd as UsdRtUsd stage_id = UsdUtils.StageCache.Get().GetId(stage).ToLongInt() fabric_active_for_stage = UsdRtUsd.Stage.StageWithHistoryExists(stage_id) if fabric_active_for_stage: return UsdRtUsd.Stage.Attach(stage_id) except (ImportError, ModuleNotFoundError): pass return None class VisibilityEdit: def __init__(self, stage, types_to_show: Optional[Sequence[str]] = None, types_to_hide: Optional[Sequence[str]] = None): # Sdf.Path.FindLongestPrefix require Sdf.PathVector (i.e. list) so we cannot use a dict self.__path_to_change = {} self.__stage = stage self.__types_to_show = types_to_show self.__types_to_hide = types_to_hide self.__ignore_hidden_in_stage = carb.settings.get_settings().get("/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden") def run(self): if self.__gather_prims(): self.__hide_prims() @carb.profiler.profile def __get_prim_iterator(self, predicate): # Early exit for request to do nothing if not bool(self.__types_to_show) and not bool(self.__types_to_hide): return # Local function to filter Usd.Prim, returns None to ignore it or the Usd.Prim otherwise def filter_prim(prim: Usd.Prim): if self.__ignore_hidden_in_stage and omni.usd.editor.is_hide_in_stage_window(prim): return None return prim # If UsdRt is available, use it to pre-prune the traversal to only given types rt_stage = _get_usd_rt_stage(self.__stage) if rt_stage: # Merge all the prim-types of interest into one set for querying if self.__types_to_show: prim_types = set(self.__types_to_show) if self.__types_to_hide: prim_types = prim_types.union(set(self.__types_to_hide)) else: prim_types = set(self.__types_to_hide) for prim_type in prim_types: for prim_path in rt_stage.GetPrimsWithTypeName(prim_type): prim = filter_prim(self.__stage.GetPrimAtPath(prim_path.GetString())) if prim: yield prim return iterator = iter(self.__stage.Traverse(predicate)) for prim in iterator: # Prune anything that is hide_in_stage_window # Not sure why, but this matches legacy behavior if filter_prim(prim) is None: iterator.PruneChildren() continue yield prim @property def predicate(self): return Usd.TraverseInstanceProxies(Usd.PrimDefaultPredicate) def __get_visibility(self, prim: Usd.Prim, prim_path: Sdf.Path): type_name = prim.GetTypeName() make_visible = type_name in self.__types_to_show if self.__types_to_show else False make_invisible = type_name in self.__types_to_hide if self.__types_to_hide else False return (make_visible, make_invisible) @carb.profiler.profile def __gather_prims(self): path_to_change = {} # Traverse the satge, gathering the prims that have requested a visibility change # This is a two-phase process to allow hiding leaves of instances by hiding the # top-most un-instanced parent whose leaves are all of a hideable type for prim in self.__get_prim_iterator(self.predicate): prim_path = prim.GetPath() make_visible, make_invisible = self.__get_visibility(prim, prim_path) # If not making this type visible or invisible, then nothing to do if (make_visible is False) and (make_invisible is False): continue if prim.IsInstanceProxy(): is_child = False for path in path_to_change.keys(): if path.GetCommonPrefix(prim_path) == path: is_child = True break if is_child: continue parent = prim.GetParent() while parent and not parent.IsInstance(): parent = parent.GetParent() # Insert the parent now and validate all children in the second phase if parent: path_to_change[parent.GetPath()] = True else: path_to_change[prim_path] = False self.__path_to_change = path_to_change return len(self.__path_to_change) != 0 @carb.profiler.profile def __hide_prims(self): # Traverse the instanced prims, making sure that all children are of the proper type # or an allowed 'intermediate' type of Xform or Scope. # If all children pass that test, then the instance can safely be hidden, otherwise # it contains children that are not being requested as hidden, so the instance is left alone. predicate = self.predicate # UsdGeom.Imageabales that are acceptable intermediate children allowed_imageables = set(("Xform", "Scope")) # Setup the edit-context once, and batch all changes session_layer = self.__stage.GetSessionLayer() with Usd.EditContext(self.__stage, session_layer): with Sdf.ChangeBlock(): for prim_path, is_instance in self.__path_to_change.items(): prim = self.__stage.GetPrimAtPath(prim_path) if not prim: continue if prim.IsInstanceProxy(): carb.log_error(f"Unexpected instance in list of prims to toggle visibility: {prim.GetPath()}") continue # Assume success toggle_error = None visible = None # If its an instance, traverse all children and make sure that # they are of the right type, not a UsdImageable, or an allowed intermediate. if is_instance: for child_prim in prim.GetFilteredChildren(predicate): child_type = child_prim.GetTypeName() child_show, child_hide = self.__get_visibility(child_prim, child_prim.GetPath()) if (not child_show) and (not child_hide): # If child is in neither list, than it must be an allowed intermediate type (or not an Imagaeable) if (not UsdGeom.Imageable(child_prim)) or (child_type in allowed_imageables): continue toggle_error = "it contains at least one child with a type not being requested to hide." break # First loop iteration, set visible to proper state if visible is None: visible = child_show if child_show != visible: toggle_error = "its hiearchy is too heterogeneous for this action." break else: visible = prim.GetTypeName() in self.__types_to_show if self.__types_to_show else False if toggle_error: visible_verb = 'show' if visible else 'hide' carb.log_warn(f"Will not {visible_verb} '{prim_path}', {toggle_error}") continue if visible: # as the session layer overrides all other layers, remove the primSpec prim_spec = session_layer.GetPrimAtPath(prim_path) property = session_layer.GetPropertyAtPath(prim_path.AppendProperty(UsdGeom.Tokens.visibility)) if prim_spec else None if property: prim_spec.RemoveProperty(property) else: imageable = UsdGeom.Imageable(prim) if imageable: imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.invisible)
8,950
Python
45.139175
148
0.574078
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/test_actions.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ['TestActionsAndHotkeys'] import omni.kit.actions.core from omni.kit.test import AsyncTestCase from ..actions import is_ui_hidden, set_camera class TestActionsAndHotkeys(AsyncTestCase): async def setUp(self): self.extension_id = "omni.kit.viewport.actions" async def wait_n_updates(self, n_frames: int = 3): app = omni.kit.app.get_app() for _ in range(n_frames): await app.next_update_async() async def test_find_registered_action(self): action_registry = omni.kit.actions.core.get_action_registry() action = action_registry.get_action(self.extension_id, "perspective_camera") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "top_camera") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "front_camera") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "right_camera") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_rtx_rendermode") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "set_viewport_resolution") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_camera_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_light_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_grid_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_axis_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_selection_hilight_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_global_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_viewport_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_hud_fps_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_hud_resolution_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_hud_progress_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_hud_camera_speed_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_hud_memory_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_hud_visibility") self.assertIsNotNone(action) action = action_registry.get_action(self.extension_id, "toggle_wireframe") self.assertIsNotNone(action) async def test_action_return_values(self): """Test the return valus for actions match expected cases.""" await omni.usd.get_context().new_stage_async() action_registry = omni.kit.actions.core.get_action_registry() test_keys = ["scene/lights", "guide/grid", "guide/axis"] try: action = action_registry.get_action(self.extension_id, "toggle_camera_visibility") self.assertIsNotNone(action) # First toggle, should return key as camera's are visible by default result = action.execute() self.assertEqual(result, "scene/cameras") # Re-run making invisible again, should do nothing as nothing was toggled result = action.execute(visible=False) self.assertEqual(result, None) # Re-run making visible again, should return the type that was toggled result = action.execute(visible=True) self.assertEqual(result, "scene/cameras") action = action_registry.get_action(self.extension_id, "toggle_viewport_visibility") self.assertIsNotNone(action) result = action.execute(keys=test_keys) self.assertEqual(result, test_keys) # Re-run making invisible again, should do nothing as nothing was toggled result = action.execute(keys=test_keys, visible=False) self.assertEqual(result, []) # Re-run making visible again, should return the type that was toggled sub_keys = [test_keys[0], test_keys[2]] result = action.execute(keys=sub_keys, visible=True) self.assertEqual(result, sub_keys) # Test API to pass sequence of visibility bools (should return nothing as [0] and [2] are vis, and [1] is invis) result = action.execute(keys=test_keys, visible=[True, False, True]) self.assertEqual(result, []) # Test API to pass sequence of visibility bools (should return type of [1] as it is toggling to visible result = action.execute(keys=test_keys, visible=[True, True, True]) self.assertEqual(result, [test_keys[1]]) action = action_registry.get_action(self.extension_id, "toggle_wireframe") self.assertIsNotNone(action) # First toggle, should change from "default" to "wireframe" result = action.execute() self.assertEqual(result, "wireframe") # Re-run, should change fron "wireframe" to "default" result = action.execute() self.assertEqual(result, "default") action = action_registry.get_action(self.extension_id, "top_camera") self.assertIsNotNone(action) result = action.execute() self.assertTrue(result) action = action_registry.get_action(self.extension_id, "front_camera") self.assertIsNotNone(action) result = action.execute() self.assertTrue(result) result = set_camera("/randomCamera") # Test for a camera that doesn't exist self.assertFalse(result) finally: # Return everything to known startup state action_registry.get_action(self.extension_id, "toggle_camera_visibility").execute(visible=True) action_registry.get_action(self.extension_id, "toggle_viewport_visibility").execute(keys=test_keys, visible=True) action_registry.get_action(self.extension_id, "perspective_camera").execute() async def test_hud_action_overrides_parent_visibility(self): """Test that toggling any HUD item to visible will force the parent to visible""" from omni.kit.viewport.utility import get_active_viewport_window import carb.settings try: vp_window = get_active_viewport_window() self.assertIsNotNone(vp_window) self.assertIsNotNone(vp_window.viewport_api) settings = carb.settings.get_settings() hud_vis_path = f"/persistent/app/viewport/{vp_window.viewport_api.id}/hud/visible" settings.set(hud_vis_path, False) await self.wait_n_updates() self.assertFalse(settings.get(hud_vis_path)) action_registry = omni.kit.actions.core.get_action_registry() action = action_registry.get_action(self.extension_id, "toggle_hud_visibility") self.assertIsNotNone(action) action.execute(visible=True, use_setting=True) # Should have forced the parent item back to True await self.wait_n_updates() self.assertTrue(settings.get(hud_vis_path)) finally: pass async def test_ui_toggling(self): """Test that ui toggles visibility and fullscreen correctly""" await omni.usd.get_context().new_stage_async() action_registry = omni.kit.actions.core.get_action_registry() # Make sure it's not hidden to start with self.assertFalse(is_ui_hidden()) action = action_registry.get_action(self.extension_id, "toggle_ui") self.assertIsNotNone(action) result = action.execute() # Make sure it was hidden when toggled self.assertTrue(is_ui_hidden()) result = action.execute() # Make sure it is unhidden again after toggling again self.assertFalse(is_ui_hidden()) action = action_registry.get_action(self.extension_id, "toggle_fullscreen") self.assertIsNotNone(action) await self.wait_n_updates(10) # Make sure we're not fullscreen already self.assertFalse(omni.appwindow.get_default_app_window().is_fullscreen()) result = action.execute() await self.wait_n_updates(10) # Make sure we are in fullscreen now self.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen()) result = action.execute() await self.wait_n_updates(10) # Make sure we are back out of fullscreen self.assertFalse(omni.appwindow.get_default_app_window().is_fullscreen())
9,685
Python
41.858407
125
0.661951
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/__init__.py
from .test_actions import * from .test_visibility import * from .test_extension import *
89
Python
21.499995
30
0.764045
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/test_extension.py
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ['TestExtension'] import omni.kit.actions.core from omni.kit.test import AsyncTestCase class TestExtension(AsyncTestCase): async def setUp(self): self.extension_id = "omni.kit.viewport.actions" async def wait_n_updates(self, n_frames: int = 3): app = omni.kit.app.get_app() for _ in range(n_frames): await app.next_update_async() async def test_extension_start_stop(self): manager = omni.kit.app.get_app().get_extension_manager() ext_id = self.extension_id self.assertTrue(ext_id) self.assertTrue(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, False) for _ in range(10): await omni.kit.app.get_app().next_update_async() self.assertTrue(not manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) for _ in range(10): await omni.kit.app.get_app().next_update_async() self.assertTrue(manager.is_extension_enabled(ext_id))
1,480
Python
36.024999
77
0.686486
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/test_visibility.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.kit.viewport.actions.visibility import VisibilityEdit import carb import omni.kit.app import omni.kit.test import omni.timeline from pxr import Sdf, Usd, UsdGeom from functools import partial from pathlib import Path TEST_DATA_PATH = Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ).resolve().absolute().joinpath("data", "tests") USD_TEST_DATA_PATH = TEST_DATA_PATH.joinpath("usd") class TestVisibilitySetting(omni.kit.test.AsyncTestCase): async def setUp(self): super().setUp() self.usd_context = omni.usd.get_context() await self.usd_context.new_stage_async() # After running each test async def tearDown(self): super().tearDown() @staticmethod def __is_in_set(prim_set: set, prim: Usd.Prim, prim_path: Sdf.Path) -> bool: # pragma: no cover return prim.GetTypeName() in prim_set @staticmethod def __make_callback(prim_set: set): return prim_set async def test_hide_show_skeletons(self): usd_path = USD_TEST_DATA_PATH.joinpath("visibility.usda") success, error = await self.usd_context.open_stage_async(str(usd_path)) self.assertTrue(success, error) stage = self.usd_context.get_stage() is_skel_test = self.__make_callback({"SkelRoot"}) vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_skel_test) vis_edit.run() # Skeleton should still be set to invisible visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility() self.assertEqual(str(visibility), "invisible") # Everything else should be have kept inherited visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") vis_edit = VisibilityEdit(stage, types_to_show=is_skel_test, types_to_hide=None) vis_edit.run() # Skeleton should still be restored to inherited visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") # Everything else should have kept inherited visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") async def test_hide_show_meshes(self): usd_path = USD_TEST_DATA_PATH.joinpath("visibility.usda") success, error = await self.usd_context.open_stage_async(str(usd_path)) self.assertTrue(success, error) stage = self.usd_context.get_stage() is_in_mesh = self.__make_callback({"Mesh", "Cone", "Cube", "Cylinder", "Sphere", "Capsule"}) vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_in_mesh) vis_edit.run() # Skeleton should still be visible visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") # Points should have kept inherited visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") # Everything else should be off or inherited visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility() self.assertEqual(str(visibility), "invisible") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility() self.assertEqual(str(visibility), "invisible") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "invisible") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility() self.assertEqual(str(visibility), "invisible") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility() self.assertEqual(str(visibility), "invisible") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility() self.assertEqual(str(visibility), "invisible") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "invisible") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "invisible") vis_edit = VisibilityEdit(stage, types_to_show=is_in_mesh, types_to_hide=None) vis_edit.run() # Skeleton should still be visible visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") # Points should have kept inherited visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") # Everything else should be restored to inherited visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility() self.assertEqual(str(visibility), "inherited") async def test_hide_show_meshes_instanceable_references(self): usd_path = USD_TEST_DATA_PATH.joinpath("referenced", "scene.usda") success, error = await self.usd_context.open_stage_async(str(usd_path)) self.assertTrue(success, error) stage = self.usd_context.get_stage() is_in_mesh = self.__make_callback({"Mesh", "Cone", "Cube", "Cylinder", "Sphere", "Capsule"}) vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_in_mesh) vis_edit.run() visibility_a = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_0/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility() visibility_b = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_1/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility() self.assertEqual(str(visibility_a), 'invisible') self.assertEqual(str(visibility_b), 'invisible') vis_edit = VisibilityEdit(stage, types_to_show=is_in_mesh, types_to_hide=None) vis_edit.run() visibility_a = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_0/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility() visibility_b = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_1/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility() self.assertEqual(str(visibility_a), 'inherited') self.assertEqual(str(visibility_b), 'inherited') async def __test_hide_show_hide_camera_at_time(self): usd_path = USD_TEST_DATA_PATH.joinpath("cam_visibility.usda") success, error = await self.usd_context.open_stage_async(str(usd_path)) self.assertTrue(success, error) stage = self.usd_context.get_stage() # Default should be visible visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Frontal_50mm")).ComputeVisibility() self.assertEqual(str(visibility), 'inherited') visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Focal_Headlight_50mm")).ComputeVisibility() self.assertEqual(str(visibility), 'inherited') visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Establishing_28mm")).ComputeVisibility() self.assertEqual(str(visibility), 'inherited') visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera")).ComputeVisibility() self.assertEqual(str(visibility), 'inherited') # Hide cameras is_camera = self.__make_callback({"Camera"}) vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_camera) vis_edit.run() visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Frontal_50mm")).ComputeVisibility() self.assertEqual(str(visibility), 'invisible') visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Focal_Headlight_50mm")).ComputeVisibility() self.assertEqual(str(visibility), 'invisible') visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Establishing_28mm")).ComputeVisibility() self.assertEqual(str(visibility), 'invisible') visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera")).ComputeVisibility() self.assertEqual(str(visibility), 'invisible') # Show cameras vis_edit = VisibilityEdit(stage, types_to_show=is_camera, types_to_hide=None) vis_edit.run() visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Frontal_50mm")).ComputeVisibility() self.assertEqual(str(visibility), 'inherited') visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Focal_Headlight_50mm")).ComputeVisibility() self.assertEqual(str(visibility), 'inherited') visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Establishing_28mm")).ComputeVisibility() self.assertEqual(str(visibility), 'inherited') visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera")).ComputeVisibility() self.assertEqual(str(visibility), 'inherited') async def test_hide_show_hide_camera(self): '''Test show and hide of camera works at default time''' await self.__test_hide_show_hide_camera_at_time() async def test_hide_show_hide_camera_at_time(self): '''Test show and hide of camera works at user time''' try: omni.timeline.get_timeline_interface().set_current_time(100) await self.__test_hide_show_hide_camera_at_time() finally: omni.timeline.get_timeline_interface().set_current_time(0) @omni.kit.test.omni_test_registry(guid="1e1fa926-ddf8-11ed-995d-ac91a108fede") async def test_camera_visibility_stage_window_hidden(self): '''Test show and hide of prims that accounts for objects hidden in stage window''' usd_path = USD_TEST_DATA_PATH.joinpath("stage_window_hidden.usda") success, error = await self.usd_context.open_stage_async(str(usd_path)) self.assertTrue(success, error) stage = self.usd_context.get_stage() # Default should be visible def test_visibility(expected): if isinstance(expected, str): expected = [expected] * 4 visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/CameraA")).ComputeVisibility() self.assertEqual(str(visibility), expected[0]) visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/CameraB")).ComputeVisibility() self.assertEqual(str(visibility), expected[1]) visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshA")).ComputeVisibility() self.assertEqual(str(visibility), expected[2]) visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshB")).ComputeVisibility() self.assertEqual(str(visibility), expected[3]) test_visibility('inherited') # Hide all camera and mesh prim_test = self.__make_callback({"Camera", "Mesh"}) vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=prim_test) vis_edit.run() test_visibility('invisible') # Revert back and re-test vis_edit = VisibilityEdit(stage, types_to_show=prim_test, types_to_hide=None) vis_edit.run() test_visibility('inherited') settings = carb.settings.get_settings() igswh = settings.get('/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden') try: settings.set('/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden', True) vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=prim_test) vis_edit.run() test_visibility(['invisible', 'inherited', 'invisible', 'inherited']) # Revert back and re-test vis_edit = VisibilityEdit(stage, types_to_show=prim_test, types_to_hide=None) vis_edit.run() test_visibility('inherited') finally: settings.set('/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden', igswh)
17,167
Python
46.821727
130
0.694472
omniverse-code/kit/exts/omni.assets/omni/assets/yeller.py
import carb import omni.ext class AssetsYellerExtension(omni.ext.IExt): def on_startup(self, ext_id): carb.log_warn('omni.assets extension is deprecated! Please replace your dependency omni.assets -> omni.assets.plugins in extension.toml!') def on_shutdown(self): pass
296
Python
25.999998
146
0.719595
omniverse-code/kit/exts/omni.kit.window.material_swap/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.3" category = "Internal" # 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 = "Material Swap" description="Replaces bound materials" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "usd", "material"] # 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.usd" = {} "omni.ui" = {} "omni.kit.window.filepicker" = {} [[python.module]] name = "omni.kit.window.material_swap"
815
TOML
25.32258
90
0.72638
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/scripts/__init__.py
from .material_swap import *
29
Python
13.999993
28
0.758621
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/scripts/material_swap.py
import os import carb import weakref import omni.ext import omni.kit.ui import omni.usd from typing import Callable from pathlib import Path from pxr import Usd, UsdGeom, Sdf, UsdShade from omni.kit.window.filepicker import FilePickerDialog from omni.kit.widget.filebrowser import FileBrowserItem TEST_DATA_PATH = "" _extension_instance = None class MaterialSwapExtension(omni.ext.IExt): def on_startup(self, ext_id): self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._build_ui() manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) global TEST_DATA_PATH TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests") global _extension_instance _extension_instance = self def _build_ui(self): self._window = omni.kit.ui.Window("Material Swap", 300, 200, menu_path="Window/Material Swap") mat_settings = omni.kit.ui.CollapsingFrame("Material Swap Parameters", True) field_width = 120 self._default_material_name = "None Selected" self._old_mat = omni.kit.ui.TextBox(self._default_material_name) self._old_mat_label = omni.kit.ui.Label("Material to Replace") self._old_mat_selected = omni.kit.ui.Button("Use Selected") self._old_mat_selected.set_clicked_fn(self._get_selectedold_fn) self._old_mat.width = field_width * 3 self._old_mat_label.width = field_width self._old_mat_selected.width = field_width old_row = omni.kit.ui.RowLayout() old_row.add_child(self._old_mat_label) old_row.add_child(self._old_mat) old_row.add_child(self._old_mat_selected) self._new_mat = omni.kit.ui.TextBox(self._default_material_name) self._new_mat_label = omni.kit.ui.Label("Material to Use") self._new_mat_browse = omni.kit.ui.Button("Browse") self._new_mat_browse.set_clicked_fn(self._on_browse_fn) self._new_mat_selected = omni.kit.ui.Button("Use Selected") self._new_mat_selected.set_clicked_fn(self._get_selectednew_fn) def on_filter_item(dialog: FilePickerDialog, item: FileBrowserItem) -> bool: if item and not item.is_folder and dialog.current_filter_option == 0: _, ext = os.path.splitext(item.path) return ext in [".mdl"] return True # create filepicker dialog = FilePickerDialog( "Open File", apply_button_label="Open", click_apply_handler=lambda filename, dirname, o=weakref.ref(self): MaterialSwapExtension._on_file_open(o, dialog, filename, dirname), item_filter_options=["MDL Files (*.mdl)", "All Files (*)"], item_filter_fn=lambda item: on_filter_item(dialog, item), ) dialog.hide() self._new_mat_fp = dialog self._new_mat.width = field_width * 3 self._new_mat_label.width = field_width self._new_mat_browse.width = field_width self._new_mat_selected.width = field_width new_row = omni.kit.ui.RowLayout() new_row.add_child(self._new_mat_label) new_row.add_child(self._new_mat) new_row.add_child(self._new_mat_selected) new_row.add_child(self._new_mat_browse) mat_settings.add_child(old_row) mat_settings.add_child(new_row) # buttons actions = omni.kit.ui.CollapsingFrame("Actions", True) self._ui_swap_button = omni.kit.ui.Button("Swap") self._ui_swap_button.set_clicked_fn(self._on_swap_fn) self._ui_swap_button.width = omni.kit.ui.Percent(30) actions.add_child(self._ui_swap_button) self._window.layout.add_child(mat_settings) self._window.layout.add_child(actions) def _on_swap_fn(self, widget): if self._old_mat.value == self._default_material_name: carb.log_error('"Material To Replace" not set') return if self._new_mat.value == self._default_material_name: carb.log_error('"Material to Use" not set') return stage = self._usd_context.get_stage() for prim in stage.Traverse(): if not prim.GetMetadata("hide_in_stage_window") and omni.usd.is_prim_material_supported(prim): mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() mat_path = mat.GetPath() if mat_path == self._old_mat.value: path = prim.GetPath() omni.kit.commands.execute( "BindMaterial", prim_path=path, material_path=self._new_mat.value, strength=UsdShade.Tokens.weakerThanDescendants, ) def _on_browse_fn(self, widget): self._new_mat_fp.show() @staticmethod def _on_file_open(owner_weak, dialog: FilePickerDialog, filename: str, dirname: str): owner = owner_weak() if not owner: return file_path = "" if dirname: file_path = f"{dirname}/{filename}" elif filename: file_path = filename dialog.hide() if not "omniverse:" in file_path: carb.log_warn("No local file support, please select an Omniverse asset") owner._new_mat.value = "No local file support, please select an Omniverse asset" else: owner._import_file_path = file_path base_name = os.path.basename(owner._import_file_path) file_name, _ = os.path.splitext(os.path.basename(base_name)) file_name = owner._make_valid_identifier(file_name) owner._add_material(file_path, file_name) def _add_material(self, mat_path, mat_name): stage = self._usd_context.get_stage() d_xform = stage.GetDefaultPrim() d_xname = str(d_xform.GetPath()) mat_prim = stage.DefinePrim("{}/Looks/{}".format(d_xname, mat_name), "Material") mat = UsdShade.Material.Get(stage, mat_prim.GetPath()) if mat: shader_prim = stage.DefinePrim("{}/Looks/{}/Shader".format(d_xname, mat_name), "Shader") shader = UsdShade.Shader.Get(stage, shader_prim.GetPath()) if shader: mdl_token = "mdl" shader_out = shader.CreateOutput("out", Sdf.ValueTypeNames.Token) mat.CreateSurfaceOutput(mdl_token).ConnectToSource(shader_out) mat.CreateVolumeOutput(mdl_token).ConnectToSource(shader_out) mat.CreateDisplacementOutput(mdl_token).ConnectToSource(shader_out) shader.GetImplementationSourceAttr().Set(UsdShade.Tokens.sourceAsset) shader.SetSourceAsset(mat_path, mdl_token) shader.SetSourceAssetSubIdentifier(mat_name, mdl_token) self._new_mat.value = str(mat.GetPath()) def _make_valid_identifier(self, identifier): if len(identifier) == 0: return "_" result = identifier[0] if not identifier[0].isalpha(): result = "_" for i in range(len(identifier) - 1): if identifier[i + 1].isalnum(): result += identifier[i + 1] else: result += "_" return result def _on_file_selected_fn(self, widget): carb.log_warn("file selected fn") def _get_selectedold_fn(self, widget): paths = self._selection.get_selected_prim_paths() base_path = paths[0] if len(paths) > 0 else None base_path = Sdf.Path(base_path) if base_path else None if base_path: mat = self._get_material(base_path) self._old_mat.value = str(mat) else: carb.log_error("No selected prim") def _get_selectednew_fn(self, widget): paths = self._selection.get_selected_prim_paths() base_path = paths[0] if len(paths) > 0 else None base_path = Sdf.Path(base_path) if base_path else None if base_path: mat = self._get_material(base_path) self._new_mat.value = str(mat) else: carb.log_error("No selected prim") def _get_material(self, path): stage = self._usd_context.get_stage() prim = stage.GetPrimAtPath(path) p_type = prim.GetTypeName() if p_type == "Material": return path else: return None def on_shutdown(self): if self._new_mat_fp: del self._new_mat_fp self._new_mat_fp = None global _extension_instance _extension_instance = None def get_instance(): global _extension_instance return _extension_instance
8,818
Python
36.688034
145
0.598889
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/tests/__init__.py
from .test_material_swap import *
34
Python
16.499992
33
0.764706
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/tests/test_material_swap.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 unittest import carb import omni.kit.test from pxr import Usd, UsdGeom, Sdf, UsdShade class TestMaterialSwap(omni.kit.test.AsyncTestCase): async def setUp(self): from omni.kit.window.material_swap.scripts.material_swap import TEST_DATA_PATH self._usd_path = TEST_DATA_PATH.absolute() async def tearDown(self): pass async def test_material_swap(self): def get_bound_material(path: str) -> str: prim = omni.usd.get_context().get_stage().GetPrimAtPath(path) mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() if mat: return mat.GetPath().pathString return "" test_file_path = self._usd_path.joinpath("material_swap_test.usda").absolute() await omni.usd.get_context().open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() material_swap = omni.kit.window.material_swap.get_instance() selection = omni.usd.get_context().get_selection() # verify initial state self.assertEqual(get_bound_material('/World/studiohemisphere/Sphere'), "/World/Looks/GroundMat") self.assertEqual(get_bound_material('/World/studiohemisphere/Floor'), "/World/Looks/GroundMat") # select old material selection.set_selected_prim_paths(["/World/Looks/GroundMat"], True) material_swap._get_selectedold_fn(None) await omni.kit.app.get_app().next_update_async() # select new material selection.set_selected_prim_paths(["/World/Looks/PreviewSurfaceTexture"], True) material_swap._get_selectednew_fn(None) await omni.kit.app.get_app().next_update_async() # swap material material_swap._on_swap_fn(None) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # verify change self.assertEqual(get_bound_material('/World/studiohemisphere/Sphere'), "/World/Looks/PreviewSurfaceTexture") self.assertEqual(get_bound_material('/World/studiohemisphere/Floor'), "/World/Looks/PreviewSurfaceTexture")
2,592
Python
41.508196
116
0.689043
omniverse-code/kit/exts/omni.kit.window.material_swap/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.3] - 2021-06-30 ### Changes - Material test optimization ## [1.0.2] - 2021-03-02 ### Changes - Added test ## [1.0.1] - 2020-11-23 ### Changes - Updated to use new FilePicker ## [1.0.0] - 2020-08-20 ### Changes - converted to extension 2.0 - fixed issues with ui errors fixed issue with incorrect usage of GetBoundMaterial fixed issues with hidden and valid mesh types
474
Markdown
21.619047
128
0.689873
omniverse-code/kit/exts/omni.kit.window.material_swap/docs/index.rst
omni.kit.window.material_swap ############################## Material Swap .. toctree:: :maxdepth: 1 CHANGELOG
125
reStructuredText
7.4
30
0.496
omniverse-code/kit/exts/omni.rtx.settings.core/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.5.8" # 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 = "RTX Realtime/PT Renderer Settings" description="Renderer Settings for RTX Realtime/PathTracer" # 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 = "Rendering" # Keywords for the extension keywords = ["kit", "rtx", "rendering"] # 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" # 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" [dependencies] "omni.kit.commands" = {} "omni.ui" = {} "omni.rtx.window.settings" = { } "omni.usd" = {} # Should always load after omni.hydra.rtx, but keep as an optional dependency "omni.hydra.rtx" = {optional = true} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.rtx.settings.core" [[test]] timeout = 600 # OM-51983 args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/renderer/resolution/width=128", "--/app/renderer/resolution/height=128", "--no-window" ] stdoutFailPatterns.exclude = [ ] dependencies = [ "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.ui_test", "omni.hydra.rtx", "omni.kit.window.viewport" ]
2,080
TOML
29.15942
118
0.718269
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/extension.py
import omni.ext from omni.rtx.window.settings import RendererSettingsFactory from .widgets.common_widgets import CommonSettingStack from .widgets.post_widgets import PostSettingStack from .widgets.pt_widgets import PTSettingStack from .widgets.rt_widgets import RTSettingStack class RTXSettingsExtension(omni.ext.IExt): MENU_PATH = "Rendering" rendererNames = ["Real-Time", "Interactive (Path Tracing)"] stackNames = ["Common", "Ray Tracing", "Path Tracing", "Post Processing"] def on_startup(self): RendererSettingsFactory.register_stack(self.stackNames[0], CommonSettingStack) RendererSettingsFactory.register_stack(self.stackNames[1], RTSettingStack) RendererSettingsFactory.register_stack(self.stackNames[2], PTSettingStack) RendererSettingsFactory.register_stack(self.stackNames[3], PostSettingStack) RendererSettingsFactory.register_renderer( self.rendererNames[0], [self.stackNames[0], self.stackNames[1], self.stackNames[3]] ) RendererSettingsFactory.register_renderer( self.rendererNames[1], [self.stackNames[0], self.stackNames[2], self.stackNames[3]] ) RendererSettingsFactory.build_ui() def on_shutdown(self): for renderer in self.rendererNames: RendererSettingsFactory.unregister_renderer(renderer) for stack in self.stackNames: RendererSettingsFactory.unregister_stack(stack) RendererSettingsFactory.build_ui()
1,496
Python
40.583332
95
0.731952
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/common_widgets.py
import omni.ui as ui from omni.kit.widget.settings import SettingType import omni.kit.commands from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame from omni.kit.widget.settings import SettingsWidgetBuilder import carb class GeometrySettingsFrame(SettingsCollectionFrame): """ Geometry """ def _build_ui(self): tbnMode = ["Auto", "CPU", "GPU", "Force GPU"] scale_option = {"Default": -1, "Small - 1cm": 0.01, "Medium - 10 cm": 0.1, "Big - 100 cm": 1} with ui.CollapsableFrame("Misc Settings", height=0): with ui.VStack(height=0, spacing=5): self._add_setting_combo("Normal & Tangent Space Generation Mode", "/rtx/hydra/TBNFrameMode", tbnMode, tooltip="\nMode selection for vertex Normals and Tangents generation. Options are:" "\n-AUTO: Selects the mode depending on available data and data update pattern." "\n-CPU: Uses mikktspace to generate tangent basis on the CPU." "\n-GPU: Allows normal and tangent basis update on the GPU to avoid the CPU overhead, such as for deforming meshes." "\n-Force GPU: Forces GPU mode.") self._add_setting(SettingType.BOOL, "Back Face Culling", "/rtx/hydra/faceCulling/enabled", tooltip="\nEnables back face culling for 'Single Sided' primitives." "\nThis applies to UsdGeom prims set to 'Single Sided' since the Double Sided flag is ignored.") self._add_setting(SettingType.BOOL, "USD ST Main Texcoord as Default UV Set", "/rtx/hydra/uvsets/stIsDefaultUvSet", tooltip="\nIf enabled, ST is considered to be the default UV set name.") self._add_setting(SettingType.BOOL, "Hide Geometry That Uses Opacity (debug)", "/rtx/debug/onlyOpaqueRayFlags", tooltip="\nAllows hiding all objects which have opacity enabled in their material.") self._add_setting(SettingType.BOOL, "Instance Selection", "/rtx/hydra/instancePickingEnabled", tooltip="\nEnables the picking of instances.") # if set to zero, override to scene unit, which means the scale factor would be 1 self._add_setting_combo("Renderer-Internal Meters Per Unit", "/rtx/scene/renderMeterPerUnit", scale_option, tooltip="\nNumber of units per meter used by the renderer relative to the scene scale." "\nSome materials depend on scene scale, such as subsurface scattering and volumetric shading.") self._add_setting(SettingType.FLOAT, "Ray Offset (0 = auto)", "/rtx/raytracing/rayOffset", 0.0, 5.0, 0.001, tooltip="\nOffset used to prevent ray-triangle self intersections." ) self._add_setting(SettingType.FLOAT, "Points Default Width", "/persistent/rtx/hydra/points/defaultWidth", tooltip="\nUses this value if width is not specified in UsdGeomPoints.") with ui.CollapsableFrame("Wireframe Settings", height=0): with ui.VStack(height=0, spacing=5): self._add_setting(SettingType.BOOL, "Per-primitive Wireframe uses World Space Thickness", "/rtx/wireframe/wireframeThicknessWorldSpace", tooltip="\nInterprets the per-primitive wireframe thickness value in world space instead of screen space.") self._add_setting(SettingType.BOOL, "Global Wireframe uses World Space Thickness", "/rtx/wireframe/globalWireframeThicknessWorldSpace", tooltip="\nInterprets the global wireframe thickness value in world space instead of screen space.") self._add_setting(SettingType.FLOAT, "Thickness", "/rtx/wireframe/wireframeThickness", 0.1, 100, 0.1, tooltip="\nWireframe thickness in wireframe mode.") def clear_refinement_overrides(): omni.kit.commands.execute("ClearRefinementOverrides") with ui.CollapsableFrame("Subdivision Settings", height=0): with ui.VStack(height=0, spacing=5): self._add_setting(SettingType.INT, "Global Refinement Level", "/rtx/hydra/subdivision/refinementLevel", 0, 8, hard_range=True, tooltip="\nThe refinement level for all primitives with Subdivision Schema not set to None." "\nEach increment increases the mesh triangle count by a factor of 4.") self._add_setting(SettingType.BOOL, "Feature-Adaptive Refinement", "/rtx/hydra/subdivision/adaptiveRefinement", tooltip="\nIncreases or reduces the refinement level based on geometric features." "\nThis reduces the number of triangles used in flat areas for example.") ui.Button("Clear Refinement Override in All Prims", clicked_fn=clear_refinement_overrides, tooltip="\nClears the Refinement Override set in all Prims.") def clear_splits_overrides(): omni.kit.commands.execute("ClearCurvesSplitsOverridesCommand") with ui.CollapsableFrame("Curves Settings", height=0): with ui.VStack(height=0, spacing=5): self._add_setting(SettingType.INT, "Global Number of BVH Splits", "/rtx/hydra/curves/splits", 1, 8, hard_range=True, tooltip="\nHigher number of splits results in faster rendering but longer BVH build time." "\nThe speed up depends on the geometry: long and thin curve segments tend to benefit from more splits." "\nMemory used by the BVH grows linearly with the number of splits.") ui.Button("Clear Number of BVH Splits Overrides in All Prims", clicked_fn=clear_splits_overrides, tooltip="\nClears the Number of BVH Splits Refinement Override set in all Prims.") class MaterialsSettingsFrame(SettingsCollectionFrame): """ Materials """ def _on_change(self, *_): self._rebuild() def _build_ui(self): self._change_cb1 = omni.kit.app.SettingChangeSubscription("/app/renderer/skipMaterialLoading", self._on_change) self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx-transient/resourcemanager/enableTextureStreaming", self._on_change) # The setting is maxMipCount, to make it more user friendly we expose it in the API as max resolution texture_mip_sizes = { "64": 7, "128": 8, "256": 9, "512": 10, "1024": 11, "2048": 12, "4096": 13, "8192": 14, "16384": 15, "32768": 16, } self._add_setting(SettingType.BOOL, "Disable Material Loading", "/app/renderer/skipMaterialLoading", tooltip="\nScenes will be loaded without materials. This can lower scene loading time.") if not self._settings.get("/app/renderer/skipMaterialLoading"): with ui.CollapsableFrame("Texture Compression Settings", height=0): with ui.VStack(height=0, spacing=5): self._add_setting_combo("Max Resolution", "/rtx-transient/resourcemanager/maxMipCount", texture_mip_sizes, tooltip="\nTextures larger than this will be downsampled at this resolution.") self._add_setting(SettingType.INT, "Compression Size Threshold", "/rtx-transient/resourcemanager/compressionMipSizeThreshold", 0, 8192, tooltip="\nTextures smaller than this size won't be compressed. 0 disables compression.") self._add_setting(SettingType.BOOL, "Normal Map Mip-Map Generation (toggling requires scene reload)", "/rtx-transient/resourcemanager/genMipsForNormalMaps", tooltip="\nEnables mip-map generation for normal maps to reduce memory usage at the expense of quality.") # if self._settings.get("/rtx-transient/resourcemanager/genMipsForNormalMaps"): # self._add_setting(SettingType.BOOL, "Normal Map Roughness generation (toggling requires scene reload)", "/rtx-transient/resourcemanager/createNormalRoughness", tooltip="\nEnables roughness generation for normal maps for improved specular reflection with mip mapping enabled.") with ui.CollapsableFrame("Texture Streaming Settings", height=0): with ui.VStack(height=0, spacing=5): self._add_setting(SettingType.BOOL, "Enable Texture Streaming (toggling requires scene reload)", "/rtx-transient/resourcemanager/enableTextureStreaming", tooltip="\nEnables texture streaming.") if self._settings.get("/rtx-transient/resourcemanager/enableTextureStreaming"): self._add_setting(SettingType.FLOAT, " Memory Budget (% of GPU memory)", "/rtx-transient/resourcemanager/texturestreaming/memoryBudget", 0, 1, tooltip="\nLimits the GPU memory budget used for texture streaming.") self._add_setting(SettingType.INT, " Budget Per Request (in MB)", "/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", 0, 10000, tooltip="\nMaximum budget per streaming request. 0 = unlimited but could lead to stalling during streaming." "\nHigh or unlimited budget could lead to stalling during streaming.") with ui.CollapsableFrame("MDL Settings", height=0): with ui.VStack(height=0, spacing=5): self._add_setting(SettingType.FLOAT, "Animation Time Override", "/rtx/animationTime", tooltip="\nOverrides the time value provided to MDL materials.") self._add_setting(SettingType.BOOL, "Animation Time Use Wallclock", "/rtx/animationTimeUseWallclock", tooltip="\nUse actual elapsed time for animation instead of simulated time.") def destroy(self): self._change_cb1 = None self._change_cb2 = None super().destroy() class LightingSettingsFrame(SettingsCollectionFrame): """ Lighting """ def _build_ui(self): with ui.CollapsableFrame("Light Visibility Settings", height=0): with ui.VStack(height=0, spacing=5): # Common show light setting for all render modes - this makes the /pathracing/showLights and /directLighting/showLights deprecated and should be used instead # see LightTypes.hlslh for enum show_lights_settings = { "Per-Light Enable": 0, "Force Enable": 1, "Force Disable": 2 } self._add_setting_combo("Show Area Lights In Primary Rays", "/rtx/raytracing/showLights", show_lights_settings, tooltip="\nDefines if area lights are visible or invisible in primary rays.") self._add_setting(SettingType.FLOAT, "Invisible Lights Roughness Threshold", "/rtx/raytracing/invisLightRoughnessThreshold", 0, 1, 0.001, tooltip="\nDefines the roughness threshold below which lights invisible in primary rays" "\nare also invisible in reflections and refractions.") self._add_setting(SettingType.BOOL, "Use First Distant Light & First Dome Light Only", "/rtx/scenedb/skipMostLights", tooltip="\nDisable all lights except the first distant light and first dome light.") self._add_setting(SettingType.FLOAT, "Shadow Bias", "/rtx/raytracing/shadowBias", 0.0, 5.0, 0.001, tooltip="\nOffset applied for shadow ray origin along the surface normal. Reduces self-shadowing artifacts.") with ui.CollapsableFrame("Dome Light Settings", height=0): with ui.VStack(height=0, spacing=5): dome_lighting_sampling_type = { "Image-Based Lighting": 0, "Approximated Image-Based Lighting": 4, "Environment Mapped Image-Based Lighting": 3 } self._add_setting_combo("Lighting Mode", "/rtx/domeLight/upperLowerStrategy", dome_lighting_sampling_type, tooltip="\n-Image-Based Lighting: Most accurate even for high-frequency Dome Light textures. Can introduce sampling artefacts in real-time mode." "\n-Approximated Image-Based Lighting: Fast and artefacts-free sampling in real-time mode but only works well with a low-frequency texture," "\nfor example a sky with no sun disc where the sun is instead a separate Distant Light. Requires enabling Direct Lighting denoiser." "\n-Limited Image-Based Lighting: Only sampled for reflection and refraction. Fastest, but least accurate. Good for cases where the Dome Light" "\ncontributes less than other light sources.") dome_texture_resolution_items = { "16": 16, "32": 32, "64": 64, "128": 128, "256": 256, "512": 512, "1024": 1024, "2048": 2048, "4096": 4096, "8192": 8192, } self._add_setting_combo("Baking Resolution", "/rtx/domeLight/baking/resolution", dome_texture_resolution_items, tooltip="\nThe baking resolution of the Dome Light texture when an MDL material is used as its image source.") class GlobalVolumetricEffectsSettingsFrame(SettingsCollectionFrame): """ Global Volumetric Effects Common Settings RT & PT """ def _frame_setting_path(self): return "/rtx/raytracing/globalVolumetricEffects/enabled" def _build_ui(self): self._add_setting(SettingType.FLOAT, "Fog Height", "/rtx/raytracing/inscattering/atmosphereHeight", -2000, 100000, 10, tooltip="\nHeight in world units (centimeters) at which the medium ends. Useful for atmospheres with distant lights or dome lights.") self._add_setting(SettingType.FLOAT, "Fog Height Fall Off", "/rtx/pathtracing/ptvol/fogHeightFallOff", 10, 2000, 1, tooltip="\nExponential decay of the fog above the Fog Height.") self._add_setting(SettingType.FLOAT, "Maximum inscattering Distance", "/rtx/raytracing/inscattering/maxDistance", 10, 1000000, tooltip="\nMaximum depth in world units (centimeters) the voxel grid is allocated to." "\nIf set to 10,000 with 10 depth slices, each slice will span 1,000 units (assuming a slice distribution exponent of 1)." "\nIdeally this should be kept as low as possible without causing artifacts to make the most of the fixed number of depth slices.") self._add_setting(SettingType.FLOAT, "Density Multiplier", "/rtx/raytracing/inscattering/densityMult", 0, 2, 0.001, tooltip="\nScales the fog density.") self._add_setting(SettingType.FLOAT, "Transmittance Measurment Distance", "/rtx/raytracing/inscattering/transmittanceMeasurementDistance", 0.0001, 1000000, 10, tooltip="\nControls how far light can travel through fog. Lower values yield thicker fog.") self._add_setting(SettingType.COLOR3, "Transmittance Color", "/rtx/raytracing/inscattering/transmittanceColor", tooltip="\nAssuming a white light, it represents its tint after traveling a number of units through" "\nthe volume as specified in Transmittance Measurement Distance.") self._add_setting(SettingType.COLOR3, "Single Scattering Albedo", "/rtx/raytracing/inscattering/singleScatteringAlbedo", tooltip="\nThe ratio of scattered-light to attenuated-light for an interaction with the volume. Values closer to 1 indicate high scattering.") self._add_setting(SettingType.FLOAT, "Anisotropy Factor (g)", "/rtx/raytracing/inscattering/anisotropyFactor", -0.999, 0.999, 0.01, tooltip="\nAnisotropy of the volumetric phase function, or the degree of light scattering asymmetry." "\n-1 is back-scattered, 0 is isotropic, 1 is forward-scattered.") with ui.CollapsableFrame("Density Noise Settings", height=0): with ui.VStack(height=0, spacing=5): self._add_setting(SettingType.BOOL, "Apply Density Noise", "/rtx/raytracing/inscattering/useDetailNoise", tooltip="\nEnables modulating the density with a noise. Enabling this option can reduce performance.") self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/raytracing/inscattering/useDetailNoise", self._on_change) if self._settings.get("/rtx/raytracing/inscattering/useDetailNoise"): self._add_setting(SettingType.FLOAT, " World Scale", "/rtx/raytracing/inscattering/detailNoiseScale", 0.0, 1, 0.00001, tooltip="\nA scale multiplier for the noise. Smaller values produce more sparse noise.") self._add_setting(SettingType.FLOAT, " Animation Speed X", "/rtx/raytracing/inscattering/noiseAnimationSpeedX", -1.0, 1.0, 0.01, tooltip="\nThe X vector for the noise shift when animated.") self._add_setting(SettingType.FLOAT, " Animation Speed Y", "/rtx/raytracing/inscattering/noiseAnimationSpeedY", -1.0, 1.0, 0.01, tooltip="\nThe Y vector for the noise shift when animated.") self._add_setting(SettingType.FLOAT, " Animation Speed Z", "/rtx/raytracing/inscattering/noiseAnimationSpeedZ", -1.0, 1.0, 0.01, tooltip="\nThe Z vector for the noise shift when animated.") self._add_setting(SettingType.FLOAT, " Scale Min", "/rtx/raytracing/inscattering/noiseScaleRangeMin", -1.0, 5.0, 0.01, tooltip="\nA range to map the noise values of each noise octave." "\nTypically these should be 0 and 1." "\nTo make sparse points in the noise less sparse a higher Min can be used, or a lower Max for dense points to be less dense.") self._add_setting(SettingType.FLOAT, " Scale Max", "/rtx/raytracing/inscattering/noiseScaleRangeMax", -1.0, 5.0, 0.01, tooltip="\nA range to map the noise values of each noise octave." "\nTypically these should be 0 and 1. To make sparse points in the noise less sparse" "\na higher Min can be used, or a lower Max for dense points to be less dense.") self._add_setting(SettingType.INT, " Octave Count", "/rtx/raytracing/inscattering/noiseNumOctaves", 1, 8, tooltip="\nA higher octave count results in greater noise detail, at the cost of performance.") def destroy(self): self._change_cb1 = None super().destroy() class SimpleFogSettingsFrame(SettingsCollectionFrame): """ Simple Fog """ def _frame_setting_path(self): return "/rtx/fog/enabled" def _build_ui(self): self._add_setting(SettingType.COLOR3, "Color", "/rtx/fog/fogColor", tooltip="\nThe color or tint of the fog volume.") self._add_setting(SettingType.FLOAT, "Intensity", "/rtx/fog/fogColorIntensity", 1, 1000000, 1, tooltip="\nThe intensity of the fog effect.") self._add_setting(SettingType.BOOL, "Height-based Fog - Use +Z Axis", "/rtx/fog/fogZup/enabled", tooltip="\nUse positive Z axis for height-based fog. Otherwise use the positive Y axis.") self._add_setting(SettingType.FLOAT, "Height-based Fog - Plane Height", "/rtx/fog/fogStartHeight", -1000000, 1000000, 0.01, tooltip="\nThe starting height (in meters) for height-based fog.") self._add_setting(SettingType.FLOAT, "Height Density", "/rtx/fog/fogHeightDensity", 0, 1, 0.001, tooltip="\nDensity of the height-based fog. Higher values result in thicker fog.") self._add_setting(SettingType.FLOAT, "Height Falloff", "/rtx/fog/fogHeightFalloff", 0, 1000, 0.002, tooltip="\nRate at which the height-based fog falls off.") self._add_setting(SettingType.FLOAT, "Start Distance to Camera", "/rtx/fog/fogStartDist", 0, 1000000, 0.1, tooltip="\nDistance from the camera at which the fog begins.") self._add_setting(SettingType.FLOAT, "End Distance to Camera", "/rtx/fog/fogEndDist", 0, 1000000, 0.1, tooltip="\nDistance from the camera at which the fog achieves maximum density.") self._add_setting(SettingType.FLOAT, "Distance Density", "/rtx/fog/fogDistanceDensity", 0, 1, 0.001, tooltip="\nThe fog density at the End Distance.") def destroy(self): super().destroy() class FlowSettingsFrame(SettingsCollectionFrame): """ Flow """ def _frame_setting_path(self): return "/rtx/flow/enabled" def _build_ui(self): self._add_setting(SettingType.BOOL, "Flow in Real-Time Ray Traced Shadows", "/rtx/flow/rayTracedShadowsEnabled") self._add_setting(SettingType.BOOL, "Flow in Real-Time Ray Traced Reflections", "/rtx/flow/rayTracedReflectionsEnabled") self._add_setting(SettingType.BOOL, "Flow in Real-Time Ray Traced Translucency", "/rtx/flow/rayTracedTranslucencyEnabled") self._add_setting(SettingType.BOOL, "Flow in Path-Traced Mode", "/rtx/flow/pathTracingEnabled") self._add_setting(SettingType.BOOL, "Flow in Path-Traced Mode Shadows", "/rtx/flow/pathTracingShadowsEnabled") self._add_setting(SettingType.BOOL, "Composite with Flow Library Renderer", "/rtx/flow/compositeEnabled") self._add_setting(SettingType.BOOL, "Use Flow Library Self Shadow", "/rtx/flow/useFlowLibrarySelfShadow") self._add_setting(SettingType.INT, "Max Blocks", "/rtx/flow/maxBlocks") def destroy(self): super().destroy() class IndexCompositeSettingsFrame(SettingsCollectionFrame): """ NVIDIA IndeX Compositing """ def _frame_setting_path(self): return "/rtx/index/compositeEnabled" def _build_ui(self): ui.Label("You can activate IndeX composite rendering for individual Volume or Points prims " "by enabling their 'Use IndeX compositing' property.", word_wrap=True) ui.Separator() depth_compositing_settings = { "Disable": 0, "Before Anti-Aliasing": 1, "After Anti-Aliasing": 2, "After Anti-Aliasing (Stable Depth)": 3 } self._add_setting_combo( "Depth Compositing", "/rtx/index/compositeDepthMode", depth_compositing_settings, tooltip="Depth-correct compositing between renderers") self._add_setting( SettingType.FLOAT, "Color Scaling", "/rtx/index/colorScale", 0.0, 100.0, tooltip="Scale factor for color output", ) self._add_setting( SettingType.BOOL, "sRGB Conversion", "/rtx/index/srgbConversion", tooltip="Apply color space conversion to IndeX rendering", ) self._add_setting( SettingType.INT, "Resolution Scaling", "/rtx/index/resolutionScale", 1, 100, tooltip="Reduces the IndeX rendering resolution (in percent relative to the viewport resolution)", ) self._add_setting( SettingType.INT, "Rendering Samples", "/rtx/index/renderingSamples", 1, 32, tooltip="Number of samples per pixel used during rendering", ) self._add_setting( SettingType.FLOAT, "Default Point Width", "/rtx/index/defaultPointWidth", tooltip="Default point width for new point clouds loaded from USD. If set to 0, a simple heuristic will be used.", ) def destroy(self): super().destroy() class DebugViewSettingsFrame(SettingsCollectionFrame): """ Debug View """ def _on_debug_view_change(self, *_): self._rebuild() def _build_ui(self): debug_view_items = { "Off": "", "RT Developer Debug Texture": "developerDebug", "3D Motion Vectors [WARNING: Flashing Colors]": "targetMotion", "3D Motion Vector Arrows [WARNING: Flashing Colors]": "targetMotionArrows", "3D Final Motion Vector Arrows [WARNING: Flashing Colors]": "finalMotion", "Barycentrics": "barycentrics", "Beauty After Tonemap": "beautyPostTonemap", "Beauty Before Tonemap": "beautyPreTonemap", "Depth": "depth", "Instance ID": "instanceId", "Interpolated Normal": "normal", "Heat Map: Any Hit": "anyHitCountHeatMap", "Heat Map: Intersection": "intersectionCountHeatMap", "Heat Map: Timing": "timingHeatMap", "SDG: Cross Correspondence": "sdgCrossCorrespondence", "SDG: Motion": "sdgMotion", "Tangent U": "tangentu", "Tangent V": "tangentv", "Texture Coordinates 0": "texcoord0", "Texture Coordinates 1": "texcoord1", "Triangle Normal": "triangleNormal", "Triangle Normal (OctEnc)": "triangleNormalOctEnc", # ReLAX Only "Wireframe": "wire", "RT Ambient Occlusion": "ao", "RT Caustics": "caustics", "RT Denoised Dome Light": "denoisedDomeLightingTex", "RT Denoised Sampled Lighting": "rtDenoisedSampledLighting", "RT Denoised Sampled Lighting Diffuse": "rtDenoiseSampledLightingDiffuse", # ReLAX Only "RT Denoised Sampled Lighting Specular": "rtDenoiseSampledLightingSpecular", # ReLAX Only "RT Diffuse GI": "indirectDiffuse", "RT Diffuse GI (Not Accumulated)": "indirectDiffuseNonAccum", "RT Diffuse Reflectance": "diffuseReflectance", "RT Material Normal": "materialGeometryNormal", "RT Material Normal (OctEnc)": "materialGeometryNormalOctEnc", # ReLAX Only "RT Matte Object Compositing Alpha": "matteObjectAlpha", "RT Matte Object Mask": "matteObjectMask", "RT Matte Object View Before Postprocessing": "matteBeforePostprocessing", "RT Noisy Dome Light": "noisyDomeLightingTex", "RT Noisy Sampled Lighting": "rtNoisySampledLighting", "RT Noisy Sampled Lighting (Not Accumulated)": "rtNoisySampledLightingNonAccum", "RT Noisy Sampled Lighting Diffuse": "rtNoisySampledLightingDiffuse", # ReLAX Only "RT Noisy Sampled Lighting Diffuse (Not Accumulated)": "sampledLightingDiffuseNonAccum", "RT Noisy Sampled Lighting Specular": "rtNoisySampledLightingSpecular", # ReLAX Only "RT Noisy Sampled Lighting Specular (Not Accumulated)": "sampledLightingSpecularNonAccum", "RT Radiance": "radiance", "RT Subsurface Radiance": "subsurface", "RT Subsurface Transmission Radiance": "subsurfaceTransmission", "RT Reflections": "reflections", "RT Reflections (Not Accumulated)": "reflectionsNonAccum", "RT Reflections 3D Motion Vectors [WARNING: Flashing Colors]": "reflectionsMotion", "RT Roughness": "roughness", "RT Shadow (last light)": "shadow", "RT Specular Reflectance": "reflectance", "RT Translucency": "translucency", "RT World Position": "worldPosition", "PT Adaptive Sampling Error [WARNING: Flashing Colors]": "PTAdaptiveSamplingError", "PT Denoised Result": "pathTracerDenoised", "PT Noisy Result": "pathTracerNoisy", "PT AOV Background": "PTAOVBackground", "PT AOV Diffuse Filter": "PTAOVDiffuseFilter", "PT AOV Direct Illumation": "PTAOVDI", "PT AOV Global Illumination": "PTAOVGI", "PT AOV Reflections": "PTAOVReflections", "PT AOV Reflection Filter": "PTAOVReflectionFilter", "PT AOV Refractions": "PTAOVRefractions", "PT AOV Refraction Filter": "PTAOVRefractionFilter", "PT AOV Self-Illumination": "PTAOVSelfIllum", "PT AOV Volumes": "PTAOVVolumes", "PT AOV World Normal": "PTAOVWorldNormals", "PT AOV World Position": "PTAOVWorldPos", "PT AOV Z-Depth": "PTAOVZDepth", "PT AOV Multimatte0": "PTAOVMultimatte0", "PT AOV Multimatte1": "PTAOVMultimatte1", "PT AOV Multimatte2": "PTAOVMultimatte2", "PT AOV Multimatte3": "PTAOVMultimatte3", "PT AOV Multimatte4": "PTAOVMultimatte4", "PT AOV Multimatte5": "PTAOVMultimatte5", "PT AOV Multimatte6": "PTAOVMultimatte6", "PT AOV Multimatte7": "PTAOVMultimatte7", } self._add_setting_searchable_combo("Render Target", "/rtx/debugView/target", debug_view_items, "Off", "\nA list of all render passes which can be visualized.") debug_view_target = self._settings.get("/rtx/debugView/target") # Trigger the combo update to reflect the current selection when the ui is rebuilt self._settings.set("/rtx/debugView/target", debug_view_target); # Subscribe this frame to the target setting so we can show the heat map controls if necessary. # This will remove the subscription from the searchable combo, but we will have a chance to update it # because the new callback does a rebuild. self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/debugView/target", self._on_debug_view_change) is_timing_heat_map = debug_view_target == "timingHeatMap" is_any_hit_count_heat_map = debug_view_target == "anyHitCountHeatMap" is_intersection_count_heat_map = debug_view_target == "intersectionCountHeatMap" if is_timing_heat_map or is_any_hit_count_heat_map or is_intersection_count_heat_map: # 'heat_map_view_items' MUST perfectly match with 'HeatMapSelectablePass' in 'RtxRendererContext.h' heat_map_view_items = { "GBuffer RT": 1, "Path Tracing": 2, "Shadow RT": 3, "Deferred LTC Lighting RT": 4, "Deferred Sampled Lighting RT": 5, "Reflections LTC RT ": 6, "Reflections Sampled RT": 7, "Back Lighting": 8, "Translucency RT": 9, "SSS RT": 10, "Transmission RT": 11, "Indirect Diffuse RT (Apply Cache)": 12, "Ray Traced Ambient Occlusion": 13 } # 'heat_map_color_palette_items' MUST perfectly match with condition in 'temperature' function in 'DebugView.cs.hlsl' heat_map_color_palette_items = { "Rainbow": 0, "Viridis": 1, "Turbo": 2, "Plasma": 3 } self._add_setting_combo(" Pass To Visualize ", "/rtx/debugView/heatMapPass", heat_map_view_items) if is_timing_heat_map: self._add_setting(SettingType.FLOAT, " Maximum Time (µs)", "/rtx/debugView/heatMapMaxTime", 0, 100000.0, 1.0) elif is_any_hit_count_heat_map: self._add_setting(SettingType.INT, " Maximum Any Hit", "/rtx/debugView/heatMapMaxAnyHitCount", 1, 100) elif is_intersection_count_heat_map: self._add_setting(SettingType.INT, " Maximum Intersection", "/rtx/debugView/heatMapMaxIntersectionCount", 1, 100) self._add_setting_combo(" Color Palette", "/rtx/debugView/heatMapColorPalette", heat_map_color_palette_items) self._add_setting(SettingType.BOOL, " Show Color Bar", "/rtx/debugView/heatMapOverlayHeatMapScale") else: self._add_setting(SettingType.FLOAT, " Output Value Scaling", "/rtx/debugView/scaling", -1000000, 1000000, 1.0, tooltip="\nScales the output value by this factor. Useful to accentuate differences.") class MaterialFlattenerSettingsFrame(SettingsCollectionFrame): """ Material Flattening """ def _build_ui(self): import carb if not carb.settings.get_settings().get("/rtx/materialflattener/enabled"): ui.Label("Material flattener disabled, rerun with --/rtx/materialflattener/enabled=true") else: planarProjectionPlaneAxes = ["auto", "xy", "xz", "yz"] self._add_setting_combo("Planar Projection Plane Axes", "/rtx/materialflattener/planarProjectionPlaneAxes", planarProjectionPlaneAxes) self._add_setting(SettingType.BOOL, "Show Decal Sources", "/rtx/materialflattener/showSources") self._add_setting(SettingType.BOOL, "Live Baking", "/rtx/materialflattener/liveBaking") self._add_setting(SettingType.BOOL, "Rebaking", "/rtx/materialflattener/rebaking") self._add_setting(SettingType.BOOL, "Clear before baking", "/rtx/materialflattener/clearMaterialInputsBeforeBaking") coverageSamples = ["Disabled", "4", "16", "64", "256"] self._add_setting_combo("Decal Antialiasing Samples", "/rtx/materialflattener/decalCoverageSamples", coverageSamples) self._add_setting(SettingType.BOOL, "Disable tile budget", "/rtx/materialflattener/disableTileBudget") self._add_setting(SettingType.INT, "Number of tiles per frame", "/rtx/materialflattener/maxNumTilesToBakePerFrame") self._add_setting(SettingType.INT, "Number of texels per frame", "/rtx/materialflattener/maxNumTexelsToBakePerFrame") self._add_setting(SettingType.INT, "Number of material components per bake pass", "/rtx/materialflattener/numMaterialComponentsPerBakePass", 1, 12) self._add_setting(SettingType.INT, "VTex Group to bake (-1 ~ all)", "/rtx/materialflattener/vtexGroupToBake", -1, 1023) self._add_setting(SettingType.BOOL, "Radius based tile residency", "/rtx/materialflattener/radiusBasedResidency") self._add_setting(SettingType.FLOAT, "Radius based tile residency - radius", "/rtx/materialflattener/radiusBasedResidencyRadius", 0, 10000, 0.1) self._add_setting(SettingType.FLOAT, "Lod: derivative scale", "/rtx/virtualtexture/derivativeScale", 0.01, 100, 0.01) self._add_setting(SettingType.FLOAT, "Decal distance tolerance", "/rtx/materialflattener/decalDistanceTolerance", 0, 1000, 0.01) self._add_setting(SettingType.FLOAT, "Sampling LOD Bias", "/rtx/textures/lodBias", -15, 15, 0.01) self._add_setting(SettingType.INT, "VTex Group ID color option (0 = disabled)", "/rtx/virtualtexture/colorCodeByVtexGroupIdOption", 0, 4) self._add_setting(SettingType.INT, "Baking LOD Bias (on top of Sampling LOD bias)", "/rtx/materialflattener/bakingLodBias", -15, 12) class CommonSettingStack(RTXSettingsStack): def __init__(self) -> None: self._stack = ui.VStack(spacing=7, identifier=__class__.__name__) with self._stack: GeometrySettingsFrame("Geometry", parent=self) MaterialsSettingsFrame("Materials", parent=self) LightingSettingsFrame("Lighting", parent=self) SimpleFogSettingsFrame("Simple Fog", parent=self) GlobalVolumetricEffectsSettingsFrame("Global Volumetric Effects", parent=self) FlowSettingsFrame("Flow", parent=self) # Only show IndeX settings if the extension is loaded if carb.settings.get_settings().get("/nvindex/compositeRenderingMode"): IndexCompositeSettingsFrame("NVIDIA IndeX Compositing", parent=self) # MaterialFlattenerSettingsFrame("Material Flattener", parent=self) DebugViewSettingsFrame("Debug View", parent=self)
36,215
Python
69.459144
302
0.638133
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/post_widgets.py
import omni.kit.app import omni.ui as ui from omni.kit.widget.settings import SettingType from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame import carb.settings class ToneMappingSettingsFrame(SettingsCollectionFrame): """ Tone Mapping """ def _on_tonemap_change(self, *_): self._rebuild() def _build_ui(self): # The main tonemapping layout contains only the combo box. All the other options # are saved in a different layout which can be swapped out in case the tonemapper changes. tonemapper_ops = [ "Clamp", "Linear (Off)", "Reinhard", "Modified Reinhard", "HejlHableAlu", "HableUc2", "Aces", "Iray", ] self._add_setting_combo("Tone Mapping Operator", "/rtx/post/tonemap/op", tonemapper_ops, tooltip="\nTone Mapping Operator selector." "\n-Clamp: Leaves the radiance values unchanged, skipping any exposure adjustment." "\n-Linear (Off): Applies the exposure adjustments but leaves the tone values otherwise unchanged." "\n-Reinhard: Operator based on Erik Reinhard's tone mapping work." "\n-Modified Reinhard: Variation of the operator based on Erik Reinhard's tone mapping work." "\n-HejiHableAlu: John Hable's ALU approximation of Jim Heji's operator." "\n-HableUC2: John Hable's Uncharted 2 filmic tone map." "\n-ACES: Operator based on the Academy Color Encoding System." "\n-Iray: Reinhard-based operator that matches the operator used by NVIDIA Iray by default.") tonemapOpIdx = self._settings.get("/rtx/post/tonemap/op") self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/tonemap/op", self._on_change) if tonemapOpIdx == 3: # Modified Reinhard self._add_setting(SettingType.FLOAT, " Max White Luminance", "/rtx/post/tonemap/maxWhiteLuminance", 0, 100, tooltip="\nMaximum HDR luminance value that will map to 1.0 post tonemap.") if tonemapOpIdx == 5: # HableUc2 self._add_setting(SettingType.FLOAT, " White Scale Value", "/rtx/post/tonemap/whiteScale", 0, 100, tooltip="\nMaximum white value that will map to 1.0 post tonemap.") if tonemapOpIdx == 7: # Iray self._add_setting(SettingType.FLOAT, " Crush Blacks", "/rtx/post/tonemap/irayReinhard/crushBlacks", 0, 1, 0.02) self._add_setting(SettingType.FLOAT, " Burn Highlights", "/rtx/post/tonemap/irayReinhard/burnHighlights", 0, 1, 0.02) self._add_setting(SettingType.BOOL, " Burn Highlights per Component", "/rtx/post/tonemap/irayReinhard/burnHighlightsPerComponent") self._add_setting(SettingType.BOOL, " Burn Highlights max Component", "/rtx/post/tonemap/irayReinhard/burnHighlightsMaxComponent") self._add_setting(SettingType.FLOAT, " Saturation", "/rtx/post/tonemap/irayReinhard/saturation", 0, 1, 0.02) if tonemapOpIdx != 0: # Clamp is never using srgb conversion self._add_setting(SettingType.BOOL, " SRGB To Gamma Conversion", "/rtx/post/tonemap/enableSrgbToGamma", tooltip="\nAvailable with Linear/Reinhard/Modified Reinhard/HejiHableAlu/HableUc2 Tone Mapping.") self._add_setting(SettingType.FLOAT, "cm^2 Factor", "/rtx/post/tonemap/cm2Factor", 0, 2, tooltip="\nUse this factor to adjust for scene units being different from centimeters.") self._add_setting(SettingType.FLOAT, "Film ISO", "/rtx/post/tonemap/filmIso", 50, 1600, tooltip="\nSimulates the effect on exposure of a camera's ISO setting.") self._add_setting(SettingType.FLOAT, "Camera Shutter", "/rtx/post/tonemap/cameraShutter", 1, 5000, tooltip="\nSimulates the effect on exposure of a camera's shutter open time.") self._add_setting(SettingType.FLOAT, "F-stop", "/rtx/post/tonemap/fNumber", 1, 20, 0.1, tooltip="\nSimulates the effect on exposure of a camera's f-stop aperture.") self._add_setting(SettingType.COLOR3, "White Point", "/rtx/post/tonemap/whitepoint", tooltip="\nA color mapped to white on the output.") tonemapColorMode = ["sRGBLinear", "ACEScg"] self._add_setting_combo("Tone Mapping Color Space", "/rtx/post/tonemap/colorMode", tonemapColorMode, tooltip="\nTone Mapping Color Space selector.") self._add_setting(SettingType.FLOAT, "Wrap Value", "/rtx/post/tonemap/wrapValue", 0, 100000, tooltip="\nOffset") self._add_setting(SettingType.FLOAT, "Dither strength", "/rtx/post/tonemap/dither", 0, .02, .001, tooltip="\nRemoves banding artifacts in final images.") def destroy(self): self._change_cb = None super().destroy() class AutoExposureSettingsFrame(SettingsCollectionFrame): """ Auto Exposure """ def _frame_setting_path(self): return "/rtx/post/histogram/enabled" def _build_ui(self): histFilter_types = ["Median", "Average"] self._add_setting_combo("Histogram Filter", "/rtx/post/histogram/filterType", histFilter_types, tooltip="\nSelect a method to filter the histogram. Options are Median and Average.") self._add_setting(SettingType.FLOAT, "Adaptation Speed", "/rtx/post/histogram/tau", 0.5, 10.0, 0.01, tooltip="\nHow fast automatic exposure compensation adapts to changes in overall light intensity.") self._add_setting(SettingType.FLOAT, "White Point Scale", "/rtx/post/histogram/whiteScale", 0.01, 80.0, 0.001, tooltip="\nControls how bright of an image the auto-exposure should aim for." "\nLower values result in brighter images, higher values result in darker images.") self._add_setting(SettingType.BOOL, "Exposure Value Clamping", "/rtx/post/histogram/useExposureClamping", tooltip="\nClamps the exposure to a range within a specified minimum and maximum Exposure Value.") self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/histogram/useExposureClamping", self._on_change) if self._settings.get("/rtx/post/histogram/useExposureClamping"): self._add_setting(SettingType.FLOAT, " Minimum Value", "/rtx/post/histogram/minEV", 0.0, 1000000.0, 1, tooltip="\nClamps the exposure to a range within a specified minimum and maximum Exposure Value.") self._add_setting(SettingType.FLOAT, " Maximum Value", "/rtx/post/histogram/maxEV", 0.0, 1000000.0, 1, tooltip="\nClamps the exposure to a range within a specified minimum and maximum Exposure Value.") # self._add_setting(SettingType.FLOAT, "Min Log Luminance", "/rtx/post/histogram/minloglum", -15, 5.0, 0.001) # self._add_setting(SettingType.FLOAT, "Log Luminance Range", "/rtx/post/histogram/loglumrange", 0.00001, 50.0, 0.001) def destroy(self): self._change_cb = None super().destroy() class ColorCorrectionSettingsFrame(SettingsCollectionFrame): """ Color Correction """ def _frame_setting_path(self): return "/rtx/post/colorcorr/enabled" def _on_colorcorrect_change(self, *_): self._rebuild() def _build_ui(self): mode = ["ACES (Pre-Tonemap)", "Standard (Post-Tonemap)"] self._add_setting_combo("Mode", "/rtx/post/colorcorr/mode", mode, tooltip="\nChoose between ACES (Pre-Tone mapping) or Standard (Post-Tone mapping) mode.") self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/colorcorr/mode", self._on_change) colorCorrectionMode = ["sRGBLinear", "ACEScg"] if self._settings.get("/rtx/post/colorcorr/mode") == 0: self._add_setting_combo(" Output Color Space", "/rtx/post/colorcorr/outputMode", colorCorrectionMode, tooltip="\nDefines the color space used as output of Color Correction." "\nsRGB Linear: scene linear space" "\nAcesCG: ACES CG color space") self._add_setting(SettingType.COLOR3, "Saturation", "/rtx/post/colorcorr/saturation", tooltip="\nHigher values increase color saturation while lowering desaturates.") self._add_setting(SettingType.COLOR3, "Contrast", "/rtx/post/colorcorr/contrast", 0, 10, 0.005, tooltip="\nHigher values increase the contrast of darks/lights and colors.") self._add_setting(SettingType.COLOR3, "Gamma", "/rtx/post/colorcorr/gamma", 0.2, 10, 0.005, tooltip="\nGamma value in inverse gamma curve applied before output.") self._add_setting(SettingType.COLOR3, "Gain", "/rtx/post/colorcorr/gain", 0, 10, 0.005, tooltip="\nA factor applied to the color values.") self._add_setting(SettingType.COLOR3, "Offset", "/rtx/post/colorcorr/offset", -1, 1, 0.001, tooltip="\nAn offset applied to the color values.") def destroy(self): self._change_cb = None super().destroy() class ColorGradingSettingsFrame(SettingsCollectionFrame): """ Color Grading """ def _frame_setting_path(self): return "/rtx/post/colorgrad/enabled" def _on_colorgrade_change(self, *_): self._rebuild() def _build_ui(self): mode = ["ACES (Pre-Tonemap)", "Standard (Post-Tonemap)"] self._add_setting_combo("Mode", "/rtx/post/colorgrad/mode", mode, tooltip="\nChoose between ACES (Pre-Tonemap) or Standard (Post-Tonemap) Mode.") self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/colorgrad/mode", self._on_change) colorGradingMode = ["sRGBLinear", "ACEScg"] if self._settings.get("/rtx/post/colorgrad/mode") == 0: self._add_setting_combo(" Output Color Space", "/rtx/post/colorgrad/outputMode", colorGradingMode, tooltip="\nChoose between ACES (Pre-Tonemap) or Standard (Post-Tonemap) Mode." "\nsRGB Linear: scene linear space" "\nAcesCG: ACES CG color space") self._add_setting(SettingType.COLOR3, "Black Point", "/rtx/post/colorgrad/blackpoint", -1, 1, 0.005, tooltip="\nDefines the Black Point value.") self._add_setting(SettingType.COLOR3, "White Point", "/rtx/post/colorgrad/whitepoint", 0, 10, 0.005, tooltip="\nDefines the White Point value.") self._add_setting(SettingType.COLOR3, "Contrast", "/rtx/post/colorgrad/contrast", 0, 10, 0.005, tooltip="\nHigher values increase the contrast of darks/lights and colors.") self._add_setting(SettingType.COLOR3, "Lift", "/rtx/post/colorgrad/lift", -10, 10, 0.005, tooltip="\nColor is multiplied by (Lift - Gain) and later Lift is added back.") self._add_setting(SettingType.COLOR3, "Gain", "/rtx/post/colorgrad/gain", 0, 10, 0.005, tooltip="\nColor is multiplied by (Lift - Gain) and later Lift is added back.") self._add_setting(SettingType.COLOR3, "Multiply", "/rtx/post/colorgrad/multiply", 0, 10, 0.005, tooltip="\nA factor applied to the color values.") self._add_setting(SettingType.COLOR3, "Offset", "/rtx/post/colorgrad/offset", -1, 1, 0.001, tooltip="\nColor offset: an offset applied to the color values.") self._add_setting(SettingType.COLOR3, "Gamma", "/rtx/post/colorgrad/gamma", 0.2, 10, 0.005, tooltip="\nGamma value in inverse gamma curve applied before output.") def destroy(self): self._change_cb = None super().destroy() class MatteObjectSettingsFrame(SettingsCollectionFrame): def _frame_setting_path(self): return "/rtx/matteObject/enabled" def _build_ui(self): self._add_setting(SettingType.COLOR3, "Backplate Color", "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor", tooltip="\nA constant color used if no backplate texture is set.") self._add_setting("ASSET", "Backplate Texture", "/rtx/post/backgroundZeroAlpha/backplateTexture", tooltip="\nThe path to a texture to use as a backplate.") self._add_setting(SettingType.BOOL, "Shadow Catcher", "/rtx/post/matteObject/enableShadowCatcher", tooltip="\Treats all matte objects as shadow catchers. Matte objects receives only shadow and" "\nnot reflections or GI which improves rendering performance." ) class XRCompositingSettingsFrame(SettingsCollectionFrame): def _frame_setting_path(self): return "/rtx/post/backgroundZeroAlpha/enabled" def _build_ui(self): self._add_setting(SettingType.BOOL, "Composite in Editor", "/rtx/post/backgroundZeroAlpha/backgroundComposite", tooltip="\nEnables alpha compositing with a backplate texture, instead of" "\noutputting the rendered image with an alpha channel for compositing externally," "\nby saving to EXR images.") self._add_setting(SettingType.BOOL, "Output Alpha in Composited Image", "/rtx/post/backgroundZeroAlpha/outputAlphaInComposite", tooltip="\nOutputs the matte compositing alpha in the composited image." "\nOnly activates when not compositing in editor." "\nThis option can interfere with DLSS, producing jaggied edges.") self._add_setting(SettingType.BOOL, "Output Black Background in Composited Image", "/rtx/post/backgroundZeroAlpha/blackBackgroundInComposite", tooltip="\nOutputs a black background in the composited image, for XR compositing." "\nOnly activates when not compositing in editor.") self._add_setting(SettingType.BOOL, "Multiply color value by alpha in Composited Image", "/rtx/post/backgroundZeroAlpha/premultiplyColorByAlpha", tooltip="\nWhen enabled, the RGB color will be RGB * alpha.") self._add_setting(SettingType.COLOR3, "Backplate Color", "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor", tooltip="\nA constant color used if no backplate texture is set.") self._add_setting("ASSET", "Backplate Texture", "/rtx/post/backgroundZeroAlpha/backplateTexture", tooltip="\nThe path to a texture to use as a backplate.") self._add_setting(SettingType.BOOL, " Is linear", "/rtx/post/backgroundZeroAlpha/backplateTextureIsLinear", tooltip="\nSets the color space for the Backplate Texture to linear space.") self._add_setting(SettingType.FLOAT, "Backplate Luminance Scale", "/rtx/post/backgroundZeroAlpha/backplateLuminanceScaleV2", tooltip="\nScales the Backplate Texture/Color luminance.") self._add_setting(SettingType.BOOL, "Lens Distortion", "/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection", tooltip="\nEnables distortion of the rendered image using a set of lens distortion and undistortion maps." "\nEach of these should refer to a <UDIM> EXR texture set, containing one image for each" "\nof the discrete focal length values specified in the array of float settings under" "\n/rtx/post/lensDistortion/lensFocalLengthArray (not currently exposed).") self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection", self._on_change) if self._settings.get("/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection"): self._add_setting("ASSET", " Distortion Map", "/rtx/post/lensDistortion/distortionMap", tooltip="\n<UDIM> EXR texture path to store the distortion maps for specified focal lengths.") self._add_setting("ASSET", " Undistortion Map", "/rtx/post/lensDistortion/undistortionMap", tooltip="\n<UDIM> EXR texture path to store the un-distortion maps for specified focal lengths.") def destroy(self): self._change_cb = None super().destroy() class ChromaticAberrationSettingsFrame(SettingsCollectionFrame): """ Chromatic Aberration """ def _frame_setting_path(self): return "/rtx/post/chromaticAberration/enabled" def _build_ui(self): self._add_setting(SettingType.FLOAT, "Strength Red", "/rtx/post/chromaticAberration/strengthR", -1.0, 1.0, 0.01, tooltip="\nThe strength of the distortion applied on the Red channel.") self._add_setting(SettingType.FLOAT, "Strength Green", "/rtx/post/chromaticAberration/strengthG", -1.0, 1.0, 0.01, tooltip="\nThe strength of the distortion applied on the Green channel.") self._add_setting(SettingType.FLOAT, "Strength Blue", "/rtx/post/chromaticAberration/strengthB", -1.0, 1.0, 0.01, tooltip="\nThe strength of the distortion applied on the Blue channel.") chromatic_aberration_ops = ["Radial", "Barrel"] self._add_setting_combo("Algorithm Red", "/rtx/post/chromaticAberration/modeR", chromatic_aberration_ops, tooltip="\nSelects between Radial and Barrel distortion for the Red channel.") self._add_setting_combo("Algorithm Green", "/rtx/post/chromaticAberration/modeG", chromatic_aberration_ops, tooltip="\nSelects between Radial and Barrel distortion for the Green channel.") self._add_setting_combo("Algorithm Blue", "/rtx/post/chromaticAberration/modeB", chromatic_aberration_ops, tooltip="\nSelects between Radial and Barrel distortion for the Blue channel.") self._add_setting(SettingType.BOOL, "Use Lanczos Sampler", "/rtx/post/chromaticAberration/enableLanczos", tooltip="\nUse a Lanczos sampler when sampling the input image being distorted.") with ui.CollapsableFrame("Boundary Blending", height=0): with ui.VStack(height=0, spacing=5): self._add_setting(SettingType.BOOL, "Repeat Mirrored", "/rtx/post/chromaticAberration/mirroredRepeat", tooltip="\nEnables mirror repeat for texture lookups in out-of-lens regions. When disabled, out-of-lens regions are black.") self._add_setting(SettingType.FLOAT, "Blend Region Size", "/rtx/post/chromaticAberration/boundaryBlendRegionSize", 0.0, 1.0, 0.01, tooltip="\nDetermines the blend region size.") self._add_setting(SettingType.FLOAT, "Blend Region Falloff", "/rtx/post/chromaticAberration/boundaryBlendFalloff", 0.001, 5.0, 0.001, tooltip="\nDetermines the falloff in the blending region.") class DepthOfFieldSettingsFrame(SettingsCollectionFrame): """ Depth of Field Camera Overrides """ def _frame_setting_path(self): return "/rtx/post/dof/overrideEnabled" def _build_ui(self): self._add_setting(SettingType.BOOL, "Enable DOF", "/rtx/post/dof/enabled", tooltip="\nEnables Depth of Field. If disabled, camera parameters affecting Depth of Field are ignored.") self._add_setting(SettingType.FLOAT, "Subject Distance", "/rtx/post/dof/subjectDistance", -10000, 10000.0, tooltip="\nObjects at this distance from the camera will be in focus.") self._add_setting(SettingType.FLOAT, "Focal Length (mm)", "/rtx/post/dof/focalLength", 0, 1000, tooltip="\nThe focal length of the lens (in mm). The focal length divided by the f-stop is the aperture diameter.") self._add_setting(SettingType.FLOAT, "F-stop", "/rtx/post/dof/fNumber", 0, 1000, tooltip="\nF-stop (aperture) of the lens. Lower f-stop numbers decrease the distance range from the Subject Distance where objects remain in focus.") self._add_setting(SettingType.FLOAT, "Anisotropy", "/rtx/post/dof/anisotropy", -1, 1, 0.01, tooltip="\nAnisotropy of the lens. A value of -0.5 simulates the depth of field of an anamorphic lens.") class MotionBlurSettingsFrame(SettingsCollectionFrame): """ Motion Blur """ def _frame_setting_path(self): return "/rtx/post/motionblur/enabled" def _build_ui(self): self._add_setting(SettingType.FLOAT, "Blur Diameter Fraction", "/rtx/post/motionblur/maxBlurDiameterFraction", 0, 0.5, 0.01, tooltip="\nThe fraction of the largest screen dimension to use as the maximum motion blur diameter.") self._add_setting(SettingType.FLOAT, "Exposure Fraction", "/rtx/post/motionblur/exposureFraction", 0, 5.0, 0.01, tooltip="\nExposure time fraction in frames (1.0 = one frame duration) to sample.") self._add_setting(SettingType.INT, "Number of Samples", "/rtx/post/motionblur/numSamples", 4, 32, 1, tooltip="\nNumber of samples to use in the filter. A higher number improves quality at the cost of performance.") class FFTBloomSettingsFrame(SettingsCollectionFrame): """ FFT Bloom """ def _frame_setting_path(self): return "/rtx/post/lensFlares/enabled" def _build_ui(self): self._add_setting(SettingType.FLOAT, "Scale", "/rtx/post/lensFlares/flareScale", -1000, 1000, tooltip="\nOverall intensity of the bloom effect.") self._add_setting(SettingType.DOUBLE3, "Cutoff Point", "/rtx/post/lensFlares/cutoffPoint", tooltip="\nA cutoff color value to tune the radiance range for which Bloom will have any effect. ") self._add_setting(SettingType.FLOAT, "Cutoff Fuzziness", "/rtx/post/lensFlares/cutoffFuzziness", 0.0, 1.0, tooltip="\nIf greater than 0, defines the width of a 'fuzzy cutoff' region around the Cutoff Point values." "\nInstead of a sharp cutoff, a smooth transition between 0 and the original values is used.") self._add_setting(SettingType.FLOAT, "Alpha channel scale", "/rtx/post/lensFlares/alphaExposureScale", 0.0, 100.0, tooltip="\nAlpha channel intensity of the bloom effect.") self._add_setting(SettingType.BOOL, "Energy Constrained", "/rtx/post/lensFlares/energyConstrainingBlend", tooltip="\nConstrains the total light energy generated by bloom.") self._add_setting(SettingType.BOOL, "Physical Model", "/rtx/post/lensFlares/physicalSettings", tooltip="\nChoose between a Physical or Non-Physical bloom model.") self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/lensFlares/physicalSettings", self._on_change) if self._settings.get("/rtx/post/lensFlares/physicalSettings") == 1: self._add_setting(SettingType.INT, " Blades", "/rtx/post/lensFlares/blades", 0, 10, tooltip="\nThe number of physical blades of a simulated camera diaphragm causing the bloom effect.") self._add_setting(SettingType.FLOAT, " Aperture Rotation", "/rtx/post/lensFlares/apertureRotation", -1000, 1000, tooltip="\nRotation of the camera diaphragm.") self._add_setting(SettingType.FLOAT, " Sensor Diagonal", "/rtx/post/lensFlares/sensorDiagonal", -1000, 1000, tooltip="\nDiagonal of the simulated sensor.") self._add_setting(SettingType.FLOAT, " Sensor Aspect Ratio", "/rtx/post/lensFlares/sensorAspectRatio", -1000, 1000, tooltip="\nAspect ratio of the simulated sensor, results in the bloom effect stretching in one direction.") self._add_setting(SettingType.FLOAT, " F-stop", "/rtx/post/lensFlares/fNumber", -1000, 1000, tooltip="\nIncreases/Decreases the sharpness of the bloom effect.") self._add_setting(SettingType.FLOAT, " Focal Length (mm)", "/rtx/post/lensFlares/focalLength", -1000, 1000, tooltip="\nFocal length of the lens modeled to simulate the bloom effect.") else: self._add_setting(SettingType.DOUBLE3, " Halo Radius", "/rtx/post/lensFlares/haloFlareRadius", tooltip="\nControls the size of each RGB component of the halo flare effect.") self._add_setting(SettingType.DOUBLE3, " Halo Flare Falloff", "/rtx/post/lensFlares/haloFlareFalloff", tooltip="\nControls the falloff of each RGB component of the halo flare effect.") self._add_setting(SettingType.FLOAT, " Halo Flare Weight", "/rtx/post/lensFlares/haloFlareWeight", -1000, 1000, tooltip="\nControls the intensity of the halo flare effect.") self._add_setting(SettingType.DOUBLE3, " Aniso Falloff Y", "/rtx/post/lensFlares/anisoFlareFalloffY", tooltip="\nControls the falloff of each RGB component of the anistropic flare effect in the X direction.") self._add_setting(SettingType.DOUBLE3, " Aniso Falloff X", "/rtx/post/lensFlares/anisoFlareFalloffX", tooltip="\nControls the falloff of each RGB component of the anistropic flare effect in the Y direction.") self._add_setting(SettingType.FLOAT, " Aniso Flare Weight", "/rtx/post/lensFlares/anisoFlareWeight", -1000, 1000, tooltip="\nControl the intensity of the anisotropic flare effect.") self._add_setting(SettingType.DOUBLE3, " Isotropic Flare Falloff", "/rtx/post/lensFlares/isotropicFlareFalloff", tooltip="\nControls the falloff of each RGB component of the isotropic flare effect.") self._add_setting(SettingType.FLOAT, " Isotropic Flare Weight", "/rtx/post/lensFlares/isotropicFlareWeight", -1000, 1000, tooltip="\nControl the intensity of the isotropic flare effect.") def destroy(self): self._change_cb = None super().destroy() class TVNoiseGrainSettingsFrame(SettingsCollectionFrame): """ TV Noise | Film Grain """ def _frame_setting_path(self): return "/rtx/post/tvNoise/enabled" def _build_ui(self): self._add_setting(SettingType.BOOL, "Enable Scanlines", "/rtx/post/tvNoise/enableScanlines", tooltip="\nEmulates a Scanline Distortion typical of old televisions.") self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/post/tvNoise/enableScanlines", self._on_change) if self._settings.get("/rtx/post/tvNoise/enableScanlines"): self._add_setting(SettingType.FLOAT, " Scanline Spreading", "/rtx/post/tvNoise/scanlineSpread", 0.0, 2.0, 0.01, tooltip="\nHow wide the Scanline distortion will be.") self._add_setting(SettingType.BOOL, "Enable Scroll Bug", "/rtx/post/tvNoise/enableScrollBug", tooltip="\nEmulates sliding typical on old televisions.") self._add_setting(SettingType.BOOL, "Enable Vignetting", "/rtx/post/tvNoise/enableVignetting", tooltip="\nBlurred darkening around the screen edges.") self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/post/tvNoise/enableVignetting", self._on_change) if self._settings.get("/rtx/post/tvNoise/enableVignetting"): self._add_setting(SettingType.FLOAT, " Vignetting Size", "/rtx/post/tvNoise/vignettingSize", 0.0, 255, tooltip="\nControls the size of vignette region.") self._add_setting(SettingType.FLOAT, " Vignetting Strength", "/rtx/post/tvNoise/vignettingStrength", 0.0, 2.0, 0.01, tooltip="\nControls the intensity of the vignette.") self._add_setting(SettingType.BOOL, " Enable Vignetting Flickering", "/rtx/post/tvNoise/enableVignettingFlickering", tooltip="\nEnables a slight flicker effect on the vignette.") self._add_setting(SettingType.BOOL, "Enable Ghost Flickering", "/rtx/post/tvNoise/enableGhostFlickering", tooltip="\nIntroduces a blurred flicker to help emulate an old television.") self._add_setting(SettingType.BOOL, "Enable Wavy Distortion", "/rtx/post/tvNoise/enableWaveDistortion", tooltip="\nIntroduces a Random Wave Flicker to emulate an old television.") self._add_setting(SettingType.BOOL, "Enable Vertical Lines", "/rtx/post/tvNoise/enableVerticalLines", tooltip="\nIntroduces random vertical lines to emulate an old television.") self._add_setting(SettingType.BOOL, "Enable Random Splotches", "/rtx/post/tvNoise/enableRandomSplotches", tooltip="\nIntroduces random splotches typical of old dirty television.") self._add_setting(SettingType.BOOL, "Enable Film Grain", "/rtx/post/tvNoise/enableFilmGrain", tooltip="\nEnables a film grain effect to emulate the graininess in high speed (ISO) film.") # Filmgrain is a subframe in TV Noise self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx/post/tvNoise/enableFilmGrain", self._on_change) if self._settings.get("/rtx/post/tvNoise/enableFilmGrain"): self._add_setting(SettingType.FLOAT, " Grain Amount", "/rtx/post/tvNoise/grainAmount", 0, 0.2, 0.002, tooltip="\nThe intensity of the film grain effect.") self._add_setting(SettingType.FLOAT, " Color Amount", "/rtx/post/tvNoise/colorAmount", 0, 1.0, 0.02, tooltip="\nThe amount of color offset each grain will be allowed to use.") self._add_setting(SettingType.FLOAT, " Luminance Amount", "/rtx/post/tvNoise/lumAmount", 0, 1.0, 0.02, tooltip="\nThe amount of offset in luminance each grain will be allowed to use.") self._add_setting(SettingType.FLOAT, " Grain Size", "/rtx/post/tvNoise/grainSize", 1.5, 2.5, 0.02, tooltip="\nThe size of the film grains.") def destroy(self): self._change_cb1 = None self._change_cb2 = None self._change_cb3 = None super().destroy() class ReshadeSettingsFrame(SettingsCollectionFrame): """ ReShade """ def _frame_setting_path(self): return "/rtx/reshade/enable" def _build_ui(self): self._add_setting("ASSET", "Preset File Path", "/rtx/reshade/presetFilePath", tooltip="\nThe path to a preset.init file containing the Reshade preset to use.") widget = self._add_setting("ASSET", "Effect search dir path", "/rtx/reshade/effectSearchDirPath", tooltip="\nThe path to a directory containing the Reshade files that the preset can reference.") widget.is_folder=True widget = self._add_setting("ASSET", "Texture search dir path", "/rtx/reshade/textureSearchDirPath", tooltip="\nThe path to a directory containing the Reshade texture files that the preset can reference.") widget.is_folder=True class PostSettingStack(RTXSettingsStack): def __init__(self) -> None: self._stack = ui.VStack(spacing=7, identifier=__class__.__name__) with self._stack: ToneMappingSettingsFrame("Tone Mapping", parent=self) AutoExposureSettingsFrame("Auto Exposure", parent=self) ColorCorrectionSettingsFrame("Color Correction", parent=self) ColorGradingSettingsFrame("Color Grading", parent=self) XRCompositingSettingsFrame("XR Compositing", parent=self) MatteObjectSettingsFrame("Matte Object", parent=self) ChromaticAberrationSettingsFrame("Chromatic Aberration", parent=self) DepthOfFieldSettingsFrame("Depth of Field Camera Overrides", parent=self) MotionBlurSettingsFrame("Motion Blur", parent=self) FFTBloomSettingsFrame("FFT Bloom", parent=self) TVNoiseGrainSettingsFrame("TV Noise & Film Grain", parent=self) ReshadeSettingsFrame("ReShade", parent=self) ui.Spacer()
30,479
Python
84.617977
243
0.696578
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/pt_widgets.py
import omni.ui as ui import omni.kit.app import carb.settings import math from omni.kit.widget.settings import SettingType from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame class AntiAliasingSettingsFrame(SettingsCollectionFrame): """ Anti-Aliasing """ def _build_ui(self): pt_aa_ops = ["Box", "Triangle", "Gaussian", "Uniform"] self._add_setting_combo("Anti-Aliasing Sample Pattern", "/rtx/pathtracing/aa/op", pt_aa_ops, tooltip="\nSampling pattern used for Anti-Aliasing. Select between Box, Triangle, Gaussian and Uniform.") self._add_setting(SettingType.FLOAT, "Anti-Aliasing Radius", "/rtx/pathtracing/aa/filterRadius", 0.0001, 5.0, 0.001, tooltip="\nSampling footprint radius, in pixels, when generating samples with the selected antialiasing sample pattern.") class FireflyFilterSettingsFrame(SettingsCollectionFrame): """ Firefly Filtering """ def _frame_setting_path(self): return "/rtx/pathtracing/fireflyFilter/enabled" def _build_ui(self): self._add_setting(SettingType.FLOAT, "Max Ray Intensity Glossy", "/rtx/pathtracing/fireflyFilter/maxIntensityPerSample", 0, 100000, 100, tooltip="\nClamps the maximium ray intensity for glossy bounces. Can help prevent fireflies, but may result in energy loss.") self._add_setting(SettingType.FLOAT, "Max Ray Intensity Diffuse", "/rtx/pathtracing/fireflyFilter/maxIntensityPerSampleDiffuse", 0, 100000, 100, tooltip="\nClamps the maximium ray intensity for diffuse bounces. Can help prevent fireflies, but may result in energy loss.") class PathTracingSettingsFrame(SettingsCollectionFrame): """ Path-Tracing """ def _build_ui(self): clampSpp = self._settings.get("/rtx/pathtracing/clampSpp") if clampSpp is not None and clampSpp > 1: # better 0, but setting range = (1,1) completely disables the UI control range self._add_setting(SettingType.INT, "Samples per Pixel per Frame(1 to {})".format(clampSpp), "/rtx/pathtracing/spp", 1, clampSpp, tooltip="\nTotal number of samples for each rendered pixel, per frame.") else: self._add_setting(SettingType.INT, "Samples per Pixel per Frame", "/rtx/pathtracing/spp", 1, 1048576, tooltip="\nTotal number of samples for each rendered pixel, per frame.") self._add_setting(SettingType.INT, "Total Samples per Pixel (0 = inf)", "/rtx/pathtracing/totalSpp", 0, 100000, tooltip="\nMaximum number of samples to accumulate per pixel. When this count is reached the rendering stops until" "\na scene or setting change is detected, restarting the rendering process. Set to 0 to remove this limit.") self._add_setting(SettingType.BOOL, "Adaptive Sampling", "/rtx/pathtracing/adaptiveSampling/enabled", tooltip="\nWhen enabled, noise values are computed for each pixel, and upon threshold level eached, the pixel is no longer sampled") self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/adaptiveSampling/enabled", self._on_change) if self._settings.get("/rtx/pathtracing/adaptiveSampling/enabled"): self._add_setting(SettingType.FLOAT, " Target Error", "/rtx/pathtracing/adaptiveSampling/targetError", 0.00001, 1, tooltip="\nThe noise value treshold after which the pixel would no longer be sampled.") ui.Line() self._add_setting(SettingType.INT, "Max Bounces", "/rtx/pathtracing/maxBounces", 0, 64, tooltip="\nMaximum number of ray bounces for any ray type. Higher values give more accurate results, but worse performance.") self._add_setting(SettingType.INT, "Max Specular and Transmission Bounces", "/rtx/pathtracing/maxSpecularAndTransmissionBounces", 1, 128, tooltip="\nMaximum number of ray bounces for specular and trasnimission.") self._add_setting(SettingType.INT, "Max SSS Volume Scattering Bounces", "/rtx/pathtracing/maxVolumeBounces", 0, 1024, tooltip="\nMaximum number of ray bounces for SSS.") self._add_setting(SettingType.INT, "Max Fog Scattering Bounces", "/rtx/pathtracing/ptfog/maxBounces", 1, 10, tooltip="\nMaximum number of bounces for volume scattering within a fog/sky volume.") # self._add_setting(SettingType.BOOL, "Dome Lights: High Quality Primary Rays", "/rtx/pathtracing/domeLight/primaryRaysEvaluateDomelightMdlDirectly") ui.Line() # self._add_setting(SettingType.BOOL, "Show Lights", "/rtx/pathtracing/showLights/enabled") # depreacted, use /rtx/raytracing/showLights instead self._add_setting(SettingType.BOOL, "Fractional Cutout Opacity", "/rtx/pathtracing/fractionalCutoutOpacity", tooltip="\nIf enabled, fractional cutout opacity values are treated as a measure of surface 'presence'," "\nresulting in a translucency effect similar to alpha-blending. Path-traced mode uses stochastic" "\nsampling based on these values to determine whether a surface hit is valid or should be skipped.") self._add_setting(SettingType.BOOL, "Reset Accumulation on Time Change", "/rtx/resetPtAccumOnAnimTimeChange", tooltip="\nIf enabled, rendering is restarted every time the MDL animation time changes.") def destroy(self): self._change_cb = None super().destroy() class SamplingAndCachingSettingsFrame(SettingsCollectionFrame): """ Sampling & Caching """ def _build_ui(self): self._add_setting(SettingType.BOOL, "Caching", "/rtx/pathtracing/cached/enabled", tooltip="\nEnables caching path-tracing results for improved performance at the cost of some accuracy.") self._add_setting(SettingType.BOOL, "Many-Light Sampling", "/rtx/pathtracing/lightcache/cached/enabled", tooltip="\nEnables many-light sampling algorithm, resulting in faster rendering of scenes with many lights." "\nThis should generally be always enabled, and is exposed as an option for debugging potential algorithm artifacts.") self._add_setting(SettingType.BOOL, "Mesh-Light Sampling", "/rtx/pathtracing/ris/meshLights", tooltip="\nEnables direct illumination sampling of geometry with emissive materials.") # ui.Label("Neural Radiance Caching does not work on Multi-GPU and requires (spp=1)", alignment=ui.Alignment.CENTER) # self._add_setting(SettingType.BOOL, "Enable Neural Radiance Cache (Experimental)", "/rtx/pathtracing/nrc/enabled") class DenoisingSettingsFrame(SettingsCollectionFrame): """ Denoising """ def _frame_setting_path(self): return "/rtx/pathtracing/optixDenoiser/enabled" def _build_ui(self): self._add_setting(SettingType.FLOAT, "OptiX Denoiser Blend Factor", "/rtx/pathtracing/optixDenoiser/blendFactor", 0, 1, 0.001, tooltip="\nA blend factor indicating how much to blend the denoised image with the original non-denoised image." "\n0 shows only the denoised image, 1.0 shows the image with no denoising applied.") self._add_setting(SettingType.BOOL, "Denoise AOVs", "/rtx/pathtracing/optixDenoiser/AOV", tooltip="\nIf enabled, the OptiX Denoiser will also denoise the AOVs.") class NonUniformVolumesSettingsFrame(SettingsCollectionFrame): """ Path-Traced Volume """ def _frame_setting_path(self): return "/rtx/pathtracing/ptvol/enabled" def _build_ui(self): """ Path-Traced Volume """ pt_vol_tr_ops = ["Biased Ray Marching", "Ratio Tracking"] self._add_setting_combo("Transmittance Method", "/rtx/pathtracing/ptvol/transmittanceMethod", pt_vol_tr_ops, tooltip="\nChoose between Biased Ray Marching or Ratio Tracking. Biased ray marching is the ideal option in all cases.") self._add_setting(SettingType.INT, "Max Ray Steps (Scattering)", "/rtx/pathtracing/ptvol/maxCollisionCount", 0, 1024, 32, tooltip="\nMaximum delta tracking steps between bounces. Increase to more than 32 for highly scattering volumes like clouds.") self._add_setting(SettingType.INT, "Max Ray Steps (Shadow)", "/rtx/pathtracing/ptvol/maxLightCollisionCount", 0, 1024, 16, tooltip="\nMaximum ratio tracking delta steps for shadow rays. Increase to more than 32 for highly scattering volumes like clouds.") self._add_setting(SettingType.INT, "Max Non-uniform Volume Scattering Bounces", "/rtx/pathtracing/ptvol/maxBounces", 1, 1024, 1, tooltip="\nMaximum number of bounces in non-uniform volumes.") class AOVSettingsFrame(SettingsCollectionFrame): """ AOV Settings""" def _build_ui(self): """ AOV Settings """ self._add_setting(SettingType.FLOAT, "Minimum Z-Depth", "/rtx/pathtracing/zDepthMin", 0, 10000, 1) self._add_setting(SettingType.FLOAT, "Maximum Z-Depth", "/rtx/pathtracing/zDepthMax", 0, 10000, 1) self._add_setting(SettingType.BOOL, "32 Bit Depth AOV", "/rtx/pathtracing/depth32BitAov", tooltip="\nUses a 32-bit format for the depth AOV") ui.Label("Enables AOV Preview in Debug View", alignment=ui.Alignment.CENTER) self._add_setting(SettingType.BOOL, "Background", "/rtx/pathtracing/backgroundAOV", tooltip="\nShading of the background, such as the background resulting from rendering a Dome Light.") self._add_setting(SettingType.BOOL, "Diffuse Filter", "/rtx/pathtracing/diffuseFilterAOV", tooltip="\nThe raw color of the diffuse texture.") self._add_setting(SettingType.BOOL, "Direct Illumation", "/rtx/pathtracing/diAOV", tooltip="\nShading from direct paths to light sources.") self._add_setting(SettingType.BOOL, "Global Illumination", "/rtx/pathtracing/giAOV", tooltip="\nDiffuse shading from indirect paths to light sources.") self._add_setting(SettingType.BOOL, "Reflection", "/rtx/pathtracing/reflectionsAOV", tooltip="\nShading from indirect reflection paths to light sources.") self._add_setting(SettingType.BOOL, "Reflection Filter", "/rtx/pathtracing/reflectionFilterAOV", tooltip="\nThe raw color of the reflection, before being multiplied for its final intensity.") self._add_setting(SettingType.BOOL, "Refraction", "/rtx/pathtracing/refractionsAOV", tooltip="\nShading from refraction paths to light sources.") self._add_setting(SettingType.BOOL, "Refraction Filter", "/rtx/pathtracing/refractionFilterAOV", tooltip="\nThe raw color of the refraction, before being multiplied for its final intensity.") self._add_setting(SettingType.BOOL, "Self-Illumination", "/rtx/pathtracing/selfIllumAOV", tooltip="\nShading of the surface's own emission value.") self._add_setting(SettingType.BOOL, "Volumes", "/rtx/pathtracing/volumesAOV", tooltip="\nShading from VDB volumes.") self._add_setting(SettingType.BOOL, "World Normal", "/rtx/pathtracing/worldNormalsAOV", tooltip="\nThe surface's normal in world-space.") self._add_setting(SettingType.BOOL, "World Position", "/rtx/pathtracing/worldPosAOV", tooltip="\nThe surface's position in world-space.") self._add_setting(SettingType.BOOL, "Z-Depth", "/rtx/pathtracing/zDepthAOV", tooltip="\nThe surface's depth relative to the view position.") class MultiMatteSettingsFrame(SettingsCollectionFrame): def _on_multimatte_change(self, *_): self._rebuild() def _build_ui(self): self._add_setting(SettingType.INT, "Channel Count:", "/rtx/pathtracing/multimatte/channelCount", 0, 24, 1, tooltip="\nMultimatte allows rendering AOVs of meshes which have a Multimatte ID index matching a Multimatte AOV's channel index." "\nChannel Count determines how many channels can be used, which are distributed among the Multimatte AOVs' color channels." "\nYou can preview a Multimatte AOV by selecting one in the Debug View.") self._change_channels = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/multimatte/channelCount", self._on_multimatte_change) def clamp(num, min_value, max_value): return max(min(num, max_value), min_value) value = self._settings.get("/rtx/pathtracing/multimatte/channelCount") channelCount = clamp(self._settings.get("/rtx/pathtracing/multimatte/channelCount"), 0, 24) if value is not None else 0 if channelCount != 0: mapCount = math.ceil(channelCount / 3) channelIndex = 0 for i in range(0, mapCount): ui.Label("Multimatte" + str(i), alignment=ui.Alignment.CENTER) self._add_setting(SettingType.INT, "Red Channel Multimatte ID Index", "/rtx/pathtracing/multimatte/channel" + str(channelIndex), -1, 1000000, 1, tooltip="\nThe Multimatte ID index to match for the red channel of this Multimatte AOV.") channelIndex += 1 if channelIndex >= channelCount: break self._add_setting(SettingType.INT, "Green Channel Multimatte ID Index", "/rtx/pathtracing/multimatte/channel" + str(channelIndex), -1, 1000000, 1, tooltip="\nThe Multimatte ID index to match for the green channel of this Multimatte AOV.") channelIndex += 1 if channelIndex >= channelCount: break self._add_setting(SettingType.INT, "Blue Channel Multimatte ID Index", "/rtx/pathtracing/multimatte/channel" + str(channelIndex), -1, 1000000, 1, tooltip="\nThe Multimatte ID index to match for the blue channel of this Multimatte AOV.") channelIndex += 1 if channelIndex >= channelCount: break # self._add_setting(SettingType.BOOL, "is material ID " + str(i), "/rtx/pathtracing/multimatte/channel" + str(i) + "_isMat") def destroy(self): self._change_channels = None super().destroy() class MultiGPUSettingsFrame(SettingsCollectionFrame): """ Multi-GPU """ def _frame_setting_path(self): return "/rtx/pathtracing/mgpu/enabled" def _build_ui(self): self._add_setting(SettingType.BOOL, "Auto Load Balancing","/rtx/pathtracing/mgpu/autoLoadBalancing/enabled", tooltip="\nAutomatically balance the amount of total path-tracing work to be performed by each GPU in a multi-GPU configuration.") self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/mgpu/autoLoadBalancing/enabled", self._on_change) if not self._settings.get("/rtx/pathtracing/mgpu/autoLoadBalancing/enabled") : self._add_setting(SettingType.FLOAT, "GPU 0 Weight", "/rtx/pathtracing/mgpu/weightGpu0", 0, 1, 0.001, tooltip="\nThe amount of total Path-Tracing work (between 0 and 1) to be performed by the first GPU in a Multi-GPU configuration." "\nA value of 1 means the first GPU will perform the same amount of work assigned to any other GPU.") self._add_setting(SettingType.BOOL, "Compress Radiance", "/rtx/pathtracing/mgpu/compressRadiance", tooltip="Enables lossy compression of per-pixel output radiance values.") self._add_setting(SettingType.BOOL, "Compress Albedo", "/rtx/pathtracing/mgpu/compressAlbedo", tooltip="Enables lossy compression of per-pixel output albedo values (needed by OptiX denoiser).") self._add_setting(SettingType.BOOL, "Compress Normals", "/rtx/pathtracing/mgpu/compressNormals", tooltip="Enables lossy compression of per-pixel output normal values (needed by OptiX denoiser).") self._add_setting(SettingType.BOOL, "Multi-Threading", "/rtx/multiThreading/enabled", tooltip="Enabling multi-threading improves UI responsiveness.") def destroy(self): self._change_cb1 = None super().destroy() class GlobalVolumetricEffectsSettingsFrame(SettingsCollectionFrame): """ PT Only Global Volumetric Effects Settings""" def _build_ui(self): self._add_setting(SettingType.BOOL, "Rayleigh Atmosphere", "/rtx/pathtracing/ptvol/raySky", tooltip="\nEnables an additional medium of Rayleigh-scattering particles to simulate a physically-based sky.") self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/ptvol/raySky", self._on_change) if self._settings.get("/rtx/pathtracing/ptvol/raySky"): self._add_setting(SettingType.FLOAT, " Rayleigh Atmosphere Scale", "/rtx/pathtracing/ptvol/raySkyScale", 0.01, 100, 1, tooltip="\nScales the size of the Rayleigh sky.") self._add_setting(SettingType.BOOL, " Skip Background", "/rtx/pathtracing/ptvol/raySkyDomelight", tooltip="\nIf a domelight is rendered for the sky color, the Rayleight Atmosphere is applied to the" "\nforeground while the background sky color is left unaffected.") def destroy(self): self._change_cb = None super().destroy() class PTSettingStack(RTXSettingsStack): def __init__(self) -> None: self._stack = ui.VStack(spacing=7, identifier=__class__.__name__) with self._stack: PathTracingSettingsFrame("Path-Tracing", parent=self) SamplingAndCachingSettingsFrame("Sampling & Caching", parent=self) AntiAliasingSettingsFrame("Anti-Aliasing", parent=self) FireflyFilterSettingsFrame("Firefly Filtering", parent=self) DenoisingSettingsFrame("Denoising", parent=self) NonUniformVolumesSettingsFrame("Non-uniform Volumes", parent=self) GlobalVolumetricEffectsSettingsFrame("Global Volumetric Effects", parent=self) AOVSettingsFrame("AOV", parent=self) MultiMatteSettingsFrame("Multi Matte", parent=self) gpu_count = carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount") or 0 if gpu_count > 1: MultiGPUSettingsFrame("Multi-GPU", parent=self)
18,001
Python
79.366071
279
0.70135
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/rt_widgets.py
import omni.kit.app import omni.ui as ui import carb.settings from omni.kit.widget.settings import SettingType from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame DEBUG_OPTIONS = False sampled_lighting_spp_items = {"1": 1, "2": 2, "4": 4, "8": 8} class EcoMode(SettingsCollectionFrame): """ ECO Mode """ def _frame_setting_path(self): return "/rtx/ecoMode/enabled" def _build_ui(self): self._add_setting(SettingType.INT, "Stop Rendering After This Many Frames Without Changes", "/rtx/ecoMode/maxFramesWithoutChange", 0, 100) class AntiAliasingSettingsFrame(SettingsCollectionFrame): """ DLSS """ def _on_antialiasing_change(self, *_): self._rebuild() def _build_ui(self): # Note: order depends on rtx::postprocessing::AntialiasingMethod antialiasing_ops = dict() if self._settings.get("/rtx-transient/post/dlss/supported") is True: antialiasing_ops["DLSS"] = 3 antialiasing_ops["DLAA"] = 4 if self._settings.get("/rtx-transient/hashed/995bcbda752ace40e33a4d131067d270"): self._add_setting(SettingType.BOOL, "Frame Generation", "/rtx-transient/dlssg/enabled", tooltip="\nDLSS Frame Generation boosts performance by using AI to generate more frames." "\nDLSS analyzes sequential frames and motion data to create additional high quality frames. This feature requires an Ada Lovelace architecture GPU.") self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx-transient/hashed/995bcbda752ace40e33a4d131067d270", self._on_antialiasing_change) self._add_setting(SettingType.BOOL, "Ray Reconstruction", "/rtx/newDenoiser/enabled", tooltip="\nDLSS Ray Reconstruction enhances image quality for ray-traced scenes with an NVIDIA" "\nsupercomputer-trained AI network that generates higher-quality pixels in between sampled rays.") self._add_setting_combo("Super Resolution", "/rtx/post/aa/op", antialiasing_ops, tooltip="\nDLSS Super Resolution boosts performance by using AI to output higher resolution frames from a lower resolution input." "\nDLSS samples multiple lower resolution images and uses motion data and feedback from prior frames to reconstruct native quality images.") self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/post/aa/op", self._on_antialiasing_change) antialiasingOpIdx = self._settings.get("/rtx/post/aa/op") exposure_ops = { "Force self evaluated" : 0, "PostProcess Autoexposure" : 1, "Fixed" : 2 } if antialiasingOpIdx == 1: """ TAA """ self._add_setting(SettingType.FLOAT, "Static scaling", "/rtx/post/scaling/staticRatio", 0.33, 1, 0.01) self._add_setting(SettingType.INT, "TAA Samples", "/rtx/post/taa/samples", 1, 16) self._add_setting(SettingType.FLOAT, "TAA history scale", "/rtx/post/taa/alpha", 0, 1, 0.1) elif antialiasingOpIdx == 2: """ FXAA """ self._add_setting(SettingType.FLOAT, "Subpixel Quality", "/rtx/post/fxaa/qualitySubPix", 0.0, 1.0, 0.02) self._add_setting(SettingType.FLOAT, "Edge Threshold", "/rtx/post/fxaa/qualityEdgeThreshold", 0.0, 1.0, 0.02) self._add_setting(SettingType.FLOAT, "Edge Threshold Min", "/rtx/post/fxaa/qualityEdgeThresholdMin", 0.0, 1.0, 0.02) elif antialiasingOpIdx == 3 or antialiasingOpIdx == 4: """ DLSS and DLAA """ if antialiasingOpIdx == 3: # needs to be in sync with DLSSMode enum dlss_opts = {"Auto": 3, "Performance": 0, "Balanced": 1, "Quality": 2} self._add_setting_combo(" Mode", "/rtx/post/dlss/execMode", dlss_opts, tooltip="\nAuto: Selects the best DLSS Mode for the current output resolution.\nPerformance: Higher performance than balanced mode.\nBalanced: Balanced for optimized performance and image quality.\nQuality: Higher image quality than balanced mode.") self._add_setting(SettingType.FLOAT, " Sharpness", "/rtx/post/aa/sharpness", 0.0, 1.0, 0.5, tooltip="\nHigher values produce sharper results.") self._add_setting_combo(" Exposure Mode", "/rtx/post/aa/autoExposureMode", exposure_ops, tooltip="\nChoose between Force self evaluated, PostProcess AutoExposure, Fixed.") self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/post/aa/autoExposureMode", self._on_antialiasing_change) autoExposureIdx = self._settings.get("/rtx/post/aa/autoExposureMode") if autoExposureIdx == 1: self._add_setting(SettingType.FLOAT, " Auto Exposure Multiplier", "/rtx/post/aa/exposureMultiplier", 0.00001, 10.0, 0.00001, tooltip="\nFactor with which to multiply the selected exposure mode.") elif autoExposureIdx == 2: self._add_setting(SettingType.FLOAT, " Fixed Exposure Value", "/rtx/post/aa/exposure", 0.00001, 1.0, 0.00001) def destroy(self): self._change_cb1 = None self._change_cb2 = None self._change_cb3 = None super().destroy() class DirectLightingSettingsFrame(SettingsCollectionFrame): """ Direct Lighting """ def _frame_setting_path(self): return "/rtx/directLighting/enabled" def _build_ui(self): self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/sampledLighting/enabled", self._on_change) self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/sampledLighting/autoEnable", self._on_change) self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/domeLight/enabled", self._on_change) self._change_cb4 = omni.kit.app.SettingChangeSubscription("/rtx/newDenoiser/enabled", self._on_change) self._change_cb5 = omni.kit.app.SettingChangeSubscription("/rtx/shadows/enabled", self._on_change) self._add_setting(SettingType.BOOL, "Shadows", "/rtx/shadows/enabled", tooltip="\nWhen disabled, lights will not cast shadows.") self._add_setting(SettingType.BOOL, "Sampled Direct Lighting Mode", "/rtx/directLighting/sampledLighting/enabled", tooltip="\nMode which favors performance with many lights (10 or more), at the cost of image quality.") self._add_setting(SettingType.BOOL, "Auto-enable Sampled Direct Lighting Above Light Count Threshold", "/rtx/directLighting/sampledLighting/autoEnable", tooltip="\nAutomatically enables Sampled Direct Lighting when the light count is greater than the Light Count Threshold.") if self._settings.get("/rtx/directLighting/sampledLighting/autoEnable"): self._add_setting(SettingType.INT, " Light Count Threshold", "/rtx/directLighting/sampledLighting/autoEnableLightCountThreshold", tooltip="\nLight count threshold above which Sampled Direct Lighting is automatically enabled.") if not self._settings.get("/rtx/directLighting/sampledLighting/enabled"): with ui.CollapsableFrame("Non-Sampled Lighting Settings", height=0): with ui.VStack(height=0, spacing=5): if self._settings.get("/rtx/shadows/enabled"): self._add_setting(SettingType.INT, " Shadow Samples per Pixel", "/rtx/shadows/sampleCount", 1, 16, tooltip="\nHigher values increase the quality of shadows at the cost of performance.") if not self._settings.get("/rtx/newDenoiser/enabled"): self._add_setting(SettingType.BOOL, " Low Resolution Shadow Denoiser", "/rtx/shadows/denoiser/quarterRes", tooltip="\nReduces the shadow denoiser resolution to gain performance at the cost of quality.") self._add_setting(SettingType.BOOL, " Dome Lighting", "/rtx/directLighting/domeLight/enabled", tooltip="\nEnables dome light contribution to diffuse BSDFs if Dome Light mode is IBL.") if self._settings.get("/rtx/directLighting/domeLight/enabled"): self._add_setting(SettingType.BOOL, " Dome Lighting in Reflections", "/rtx/directLighting/domeLight/enabledInReflections", tooltip="\nEnables Dome Light sampling in reflections at the cost of performance.") self._add_setting(SettingType.INT, " Dome Light Samples per Pixel", "/rtx/directLighting/domeLight/sampleCount", 0, 32, tooltip="\nHigher values increase dome light sampling quality at the cost of performance.") else: with ui.CollapsableFrame("Sampled Direct Lighting Settings", height=0): with ui.VStack(height=0, spacing=5): self._add_setting_combo(" Samples per Pixel", "/rtx/directLighting/sampledLighting/samplesPerPixel", sampled_lighting_spp_items, tooltip="\nHigher values increase the direct lighting quality at the cost of performance.") # self._add_setting(SettingType.BOOL, "Clamp Sample Count to Light Count", "/rtx/directLighting/sampledLighting/clampSamplesPerPixelToNumberOfLights", tooltip="\n\t When enabled, clamps the \"Samples per Pixel\" to the number of lights in the scene") self._add_setting(SettingType.FLOAT, " Max Ray Intensity", "/rtx/directLighting/sampledLighting/maxRayIntensity", 0.0, 1000000, 100, tooltip="\nClamps the brightness of a sample, which helps reduce fireflies, but may result in some loss of energy.") # self._add_setting(SettingType.BOOL, "Reflections: Clamp Sample Count to Light Count", "/rtx/reflections/sampledLighting/clampSamplesPerPixelToNumberOfLights", tooltip="\n\t When enabled, clamps the \"Reflections: Light Samples per Pixel\" to the number of lights in the scene") self._add_setting_combo(" Reflections: Light Samples per Pixel", "/rtx/reflections/sampledLighting/samplesPerPixel", sampled_lighting_spp_items, tooltip="\nHigher values increase the reflections quality at the cost of performance.") self._add_setting(SettingType.FLOAT, " Reflections: Max Ray Intensity", "/rtx/reflections/sampledLighting/maxRayIntensity", 0.0, 1000000, 100, tooltip="\nClamps the brightness of a sample, which helps reduce fireflies, but may result in some loss of energy.") if not self._settings.get("/rtx/newDenoiser/enabled"): firefly_filter_types = {"None" : "None", "Median" : "Cross-Bilateral Median", "RCRS" : "Cross-Bilateral RCRS"} self._add_setting_combo(" Firefly Filter", "/rtx/lightspeed/ReLAX/fireflySuppressionType", firefly_filter_types, tooltip="\nChoose the filter type (None, Median, RCRS). Clamps overly bright pixels to a maximum value.") self._add_setting(SettingType.BOOL, " History Clamping", "/rtx/lightspeed/ReLAX/historyClampingEnabled", tooltip="\nReduces temporal lag.") self._add_setting(SettingType.INT, " Denoiser Iterations", "/rtx/lightspeed/ReLAX/aTrousIterations", 1, 10, tooltip="\nNumber of times the frame is denoised.") # disabled with macro in the .hlsl as was causing extra spills & wasnt really used at all # self._add_setting(SettingType.BOOL, "Enable Extended Diffuse Backscattering", "/rtx/directLighting/diffuseBackscattering/enabled") # self._add_setting(SettingType.FLOAT, "Shadow Ray Offset", "/rtx/directLighting/diffuseBackscattering/shadowOffset", 0.1, 1000, 0.5) # self._add_setting(SettingType.FLOAT, "Extinction", "/rtx/directLighting/diffuseBackscattering/extinction", 0.001, 100, 0.01) self._add_setting(SettingType.BOOL, " Mesh-Light Sampling", "/rtx/directLighting/sampledLighting/ris/meshLights", tooltip="\nEnables direct illumination sampling of geometry with emissive materials.") # Hiding this to simplify things for now. Will be auto-enabled if /rtx/raytracing/fractionalCutoutOpacity is enabled # self._add_setting(SettingType.BOOL, "Enable Fractional Opacity", "/rtx/shadows/fractionalCutoutOpacity") # self._add_setting(SettingType.BOOL, "Show Lights", "/rtx/directLighting/showLights") #deprecated, use /rtx/raytracing/showLights def destroy(self): self._change_cb1 = None self._change_cb2 = None self._change_cb3 = None self._change_cb4 = None self._change_cb5 = None super().destroy() class ReflectionsSettingsFrame(SettingsCollectionFrame): """ Reflections """ def _frame_setting_path(self): return "/rtx/reflections/enabled" def _build_ui(self): self._add_setting(SettingType.FLOAT, "Roughness Cache Threshold", "/rtx/reflections/maxRoughness", 0.0, 1.0, 0.02, tooltip="\nRoughness threshold for approximated reflections. Higher values result in better quality, at the cost of performance.") self._add_setting(SettingType.INT, "Max Reflection Bounces", "/rtx/reflections/maxReflectionBounces", 0, 100, tooltip="\nNumber of bounces for reflection rays.") class TranslucencySettingsFrame(SettingsCollectionFrame): """ Translucency (Refraction) """ def _frame_setting_path(self): return "/rtx/translucency/enabled" def _build_ui(self): self._add_setting(SettingType.INT, "Max Refraction Bounces", "/rtx/translucency/maxRefractionBounces", 0, 100, tooltip="\nNumber of bounces for refraction rays.") self._add_setting(SettingType.BOOL, "Reflection Seen Through Refraction", "/rtx/translucency/reflectAtAllBounce", tooltip="\n\t When enabled, reflection seen through refraction is rendered. When disabled, reflection is limited to first bounce only. More accurate, but worse performance") self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/translucency/reflectAtAllBounce", self._on_change) if self._settings.get("/rtx/translucency/reflectAtAllBounce"): self._add_setting(SettingType.FLOAT, "Secondary Bounce Reflection Throughput Threshold", "/rtx/translucency/reflectionThroughputThreshold", 0.0, 1.0, 0.005, tooltip="\nThreshold below which reflection paths due to fresnel are no longer traced. Lower values result in higher quality at the cost of performance.") self._add_setting(SettingType.BOOL, "Fractional Cutout Opacity", "/rtx/raytracing/fractionalCutoutOpacity", tooltip="\nEnables fractional cutout opacity values resulting in a translucency-like effect similar to alpha-blending.") self._add_setting(SettingType.BOOL, "Depth Correction for DoF", "/rtx/translucency/virtualDepth", tooltip="\nImproves DoF for translucent (refractive) objects, but can result in worse performance.") self._add_setting(SettingType.BOOL, "Motion Vector Correction (experimental)", "/rtx/translucency/virtualMotion", tooltip="\nEnables motion vectors for translucent (refractive) objects, which can improve temporal rendering such as denoising, but can result in worse performance.") self._add_setting(SettingType.FLOAT, "World Epsilon Threshold", "/rtx/translucency/worldEps", 0.0001, 5, 0.01, tooltip="\nTreshold below which image-based reprojection is used to compute refractions. Lower values result in higher quality at the cost performance.") self._add_setting(SettingType.BOOL, "Roughness Sampling (experimental)", "/rtx/translucency/sampleRoughness", tooltip="\nEnables sampling roughness, such as for simulating frosted glass, but can result in worse performance.") def destroy(self): self._change_cb1 = None super().destroy() class CausticsSettingsFrame(SettingsCollectionFrame): """ Caustics """ def _frame_setting_path(self): return "/rtx/caustics/enabled" def _build_ui(self): self._add_setting(SettingType.INT, "Photon Count Multiplier", "/rtx/raytracing/caustics/photonCountMultiplier", 1, 5000, tooltip="\nFactor multiplied by 1024 to compute the total number of photons to generate from each light.") self._add_setting(SettingType.INT, "Photon Max Bounces", "/rtx/raytracing/caustics/photonMaxBounces", 1, 20, tooltip="\nMaximum number of bounces to compute for each light/photon path.") self._add_setting(SettingType.FLOAT, "Position Phi", "/rtx/raytracing/caustics/positionPhi", 0.1, 50) self._add_setting(SettingType.FLOAT, "Normal Phi", "/rtx/raytracing/caustics/normalPhi", 0.3, 1) self._add_setting(SettingType.INT, "Filter Iterations", "/rtx/raytracing/caustics/eawFilteringSteps", 0, 10, tooltip="\nNumber of iterations for the denoiser applied to the results of the caustics tracing pass.") class IndirectDiffuseLightingSettingsFrame(SettingsCollectionFrame): def _on_denoiser_change(self, *_): self._rebuild() def _build_ui(self): self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/ambientOcclusion/enabled", self._on_change) self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/indirectDiffuse/enabled", self._on_change) self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx/indirectDiffuse/denoiser/method", self._on_change) self._change_cb4 = omni.kit.app.SettingChangeSubscription("/rtx/newDenoiser/enabled", self._on_change) self._add_setting(SettingType.BOOL, "Indirect Diffuse GI", "/rtx/indirectDiffuse/enabled", tooltip="\nEnables indirect diffuse GI sampling.") if self._settings.get("/rtx/indirectDiffuse/enabled"): gi_denoising_techniques_ops = ["NVRTD", "NRD:Reblur"] self._add_setting(SettingType.INT, " Samples Per Pixel", "/rtx/indirectDiffuse/fetchSampleCount", 0, 4, tooltip="\nNumber of samples made for indirect diffuse GI. Higher number gives better GI quality, but worse performance.") self._add_setting(SettingType.INT, " Max Bounces", "/rtx/indirectDiffuse/maxBounces", 0, 16, tooltip="\nNumber of bounces approximated with indirect diffuse GI.") self._add_setting(SettingType.FLOAT, " Intensity", "/rtx/indirectDiffuse/scalingFactor", 0.0, 20.0, 0.1, tooltip="\nMultiplier for the indirect diffuse GI contribution.") self._add_setting_combo(" Denoising Mode", "/rtx/indirectDiffuse/denoiser/method", gi_denoising_techniques_ops) if self._settings.get("/rtx/indirectDiffuse/denoiser/method") == 0: self._add_setting(SettingType.INT, " Kernel Radius", "/rtx/indirectDiffuse/denoiser/kernelRadius", 1, 64, tooltip="\nControls the spread of local denoising area. Higher values results in smoother GI.") self._add_setting(SettingType.INT, " Iteration Count", "/rtx/indirectDiffuse/denoiser/iterations", 1, 10, tooltip="\nThe number of denoising passes. Higher values results in smoother looking GI.") self._add_setting(SettingType.INT, " Max History Length", "/rtx/indirectDiffuse/denoiser/temporal/maxHistory", 1, 100, tooltip="\nControls latency in GI updates. Higher values results in smoother looking GI.") if self._settings.get("/rtx/indirectDiffuse/denoiser/method") == 1: self._add_setting(SettingType.INT, " Frames In History", "/rtx/lightspeed/NRD_ReblurDiffuse/maxAccumulatedFrameNum", 0, 63) self._add_setting(SettingType.INT, " Frames In Fast History", "/rtx/lightspeed/NRD_ReblurDiffuse/maxFastAccumulatedFrameNum", 0, 63) self._add_setting(SettingType.FLOAT, " Plane Distance Sensitivity", "/rtx/lightspeed/NRD_ReblurDiffuse/planeDistanceSensitivity", 0, 1, 0.01) self._add_setting(SettingType.FLOAT, " Blur Radius", "/rtx/lightspeed/NRD_ReblurDiffuse/blurRadius", 0, 100, 5) self._add_setting(SettingType.BOOL, "Ambient Occlusion", "/rtx/ambientOcclusion/enabled", tooltip="\nEnables ambient occlusion.") if self._settings.get("/rtx/ambientOcclusion/enabled"): self._add_setting(SettingType.FLOAT, " Ray Length (cm)", "/rtx/ambientOcclusion/rayLength", 0.0, 2000.0, tooltip="\nThe radius around the intersection point which the ambient occlusion affects.") self._add_setting(SettingType.INT, " Minimum Samples Per Pixel", "/rtx/ambientOcclusion/minSamples", 1, 16, tooltip="\nMinimum number of samples per frame for ambient occlusion sampling.") self._add_setting(SettingType.INT, " Maximum Samples Per Pixel", "/rtx/ambientOcclusion/maxSamples", 1, 16, tooltip="\nMaximum number of samples per frame for ambient occlusion sampling.") aoDenoiserMode = { "None" : 0, "Aggressive" : 1, "Simple" : 2, } if not self._settings.get("/rtx/newDenoiser/enabled"): self._add_setting_combo(" Denoiser", "/rtx/ambientOcclusion/denoiserMode", aoDenoiserMode, tooltip="\nAllows for increased AO denoising at the cost of more blurring.") self._add_setting(SettingType.COLOR3, "Ambient Light Color", "/rtx/sceneDb/ambientLightColor", tooltip="\nColor of the global environment lighting.") self._add_setting(SettingType.FLOAT, "Ambient Light Intensity", "/rtx/sceneDb/ambientLightIntensity", 0.0, 10.0, 0.1, tooltip="\nBrightness of the global environment lighting.") def destroy(self): self._change_cb1 = None self._change_cb2 = None self._change_cb3 = None self._change_cb4 = None super().destroy() class RTMultiGPUSettingsFrame(SettingsCollectionFrame): """ Multi-GPU """ def _frame_setting_path(self): return "/rtx/realtime/mgpu/enabled" def _build_ui(self): self._add_setting(SettingType.BOOL, "Automatic Tiling", "/rtx/realtime/mgpu/autoTiling/enabled", tooltip="\nAutomatically determines the image-space grid used to distribute rendering to available GPUs." "\nThe image rendering is split into a large tile per GPU with a small overlap region between them." "\nNote that by default not necessarily all GPUs are used. The approximate number of tiles is viewport" "\nresolution divided by the Minimum Megapixels Per Tile setting, since at low resolution small tiles distributed" "\nacross too many devices decreases performance due to multi-GPU overheads." "\nDisable automatic tiling to manually specify the number of tiles to be distributed across devices.") self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/realtime/mgpu/autoTiling/enabled", self._on_change) if self._settings.get("/rtx/realtime/mgpu/autoTiling/enabled"): self._add_setting(SettingType.FLOAT, " Minimum Megapixels Per Tile", "/rtx/realtime/mgpu/autoTiling/minMegaPixelsPerTile", 0.1, 2.0, 0.1, tooltip="\nThe minimum number of Megapixels each tile should have after screen-space subdivision.") else: currentGpuCount = self._settings.get("/renderer/multiGpu/currentGpuCount") self._add_setting(SettingType.INT, "Tile Count", "/rtx/realtime/mgpu/tileCount", 2, currentGpuCount, tooltip="\nNumber of tiles to split the image into. Usually this should match the number of GPUs, but can be less.") self._add_setting(SettingType.INT, "Tile Overlap (Pixels)", "/rtx/realtime/mgpu/tileOverlap", 0, 256, 0.1, tooltip="\nWidth, in pixels, of the overlap region between any two neighboring tiles.") self._add_setting(SettingType.FLOAT, "GPU 0 Weight", "/rtx/realtime/mgpu/masterDeviceLoadBalancingWeight", 0, 1, 0.001, tooltip="\nThis normalized weight can be used to decrease the rendering workload on the primary device for each viewport" "\nin relation to the other secondary devices, which can be helpful for load balancing in situations where the primary" "\ndevice also needs to perform additional expensive operations such as denoising and post-processing.") self._add_setting(SettingType.BOOL, "Multi-Threading", "/rtx/multiThreading/enabled", tooltip="\nExecute per-device render command recording in separate threads.") class SubsurfaceScatteringSettingsFrame(SettingsCollectionFrame): """ Subsurface Scattering """ def _frame_setting_path(self): return "/rtx/raytracing/subsurface/enabled" def _on_change(self, *_): self._rebuild() def _build_ui(self): self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/sampledLighting/enabled", self._on_change) self._add_setting(SettingType.INT, "Max Samples Per Frame", "/rtx/raytracing/subsurface/maxSamplePerFrame", 1, 128, tooltip="\nMax samples per frame for the infinitely-thick geometry SSS approximation.") # self._add_setting(SettingType.FLOAT, "History Weight", "/rtx/raytracing/subsurface/historyWeight", 0.001, 0.5, 0.02) # self._add_setting(SettingType.FLOAT, "Variance Threshold", "/rtx/raytracing/subsurface/targetVariance", 0.001, 1, 0.05) # self._add_setting(SettingType.FLOAT, "World space sample projection Threshold", "/rtx/raytracing/subsurface/shadowRayThreshold", 0, 1, 0.01) self._add_setting(SettingType.BOOL, "Firefly Filtering", "/rtx/raytracing/subsurface/fireflyFiltering/enabled", tooltip="\nEnables firefly filtering for the subsurface scattering. The maximum filter intensity is determined by '/rtx/directLighting/sampledLighting/maxRayIntensity'.") self._add_setting(SettingType.BOOL, "Denoiser", "/rtx/raytracing/subsurface/denoiser/enabled", tooltip="\nEnables denoising for the subsurface scattering.") if self._settings.get("/rtx/directLighting/sampledLighting/enabled"): self._add_setting(SettingType.BOOL, "Denoise Irradiance Input", "/rtx/directLighting/sampledLighting/irradiance/denoiser/enabled", tooltip="\nDenoise the irradiance output from sampled lighting pass before it's used, helps in complex lighting conditions" "\nor if there are large area lights which makes irradiance estimation difficult with low sampled lighting sample count.") self._add_setting(SettingType.BOOL, "Transmission", "/rtx/raytracing/subsurface/transmission/enabled", tooltip="\nEnables transmission of light through the medium, but requires additional samples and denoising.") self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/raytracing/subsurface/transmission/enabled", self._on_change) if self._settings.get("/rtx/raytracing/subsurface/transmission/enabled"): self._add_setting(SettingType.INT, " BDSF Sample Count", "/rtx/raytracing/subsurface/transmission/bsdfSampleCount", 0, 8, tooltip="\nTransmission sample count per frame.") self._add_setting(SettingType.INT, " Samples Per BSDF Sample", "/rtx/raytracing/subsurface/transmission/perBsdfScatteringSampleCount", 0, 16, tooltip="\nTransmission samples count per BSDF Sample. Samples per pixel per frame = BSDF Sample Count * Samples Per BSDF Sample.") self._add_setting(SettingType.FLOAT, " Screen-Space Fallback Threshold", "/rtx/raytracing/subsurface/transmission/screenSpaceFallbackThresholdScale", 0.0001, 1, tooltip="\nTransmission threshold for screen-space fallback.") self._add_setting(SettingType.BOOL, " Half-Resolution Rendering", "/rtx/raytracing/subsurface/transmission/halfResolutionBackfaceLighting", tooltip="\nEnables rendering transmission in half-resolution to improve performance at the expense of quality.") self._add_setting(SettingType.BOOL, " Sample Guiding", "/rtx/raytracing/subsurface/transmission/ReSTIR/enabled", tooltip="\nEnables transmission sample guiding, which may help with complex lighting scenarios.") self._add_setting(SettingType.BOOL, " Denoiser", "/rtx/raytracing/subsurface/transmission/denoiser/enabled", tooltip="\nEnables transmission denoising.") def destroy(self): self._change_cb1 = None self._change_cb2 = None super().destroy() class GlobalVolumetricEffectsSettingsFrame(SettingsCollectionFrame): """ RT Only Global Volumetric Effects Settings""" def _build_ui(self): self._add_setting(SettingType.INT, "Accumulation Frames", "/rtx/raytracing/inscattering/maxAccumulationFrames", 0, 256, tooltip="\nNumber of frames samples accumulate over temporally. High values reduce noise, but increase lighting update times.") self._add_setting(SettingType.INT, "Depth Slices Count", "/rtx/raytracing/inscattering/depthSlices", 16, 1024, tooltip="\nNumber of layers in the voxel grid to be allocated. High values result in higher precision at the cost of memory and performance.") self._add_setting(SettingType.INT, "Pixel Density", "/rtx/raytracing/inscattering/pixelRatio", 4, 64, tooltip="\nLower values result in higher fidelity volumetrics at the cost of performance and memory (depending on the # of depth slices).") self._add_setting(SettingType.FLOAT, "Slice Distribution Exponent", "/rtx/raytracing/inscattering/sliceDistributionExponent", 1, 16, tooltip="\nControls the number (and relative thickness) of the depth slices.") self._add_setting(SettingType.INT, "Inscatter Upsample", "/rtx/raytracing/inscattering/inscatterUpsample", 1, 64, tooltip="\n") self._add_setting(SettingType.FLOAT, "Inscatter Blur Sigma", "/rtx/raytracing/inscattering/blurSigma", 0.0, 10.0, 0.01, tooltip="\nSigma parameter for the Gaussian filter used to spatially blur the voxel grid. 1 = no blur, higher values blur further.") self._add_setting(SettingType.FLOAT, "Inscatter Dithering Scale", "/rtx/raytracing/inscattering/ditheringScale", 0, 10000, tooltip="\nThe scale of the noise dithering. Used to reduce banding from quantization on smooth gradients.") self._add_setting(SettingType.FLOAT, "Spatial Sample Jittering Scale", "/rtx/raytracing/inscattering/spatialJitterScale", 0.0, 1, 0.0001, tooltip="\nScales how far light samples within a voxel are spatially jittered: 0 = only from the center, 1 = the entire voxel's volume.") self._add_setting(SettingType.FLOAT, "Temporal Reprojection Jittering Scale", "/rtx/raytracing/inscattering/temporalJitterScale", 0.0, 1, 0.0001, tooltip="\nScales how far to offset temporally-reprojected samples within a voxel: 0 = only from the center, 1 = the entire voxel's volume." "\nActs like a temporal blur and helps reduce noise under motion.") self._add_setting(SettingType.BOOL, "Use 32-bit Precision", "/rtx/raytracing/inscattering/use32bitPrecision", tooltip="\nAllocate the voxel grid with 32-bit per channel color instead of 16-bit. This doubles memory usage and reduces performance, generally avoided.") self._add_setting(SettingType.BOOL, "Flow Sampling", "/rtx/raytracing/inscattering/enableFlowSampling", tooltip="\n") self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/raytracing/inscattering/enableFlowSampling", self._on_change) if self._settings.get("/rtx/raytracing/inscattering/enableFlowSampling"): self._add_setting(SettingType.INT, " Min Layer", "/rtx/raytracing/inscattering/minFlowLayer", 0, 64, tooltip="\n") self._add_setting(SettingType.INT, " Max Layer", "/rtx/raytracing/inscattering/maxFlowLayer", 0, 64, tooltip="\n") self._add_setting(SettingType.FLOAT, " Density Scale", "/rtx/raytracing/inscattering/flowDensityScale", 0.0, 100.0, tooltip="\n") self._add_setting(SettingType.FLOAT, " Density Offset", "/rtx/raytracing/inscattering/flowDensityOffset", 0.0, 100.0, tooltip="\n") def destroy(self): self._change_cb1 = None super().destroy() class RTSettingStack(RTXSettingsStack): def __init__(self) -> None: self._stack = ui.VStack(spacing=7, identifier=__class__.__name__) with self._stack: EcoMode("Eco Mode", parent=self) AntiAliasingSettingsFrame("NVIDIA DLSS", parent=self) DirectLightingSettingsFrame("Direct Lighting", parent=self) IndirectDiffuseLightingSettingsFrame("Indirect Diffuse Lighting", parent=self) ReflectionsSettingsFrame("Reflections", parent=self) translucency = TranslucencySettingsFrame("Translucency", parent=self) SubsurfaceScatteringSettingsFrame("Subsurface Scattering", parent=translucency) CausticsSettingsFrame("Caustics", parent=self) GlobalVolumetricEffectsSettingsFrame("Global Volumetric Effects", parent=self) gpuCount = carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount") if gpuCount and gpuCount > 1: RTMultiGPUSettingsFrame("Multi-GPU", parent=self)
33,283
Python
90.189041
338
0.698314
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/tests/__init__.py
from .test_settings import TestRTXCoreSettingsUI
49
Python
48.999951
49
0.877551
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/tests/test_settings.py
import carb import omni.kit.test import omni.usd import tempfile import pathlib import rtx.settings from omni.kit import ui_test from omni.rtx.tests.test_common import wait_for_update settings = carb.settings.get_settings() EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) USD_DIR = EXTENSION_FOLDER_PATH.joinpath("data/usd") class TestRTXCoreSettingsUI(omni.kit.test.AsyncTestCase): VALUE_EPSILON = 0.00001 async def setUp(self): super().setUp() # We need to trigger Iray load to get the default render-settings values written to carb.settings # Viewports state is valid without any open stage, and only loads renderer when stage is opened. await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): omni.kit.window.property.managed_frame.reset_collapsed_state() def get_render_setings_window(self): render_settings_window = ui_test.find("Render Settings") render_settings_window.widget.height = 1200 render_settings_window.widget.width = 600 render_settings_window.widget.visible = True return render_settings_window def set_renderer(self, render_settings_window, index): #select the combo box item box = render_settings_window.find("Frame/VStack[0]/HStack[0]/ComboBox[*]") box.model.get_item_value_model(None, 0).set_value(index) def compare_floats(self, a, b, epsilon): self.assertEqual(len(a), len(b)) for i in range(0, len(a)): self.assertLessEqual( abs(a[i] - b[i]), epsilon, "a[" + str(i) + "] = " + str(a[i]) + ", b[" + str(i) + "] = " + str(b[i]) ) def compare_float(self, a, b, epsilon): self.assertLessEqual(abs(a - b), epsilon) def open_usd(self, usdSubpath: pathlib.Path): path = USD_DIR.joinpath(usdSubpath) omni.usd.get_context().open_stage(str(path)) async def test_bool_checkbox_setting(self): ''' check that we can switch on/off back face culling in Common/Geometry ''' render_settings_window = self.get_render_setings_window() setting_name = "/rtx/hydra/faceCulling/enabled" #Cycle through Realtime, path-tracing renders for index in range(0, 2): self.set_renderer(render_settings_window, index) # Set initial value settings.set(setting_name, False) await omni.kit.app.get_app().next_update_async() #choose the "Common" tab in each case button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]") await button.click() #Get the collapsable frame for Geometry and open it collapsable_frame = render_settings_window.find("**/Geometry") collapsable_frame.widget.collapsed = False await omni.kit.app.get_app().next_update_async() #This is the back face culling hstack back_face_culling_setting = collapsable_frame.find("/**/HStack_Back_Face_Culling") self.assertTrue(isinstance(back_face_culling_setting.widget, omni.ui.HStack)) check_box = back_face_culling_setting.find("**/CheckBox[0]") self.assertTrue(isinstance(check_box.widget, omni.ui.CheckBox)) await check_box.click(human_delay_speed=10) face_culling_value = settings.get(setting_name) self.assertTrue(face_culling_value) await check_box.click(human_delay_speed=10) face_culling_value = settings.get(setting_name) self.assertFalse(face_culling_value) async def test_combo_box_setting(self): ''' check that we can set TBNFrame mode Combo Box in Common/Geometry ''' render_settings_window = self.get_render_setings_window() setting_name = "/rtx/hydra/TBNFrameMode" #Cycle through Realtime, path-tracing renders for index in range(0, 2): self.set_renderer(render_settings_window, index) # Set initial value settings.set(setting_name, 0) await omni.kit.app.get_app().next_update_async() #choose the "Common" tab in each case button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]") await button.click() #Get the collapsable frame for Geometry and open it collapsable_frame = render_settings_window.find("**/Geometry") collapsable_frame.widget.collapsed = False await omni.kit.app.get_app().next_update_async() tangent_space_setting = collapsable_frame.find("/**/HStack_Normal_&_Tangent_Space_Generation_Mode") self.assertTrue(isinstance(tangent_space_setting.widget, omni.ui.HStack)) combo_box = tangent_space_setting.find("ComboBox[0]") self.assertTrue(isinstance(combo_box.widget, omni.ui.ComboBox)) combo_box.model.get_item_value_model(None, 0).set_value(1) tbn_frame_mode_setting = settings.get(setting_name) self.assertTrue(tbn_frame_mode_setting == 1) async def test_float_setting(self): ''' check that we can set float MDL Animation Time Override in Common/Materials ''' render_settings_window = self.get_render_setings_window() setting_name = "/rtx/animationTime" #Cycle through Realtime, path-tracing renders for index in range(0, 2): self.set_renderer(render_settings_window, index) # Set initial value settings.set(setting_name, -1.0) await omni.kit.app.get_app().next_update_async() #choose the "Common" tab in each case button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]") await button.click() #Get the collapsable frame for Materials and expand it collapsable_frame = render_settings_window.find("**/Geometry") collapsable_frame.widget.collapsed = True collapsable_frame = render_settings_window.find("**/Materials") collapsable_frame.widget.collapsed = False await omni.kit.app.get_app().next_update_async() tangent_space_setting = collapsable_frame.find("**/HStack_Animation_Time_Override") self.assertTrue(isinstance(tangent_space_setting.widget, omni.ui.HStack)) slider = tangent_space_setting.find("FloatDrag[0]") self.assertTrue(isinstance(slider.widget, omni.ui.FloatDrag)) await ui_test.human_delay(50) await slider.input("20.0") tbn_frame_mode_setting = settings.get(setting_name) self.assertAlmostEqual(tbn_frame_mode_setting, 20.0, 2, f"was actually {tbn_frame_mode_setting}") async def run_render_settings_storage_helper(self, must_save=False): with tempfile.TemporaryDirectory() as tmpdirname: usd_context = omni.usd.get_context() await omni.kit.app.get_app().next_update_async() # save the file with various types of setting value types. # Note: if ever any of these were removed, replace them with a new setting of the same type. setting_fog_b = "/rtx/fog/enabled" # bool setting_meter_unit_f = "/rtx/scene/renderMeterPerUnit" # float setting_heatmap_i = "/rtx/debugView/heatMapPass" # int setting_max_bounce_i = "/rtx/pathtracing/maxBounces" # int, pathtracer setting_mat_white_s = "/rtx/debugMaterialWhite" # string setting_ambinet_arr_f = "/rtx/sceneDb/ambientLightColor" # array of float3 setting_saturation_arr_f = "/rtx/post/colorcorr/saturation" # array of double3 # settings with special kSettingFlagTransient, treated like rtx-transient. setting_mthread_transient_b = "/rtx/multiThreading/enabled" # uses kSettingFlagTransient in C++ setting_dir_light_b = "/rtx-transient/disable/directLightingSampled" # manual transient setting_place_col_b = "/persistent/rtx/resourcemanager/placeholderTextureColor" # persistent # set as transient in [[test]] setting_fog_dist_i = "/rtx/fog/fogEndDist" # int setting_fog_color_arr_f = "/rtx/fog/fogColor" # array of float settings.set_bool(setting_fog_b, True) settings.set_float(setting_meter_unit_f, 0.5) settings.set_int(setting_heatmap_i, 3) settings.set_int(setting_max_bounce_i, 33) settings.set_string(setting_mat_white_s, "NoActualMat") # a random non-existent material settings.set_float_array(setting_ambinet_arr_f, [0.4, 0.5, 0.6]) settings.set_float_array(setting_saturation_arr_f, [0.7, 0.8, 0.9]) # with special flags # Note: we can't test sync/async settings, since they are needed for the loading stage. settings.set_bool(setting_mthread_transient_b, False) settings.set_bool(setting_dir_light_b, True) settings.set_float_array(setting_place_col_b, [0.4, 0.4, 0.4]) # this was set in [[test]] as transient settings.set(setting_fog_dist_i, 999) settings.set_float_array(setting_fog_color_arr_f, [0.21, 0.21, 0.21]) # verify rtx-flags is set as transient in [[test]] setting_fog_dist_flags = rtx.settings.get_associated_setting_flags_path(setting_fog_dist_i); setting_fog_color_flags = rtx.settings.get_associated_setting_flags_path(setting_fog_color_arr_f); value_fog_dist_flags = settings.get(setting_fog_dist_flags) value_fog_color_flags = settings.get(setting_fog_color_flags) self.assertEqual(value_fog_dist_flags, rtx.settings.SETTING_FLAGS_TRANSIENT) self.assertEqual(value_fog_color_flags, rtx.settings.SETTING_FLAGS_TRANSIENT) tmp_usd_path = pathlib.Path(tmpdirname) / "tmp_rtx_setting.usd" result = usd_context.save_as_stage(str(tmp_usd_path)) self.assertTrue(result) stage = usd_context.get_stage() # Make stage dirty so reload will work stage.DefinePrim("/World", "Xform") await omni.kit.app.get_app().next_update_async() # Change settings settings.set_bool(setting_fog_b, False) settings.set_float(setting_meter_unit_f, 0.3) settings.set_int(setting_heatmap_i, 2) settings.set_int(setting_max_bounce_i, 9) settings.set_string(setting_mat_white_s, "NoActualMat2") # a random non-existent material settings.set_float_array(setting_ambinet_arr_f, [0.2, 0.2, 0.2]) settings.set_float_array(setting_saturation_arr_f, [0.3, 0.3, 0.3]) # with special flags settings.set_bool(setting_mthread_transient_b, True) settings.set_bool(setting_dir_light_b, False) settings.set_float_array(setting_place_col_b, [0.6, 0.6, 0.6]) await omni.kit.app.get_app().next_update_async() # Reload stage will reload all the rtx settings # Reload with native API stage.Reload will not reopen settings # but only lifecycle API in Kit. await usd_context.reopen_stage_async() await omni.kit.app.get_app().next_update_async() value_fog_b = settings.get(setting_fog_b) value_meter_unit_f = settings.get(setting_meter_unit_f) value_heatmap_i = settings.get(setting_heatmap_i) value_max_bounce_i = settings.get(setting_max_bounce_i) value_mat_white_s = settings.get(setting_mat_white_s) value_ambinet_arr_f = settings.get(setting_ambinet_arr_f) value_saturation_arr_f = settings.get(setting_saturation_arr_f) # with special flags value_mthread_transient_b = settings.get(setting_mthread_transient_b) value_dir_light_b = settings.get(setting_dir_light_b) value_place_col_b = settings.get(setting_place_col_b) # Temporarily transient via rtx-flags specified in [[test]] value_fog_dist_i = settings.get(setting_fog_dist_i) value_fog_dist_flags = settings.get(setting_fog_dist_flags) value_fog_color_arr_f = settings.get(setting_fog_color_arr_f) value_fog_color_flags = settings.get(setting_fog_color_flags) # New stage to release the temp usd file await usd_context.new_stage_async() if must_save: self.assertEqual(value_fog_b, True) self.compare_float(value_meter_unit_f, 0.5, self.VALUE_EPSILON) self.assertEqual(value_heatmap_i, 3) self.assertEqual(value_max_bounce_i, 33) self.assertEqual(value_mat_white_s, "NoActualMat") self.compare_floats(value_ambinet_arr_f, [0.4, 0.5, 0.6], self.VALUE_EPSILON) self.compare_floats(value_saturation_arr_f, [0.7, 0.8, 0.9], self.VALUE_EPSILON) else: self.assertNotEqual(value_fog_b, True) self.assertNotAlmostEqual(value_meter_unit_f, 0.5, delta=self.VALUE_EPSILON) self.assertNotEqual(value_heatmap_i, 3) self.assertNotEqual(value_max_bounce_i, 33) self.assertNotEqual(value_mat_white_s, "NoActualMat") # self.compare_floats(value_ambinet_arr_f, [0.4, 0.5, 0.6], self.VALUE_EPSILON) # self.compare_floats(value_saturation_arr_f, [0.7, 0.8, 0.9], self.VALUE_EPSILON)) # The ones with special flags should NOT be saved or loaded from USD # same with persistent and rtx-transient self.assertEqual(value_mthread_transient_b, True) self.assertEqual(value_dir_light_b, False) self.compare_floats(value_place_col_b, [0.6, 0.6, 0.6], self.VALUE_EPSILON) # Temporarily transient via rtx-flags. Should not be saved to or loaded from USD self.assertEqual(value_fog_dist_i, 999) self.assertEqual(value_fog_dist_flags, rtx.settings.SETTING_FLAGS_TRANSIENT) self.compare_floats(value_fog_color_arr_f, [0.21, 0.21, 0.21], self.VALUE_EPSILON) self.assertEqual(value_fog_color_flags, rtx.settings.SETTING_FLAGS_TRANSIENT) async def run_render_settings_loading_helper(self, must_load=True, must_reset=True): usd_context = omni.usd.get_context() await omni.kit.app.get_app().next_update_async() # Custom values already stored in the USD test setting_tonemap_arr_f = "/rtx/post/tonemap/whitepoint" setting_sample_threshold_i = "/rtx/directLighting/sampledLighting/autoEnableLightCountThreshold" setting_max_roughness_f = "/rtx/reflections/maxRoughness" setting_reflections_b = "/rtx/reflections/enabled" # setting with kSettingFlagTransient, that should not be loaded if saved in the old USD files. setting_mthread_transient_b = "/rtx/multiThreading/enabled" setting_mat_syncload_b = "/rtx/materialDb/syncLoads" setting_hydra_mat_syncload_b = "/rtx/hydra/materialSyncLoads" # set as transient in [[test]] setting_fog_dist_i = "/rtx/fog/fogEndDist" # int setting_fog_color_arr_f = "/rtx/fog/fogColor" # array of float await omni.kit.app.get_app().next_update_async() settings.set_float_array(setting_tonemap_arr_f, [0.15, 0.16, 0.17]) settings.set(setting_sample_threshold_i, 43) # change settings with kSettingFlagTransient settings.set_bool(setting_mthread_transient_b, True) settings.set_bool(setting_mat_syncload_b, True) settings.set_bool(setting_hydra_mat_syncload_b, False) # this was set in [[test]] as transient and not saved in USD. settings.set(setting_fog_dist_i, 999) settings.set_float_array(setting_fog_color_arr_f, [0.21, 0.21, 0.21]) await omni.kit.app.get_app().next_update_async() self.open_usd("cubeRtxSettings.usda") await wait_for_update() value_tonemap_arr_f = settings.get(setting_tonemap_arr_f) value_sample_threshold_i = settings.get(setting_sample_threshold_i) value_max_roughness_f = settings.get(setting_max_roughness_f) value_reflections_b = settings.get(setting_reflections_b) value_mthread_transient_b = settings.get(setting_mthread_transient_b) value_mat_syncload_b = settings.get(setting_mat_syncload_b) value_hydra_mat_syncload_b = settings.get(setting_hydra_mat_syncload_b) # Not stored in USD file, testing the default value value_fog_dist_i = settings.get(setting_fog_dist_i) value_fog_color_arr_f = settings.get(setting_fog_color_arr_f) if must_load: # Must match to what we stored in USD self.compare_floats(value_tonemap_arr_f, [0.1, 0.2, 0.3], self.VALUE_EPSILON) self.assertEqual(value_sample_threshold_i, 77) self.compare_float(value_max_roughness_f, 0.53, self.VALUE_EPSILON) self.assertEqual(value_reflections_b, False) else: if must_reset: # Current default values set in C++ code. self.compare_floats(value_tonemap_arr_f, [1.0, 1.0, 1.0], self.VALUE_EPSILON) self.assertEqual(value_sample_threshold_i, 10) else: # what we set before loading the USD and not defaults. self.compare_floats(value_tonemap_arr_f, [0.15, 0.16, 0.17], self.VALUE_EPSILON) self.assertEqual(value_sample_threshold_i, 43) self.assertNotAlmostEqual(value_max_roughness_f, 0.53, delta=self.VALUE_EPSILON) self.assertNotEqual(value_reflections_b, False) # Must skip loading setting that use kSettingFlagTransient flag from USD # Such settings are not saved or loaded in USD, ut may exist in old USD files, such as cubeRtxSettings.usda. # if usd was re-saved, you need to manually add those transient setting for this test. Otherwise, they will be removed. self.assertEqual(value_mthread_transient_b, True) self.assertEqual(value_mat_syncload_b, True) self.assertEqual(value_hydra_mat_syncload_b, False) # Temporarily transient via rtx-flags. Should not be saved to or loaded from USD self.assertEqual(value_fog_dist_i, 999) self.compare_floats(value_fog_color_arr_f, [0.21, 0.21, 0.21], self.VALUE_EPSILON) async def test_render_settings_storage(self): await self.run_render_settings_storage_helper(must_save=True) async def test_render_settings_not_storing(self): # Test to make sure rtx settings are not stored in USD, when asked. storeRenderSettingsToStage = "/app/omni.usd/storeRenderSettingsToUsdStage"; settings.set_bool(storeRenderSettingsToStage, False) await self.run_render_settings_storage_helper(must_save=False) settings.set_bool(storeRenderSettingsToStage, True) async def test_render_settings_loading(self): await self.run_render_settings_loading_helper() async def test_render_settings_not_loading(self): # Test to make sure rtx settings are not loaded from USD, when asked. loadRenderSettingsFromStage = "/app/omni.usd/loadRenderSettingsFromUsdStage"; settings.set_bool(loadRenderSettingsFromStage, False) await self.run_render_settings_loading_helper(must_load=False) settings.set_bool(loadRenderSettingsFromStage, True) async def test_render_settings_not_loading_not_reset(self): # Test to make sure rtx settings are not loaded from USD, when asked. loadRenderSettingsFromStage = "/app/omni.usd/loadRenderSettingsFromUsdStage"; resetRenderSettingsStage = "/app/omni.usd/resetRenderSettingsInUsdStage"; settings.set_bool(loadRenderSettingsFromStage, False) settings.set_bool(resetRenderSettingsStage, False) await self.run_render_settings_loading_helper(must_load=False, must_reset=False) settings.set_bool(loadRenderSettingsFromStage, True) settings.set_bool(resetRenderSettingsStage, True)
20,535
Python
48.484337
127
0.645142
omniverse-code/kit/exts/omni.rtx.settings.core/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.rtx.settings.dev`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [0.5.10] - 2022-11-22 ### Changed - Renamed all Debug Views that are intended to be RT-specific with RT prefix. - Moved RT and PT MGPU settings frames to the bottom to be consistent with one another. ## [0.5.9] - 2022-11-16 ### Changed - For photosentivity/seizure concerns, included [WARNING: Flashing Colors] to Debug View names known to flash. ## [0.5.8] - 2022-10-26 ### Added - Added tooltips for all render settings. - Added BVH Splits settings to 'Common/Geometry/Curves Settings'. - Added Heat Map views to 'Common/Debug View'. - Added an 'Invisible Lights Roughness Threshold' setting to 'Common/Lighting'. - Added 'Frame Generation' setting to 'Real-Time/NVIDIA DLSS'. - Added 'New Denoiser (experimental)' setting to 'Real-Time/Direct Lighting'. - Added 'Multi Matte' settings in 'Interactive (Path Tracing)'. - Added 'Adaptive Sampling' settings in 'Interactive (Path Tracing)/Path-Tracing'. ### Changed - Refactored 'Lighting Mode' settings for Dome Lights in 'Common/Lighting'; now provides 'Image-Based Lighting' (simply a rename of the previous default) and 'Limited Image-Based Lighting'. - Improved UI for setting-dependency clarity; settings which depend on others now tend to be indented under them, and hidden when the parent setting is not enabled. - Improved PT AOV names for clarity. ## [0.5.7] - 2022-06-04 ### Changed - Make sure a stage is loaded to trigger RTX loading in Viewport. ## [0.5.6] - 2022-05-23 ### Changed - Add omni.hydra.rtx as test depenency ## [0.5.5] - 2022-03-11 ### Changed - Rename 'Path Traced' to 'Interactive (Path Tracing)' ## [0.5.4] - 2020-11-27 ### Changed - Update to use new RenderSettingsFactory entry point in rtx.window.settings ## [0.5.3] - 2020-11-25 ### Changed - Registration/Unregistration process - Added Reset RTX settings button - Added texture compression setting in common settings - Updated to match current Render Settings 1.0 - make Enable/Disable of settings consistent ## [0.5.2] - 2020-11-18 ### Changed - Updated to match current Render Settings 1.0 ## [0.5.1] - 2020-11-16 ### Changed - Shortened any labels that went over the new width (220) ## [0.5.0] - 2020-11-04 ### Changed - initial release
2,364
Markdown
30.959459
189
0.726734
omniverse-code/kit/exts/omni.rtx.settings.core/docs/README.md
# Developer RTX Settings [omni.rtx.settings.dev] This is a example of RTX settings extensions that can register custom settings
129
Markdown
31.499992
78
0.806202
omniverse-code/kit/exts/omni.rtx.settings.core/docs/index.rst
omni.rtx.settings.core: omni.rtx.settings.dev ############################################## .. toctree:: :maxdepth: 1 CHANGELOG
139
reStructuredText
12.999999
46
0.446043
omniverse-code/kit/exts/omni.activity.pump/config/extension.toml
[package] title = "Omni Activity Pump" category = "Telemetry" version = "1.0.0" description = "The activity and the progress processor gets pumped every frame" authors = ["NVIDIA"] keywords = ["activity"] [[python.module]] name = "omni.activity.pump" [[native.plugin]] path = "bin/*.plugin" [dependencies] "omni.activity.core" = {} [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", "omni.ui", ]
552
TOML
18.068965
79
0.655797
omniverse-code/kit/exts/omni.usd_resolver/omni/usd_resolver/__init__.py
import os from typing import Tuple, List, Callable if hasattr(os, "add_dll_directory"): scriptdir = os.path.dirname(os.path.realpath(__file__)) dlldir = os.path.abspath(os.path.join(scriptdir, "../../..")) with os.add_dll_directory(dlldir): from ._omni_usd_resolver import * else: from ._omni_usd_resolver import *
341
Python
27.499998
65
0.662757
omniverse-code/kit/exts/omni.usd_resolver/omni/usd_resolver/_omni_usd_resolver.pyi
from __future__ import annotations import omni.usd_resolver._omni_usd_resolver import typing import omni.usd_resolver __all__ = [ "Event", "EventState", "Subscription", "get_version", "register_event_callback", "set_checkpoint_message", "set_mdl_builtins" ] class Event(): """ Members: RESOLVING READING WRITING """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ READING: omni.usd_resolver.Event # value = <Event.READING: 1> RESOLVING: omni.usd_resolver.Event # value = <Event.RESOLVING: 0> WRITING: omni.usd_resolver.Event # value = <Event.WRITING: 2> __members__: dict # value = {'RESOLVING': <Event.RESOLVING: 0>, 'READING': <Event.READING: 1>, 'WRITING': <Event.WRITING: 2>} pass class EventState(): """ Members: STARTED SUCCESS FAILURE """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ FAILURE: omni.usd_resolver.EventState # value = <EventState.FAILURE: 2> STARTED: omni.usd_resolver.EventState # value = <EventState.STARTED: 0> SUCCESS: omni.usd_resolver.EventState # value = <EventState.SUCCESS: 1> __members__: dict # value = {'STARTED': <EventState.STARTED: 0>, 'SUCCESS': <EventState.SUCCESS: 1>, 'FAILURE': <EventState.FAILURE: 2>} pass class Subscription(): def __enter__(self) -> _omni_usd_resolver.Subscription: ... def __exit__(self, arg0: object, arg1: object, arg2: object) -> None: ... def unregister(self) -> None: ... pass def get_version() -> str: """ Get the version of USD Resolver being used. Returns: Returns a human readable version string. """ def register_event_callback(callback: typing.Callable[[str, omni.usd_resolver.Event, omni.usd_resolver.EventState, int], None]) -> omni.usd_resolver.Subscription: """ Register a function that will be called any time something interesting happens. Args: callback: Callback to be called with the event. Returns: Subscription Object. Callback will be unregistered once subcription is released. """ def set_checkpoint_message(message: str) -> None: """ Set the message to be used for atomic checkpoints created when saving files. Args: message (str): Checkpoint message. """ def set_mdl_builtins(arg0: typing.List[str]) -> None: """ Set a list of built-in MDLs. Resolving an MDL in this list will return immediately rather than performing a full resolution. """
3,521
unknown
28.35
162
0.573701
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnLoaded.rst
.. _omni_graph_action_OnLoaded_1: .. _omni_graph_action_OnLoaded: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Loaded :keywords: lang-en omnigraph node graph:action,event threadsafe compute-on-request action on-loaded On Loaded ========= .. <description> Triggers the output on the first update of the graph after it is created or loaded. This will run before any other event node, and will only run once after this node is created. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:execOut", "``execution``", "Executes after graph creation or loading", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnLoaded" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On Loaded" "Categories", "graph:action,event" "Generated Class Name", "OgnOnLoadedDatabase" "Python Module", "omni.graph.action"
1,487
reStructuredText
24.220339
177
0.581708
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnRationalTimeSyncGate.rst
.. _omni_graph_action_RationalTimeSyncGate_1: .. _omni_graph_action_RationalTimeSyncGate: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Rational Sync Gate :keywords: lang-en omnigraph node graph:action,flowControl threadsafe action rational-time-sync-gate Rational Sync Gate ================== .. <description> This node triggers when all its input executions have triggered successively at the same rational time. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None" "Sync Denominator (*inputs:rationalTimeDenominator*)", "``uint64``", "Denominator of the synchronization time.", "0" "Sync Numerator (*inputs:rationalTimeNumerator*)", "``int64``", "Numerator of the synchronization time.", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Execute Out (*outputs:execOut*)", "``execution``", "The output execution", "None" "Sync Denominator (*outputs:rationalTimeDenominator*)", "``uint64``", "Denominator of the synchronization time.", "None" "Sync Numerator (*outputs:rationalTimeNumerator*)", "``int64``", "Numerator of the synchronization time.", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.RationalTimeSyncGate" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Rational Sync Gate" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnRationalTimeSyncGateDatabase" "Python Module", "omni.graph.action"
2,174
reStructuredText
29.208333
124
0.612695
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnForLoop.rst
.. _omni_graph_action_ForLoop_1: .. _omni_graph_action_ForLoop: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: For Loop :keywords: lang-en omnigraph node graph:action,flowControl threadsafe action for-loop For Loop ======== .. <description> Executes the a loop body once for each value within a range. When step is positive, the values in the range are determined by the formula: r[i] = start + step*i, i >= 0 & r[i] < stop. When step is negative the constraint is instead r[i] > stop. A step of zero is an error. The break input can be used to break out of the loop before the last index. The finished output is executed after all iterations are complete, or when the loop was broken .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Break (*inputs:breakLoop*)", "``execution``", "Breaks out of the loop when the loop body traversal reaches it", "None" "In (*inputs:execIn*)", "``execution``", "Input execution", "None" "Start (*inputs:start*)", "``int``", "The first value in the range", "0" "Step (*inputs:step*)", "``int``", "The step size of the range", "1" "Stop (*inputs:stop*)", "``int``", "The limiting value of the range", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:finished", "``execution``", "Executed when the loop is finished", "None" "outputs:index", "``int``", "The current or last index within the range", "None" "outputs:loopBody", "``execution``", "Executed for each index in the range", "None" "outputs:value", "``int``", "The current or last value of the range", "None" State ----- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "state:i", "``int``", "The next position in the range or -1 when loop is not active", "-1" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.ForLoop" "Version", "1" "Extension", "omni.graph.action" "Icon", "ogn/icons/omni.graph.action.ForLoop.svg" "Has State?", "True" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "tags", "range" "uiName", "For Loop" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnForLoopDatabase" "Python Module", "omni.graph.action"
2,806
reStructuredText
30.539325
172
0.596222
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSendCustomEvent.rst
.. _omni_graph_action_SendCustomEvent_1: .. _omni_graph_action_SendCustomEvent: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Send Custom Event :keywords: lang-en omnigraph node graph:action,event action send-custom-event Send Custom Event ================= .. <description> Sends a custom event, which will asynchronously trigger any OnCustomEvent nodes which are listening for the same eventName .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Bundle (*inputs:bundle*)", "``bundle``", "Bundle to be sent with the event", "None" "Event Name (*inputs:eventName*)", "``token``", "The name of the custom event", "" "inputs:execIn", "``execution``", "Input Execution", "None" "Path (*inputs:path*)", "``token``", "The path associated with the event", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:execOut", "``execution``", "Output Execution", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.SendCustomEvent" "Version", "1" "Extension", "omni.graph.action" "Has State?", "True" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Send Custom Event" "Categories", "graph:action,event" "Generated Class Name", "OgnSendCustomEventDatabase" "Python Module", "omni.graph.action"
1,883
reStructuredText
25.535211
122
0.580988
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnDelay.rst
.. _omni_graph_action_Delay_1: .. _omni_graph_action_Delay: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Delay :keywords: lang-en omnigraph node graph:action,time threadsafe action delay Delay ===== .. <description> This node suspends the graph for a period of time before continuing. This node, and nodes upstream of this node are locked for the duration of the delay, which means any subsequent executions will be ignored. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Duration (*inputs:duration*)", "``double``", "The duration of the delay (Seconds)", "0.0" "Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Finished (*outputs:finished*)", "``execution``", "Triggered when the delay is finished", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.Delay" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Delay" "Categories", "graph:action,time" "Generated Class Name", "OgnDelayDatabase" "Python Module", "omni.graph.action"
1,767
reStructuredText
24.623188
208
0.580079
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnVariableChange.rst
.. _omni_graph_action_OnVariableChange_1: .. _omni_graph_action_OnVariableChange: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Variable Change :keywords: lang-en omnigraph node graph:action,event threadsafe action on-variable-change On Variable Change ================== .. <description> Executes an output execution pulse when the chosen variable changes .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True" "", "*literalOnly*", "1", "" "Variable Name (*inputs:variableName*)", "``token``", "The name of the graph variable to use.", "" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Changed (*outputs:changed*)", "``execution``", "The execution output", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnVariableChange" "Version", "1" "Extension", "omni.graph.action" "Has State?", "True" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On Variable Change" "Categories", "graph:action,event" "Generated Class Name", "OgnOnVariableChangeDatabase" "Python Module", "omni.graph.action"
1,849
reStructuredText
25.056338
140
0.574905
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSequence.rst
.. _omni_graph_action_Sequence_1: .. _omni_graph_action_Sequence: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sequence :keywords: lang-en omnigraph node graph:action,flowControl threadsafe action sequence Sequence ======== .. <description> Outputs an execution pulse along output A and B in sequence .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:execIn", "``execution``", "Input execution", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "A (*outputs:a*)", "``execution``", "The first output path", "None" "B (*outputs:b*)", "``execution``", "The second outputs path", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.Sequence" "Version", "1" "Extension", "omni.graph.action" "Icon", "ogn/icons/omni.graph.action.Sequence.svg" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "hidden", "true" "uiName", "Sequence" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnSequenceDatabase" "Python Module", "omni.graph.action"
1,665
reStructuredText
22.464788
97
0.561562
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnPlaybackTick.rst
.. _omni_graph_action_OnPlaybackTick_1: .. _omni_graph_action_OnPlaybackTick: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Playback Tick :keywords: lang-en omnigraph node graph:action,event threadsafe action on-playback-tick On Playback Tick ================ .. <description> Executes an output execution pulse during playback .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Delta Seconds (*outputs:deltaSeconds*)", "``double``", "The number of seconds elapsed since the last update", "None" "Frame (*outputs:frame*)", "``double``", "The global playback time in frames, equivalent to (time * fps)", "None" "Tick (*outputs:tick*)", "``execution``", "The execution output", "None" "Time (*outputs:time*)", "``double``", "The global playback time in seconds", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnPlaybackTick" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On Playback Tick" "Categories", "graph:action,event" "Generated Class Name", "OgnOnPlaybackTickDatabase" "Python Module", "omni.graph.action"
1,715
reStructuredText
26.677419
121
0.581924
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSetPrimActive.rst
.. _omni_graph_action_SetPrimActive_1: .. _omni_graph_action_SetPrimActive: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Set Prim Active :keywords: lang-en omnigraph node graph:action,sceneGraph WriteOnly action set-prim-active Set Prim Active =============== .. <description> Set a Prim active or not in the stage. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:active", "``bool``", "Wheter to set the prim active or not", "False" "inputs:execIn", "``execution``", "Input execution", "None" "Prim Path (*inputs:prim*)", "``path``", "The prim to be (de)activated", "" "Prim (*inputs:primTarget*)", "``target``", "The prim to be (de)activated", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Execute Out (*outputs:execOut*)", "``execution``", "The output execution", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.SetPrimActive" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Set Prim Active" "Categories", "graph:action,sceneGraph" "Generated Class Name", "OgnSetPrimActiveDatabase" "Python Module", "omni.graph.action"
1,809
reStructuredText
24.492957
97
0.565506
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnMessageBusEvent.rst
.. _omni_graph_action_OnMessageBusEvent_1: .. _omni_graph_action_OnMessageBusEvent: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On MessageBus Event :keywords: lang-en omnigraph node graph:action,event compute-on-request action on-message-bus-event On MessageBus Event =================== .. <description> Event node which fires when the specified event is popped from the App Message Bus. Carb events can be sent with Python: msg = carb.events.type_from_string('my_event_name') omni.kit.app.get_app().get_message_bus_event_stream().push(msg, payload={'arg1': 42}) The event payload data will be copied in to matching dynamic output attributes if they exist. In the previous example, 42 would be copied to outputs:arg1 if possible .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Event Name (*inputs:eventName*)", "``token``", "The name of the custom event", "" "", "*literalOnly*", "1", "" "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Received (*outputs:execOut*)", "``execution``", "Executes when the event is received", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnMessageBusEvent" "Version", "1" "Extension", "omni.graph.action" "Has State?", "True" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On MessageBus Event" "Categories", "graph:action,event" "Generated Class Name", "OgnOnMessageBusEventDatabase" "Python Module", "omni.graph.action"
2,227
reStructuredText
30.380281
424
0.607993
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnKeyboardInput.rst
.. _omni_graph_action_OnKeyboardInput_3: .. _omni_graph_action_OnKeyboardInput: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Keyboard Input :keywords: lang-en omnigraph node graph:action,input:keyboard compute-on-request action on-keyboard-input On Keyboard Input ================= .. <description> Event node which fires when a keyboard event occurs. The event can be a combination of keys, containing key modifiers of ctrl, alt and shift, and a normal key of any key. keyIn. For key combinations, the press event requires all keys to be pressed, with the normal key pressed last. The release event is only triggered once when one of the chosen keys released after pressed event happens. For example: if the combination is ctrl-shift-D, the pressed event happens once right after D is pressed while both ctrl and shit are held. And the release event happens only once when the user releases any key of ctrl, shift and D while holding them. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Alt (*inputs:altIn*)", "``bool``", "When true, the node will check with a key modifier Alt", "False" "", "*literalOnly*", "1", "" "Ctrl (*inputs:ctrlIn*)", "``bool``", "When true, the node will check with a key modifier Control", "False" "", "*literalOnly*", "1", "" "Key In (*inputs:keyIn*)", "``token``", "The key to trigger the downstream execution ", "A" "", "*displayGroup*", "parameters", "" "", "*literalOnly*", "1", "" "", "*allowedTokens*", "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,Apostrophe,Backslash,Backspace,CapsLock,Comma,Del,Down,End,Enter,Equal,Escape,F1,F10,F11,F12,F2,F3,F4,F5,F6,F7,F8,F9,GraveAccent,Home,Insert,Key0,Key1,Key2,Key3,Key4,Key5,Key6,Key7,Key8,Key9,Left,LeftAlt,LeftBracket,LeftControl,LeftShift,LeftSuper,Menu,Minus,NumLock,Numpad0,Numpad1,Numpad2,Numpad3,Numpad4,Numpad5,Numpad6,Numpad7,Numpad8,Numpad9,NumpadAdd,NumpadDel,NumpadDivide,NumpadEnter,NumpadEqual,NumpadMultiply,NumpadSubtract,PageDown,PageUp,Pause,Period,PrintScreen,Right,RightAlt,RightBracket,RightControl,RightShift,RightSuper,ScrollLock,Semicolon,Slash,Space,Tab,Up", "" "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True" "", "*literalOnly*", "1", "" "Shift (*inputs:shiftIn*)", "``bool``", "When true, the node will check with a key modifier Shift", "False" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:isPressed", "``bool``", "True if the key was pressed, False if it was released", "None" "Key Out (*outputs:keyOut*)", "``token``", "The key that was pressed or released", "None" "Pressed (*outputs:pressed*)", "``execution``", "Executes when key was pressed", "None" "Released (*outputs:released*)", "``execution``", "Executes when key was released", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnKeyboardInput" "Version", "3" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On Keyboard Input" "Categories", "graph:action,input:keyboard" "Generated Class Name", "OgnOnKeyboardInputDatabase" "Python Module", "omni.graph.action"
3,870
reStructuredText
45.083333
662
0.652196
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnGamepadInput.rst
.. _omni_graph_action_OnGamepadInput_1: .. _omni_graph_action_OnGamepadInput: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Gamepad Input :keywords: lang-en omnigraph node graph:action,input:gamepad compute-on-request action on-gamepad-input On Gamepad Input ================ .. <description> Event node which fires when a gamepad event occurs. This node only capture events on buttons, excluding triggers and sticks .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Gamepad Element In (*inputs:gamepadElementIn*)", "``token``", "The gamepad button to trigger the downstream execution.", "Face Button Bottom" "", "*displayGroup*", "parameters", "" "", "*literalOnly*", "1", "" "", "*allowedTokens*", "Face Button Bottom,Face Button Right,Face Button Left,Face Button Top,Left Shoulder,Right Shoulder,Special Left,Special Right,Left Stick Button,Right Stick Button,D-Pad Up,D-Pad Right,D-Pad Down,D-Pad Left", "" "Gamepad ID (*inputs:gamepadId*)", "``uint``", "Gamepad id number starting from 0. Each gamepad will be registered automatically with an unique ID monotonically increasing in the order they are connected. If gamepad is disconnected, the ID assigned to the remaining gamepad will be adjusted accordingly so the IDs are always continues and start from 0 Change this value to a non-existing ID will result an error prompt in the console and the node will not listen to any gamepad input.", "0" "", "*literalOnly*", "1", "" "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:isPressed", "``bool``", "True if the gamepad button was pressed, False if it was released", "None" "Pressed (*outputs:pressed*)", "``execution``", "Executes when gamepad element was pressed", "None" "Released (*outputs:released*)", "``execution``", "Executes when gamepad element was released", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnGamepadInput" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "On Gamepad Input" "Categories", "graph:action,input:gamepad" "Generated Class Name", "OgnOnGamepadInputDatabase" "Python Module", "omni.graph.action"
3,008
reStructuredText
38.077922
494
0.639295
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnForEach.rst
.. _omni_graph_action_ForEach_1: .. _omni_graph_action_ForEach: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: For Each Loop :keywords: lang-en omnigraph node graph:action,flowControl threadsafe action for-each For Each Loop ============= .. <description> Executes the a loop body once for each element in the input array. The finished output is executed after all iterations are complete .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Input Array (*inputs:arrayIn*)", "``['bool[]', 'colord[3][]', 'colord[4][]', 'colorf[3][]', 'colorf[4][]', 'colorh[3][]', 'colorh[4][]', 'double[2][]', 'double[3][]', 'double[4][]', 'double[]', 'float[2][]', 'float[3][]', 'float[4][]', 'float[]', 'frame[4][]', 'half[2][]', 'half[3][]', 'half[4][]', 'half[]', 'int64[]', 'int[2][]', 'int[3][]', 'int[4][]', 'int[]', 'matrixd[3][]', 'matrixd[4][]', 'normald[3][]', 'normalf[3][]', 'normalh[3][]', 'pointd[3][]', 'pointf[3][]', 'pointh[3][]', 'quatd[4][]', 'quatf[4][]', 'quath[4][]', 'texcoordd[2][]', 'texcoordd[3][]', 'texcoordf[2][]', 'texcoordf[3][]', 'texcoordh[2][]', 'texcoordh[3][]', 'timecode[]', 'token[]', 'transform[4][]', 'uchar[]', 'uint64[]', 'uint[]', 'vectord[3][]', 'vectorf[3][]', 'vectorh[3][]']``", "The array to loop over", "None" "inputs:execIn", "``execution``", "Input execution", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:arrayIndex", "``int``", "The current or last index visited", "None" "outputs:element", "``['bool', 'colord[3]', 'colord[4]', 'colorf[3]', 'colorf[4]', 'colorh[3]', 'colorh[4]', 'double', 'double[2]', 'double[3]', 'double[4]', 'float', 'float[2]', 'float[3]', 'float[4]', 'frame[4]', 'half', 'half[2]', 'half[3]', 'half[4]', 'int', 'int64', 'int[2]', 'int[3]', 'int[4]', 'matrixd[3]', 'matrixd[4]', 'normald[3]', 'normalf[3]', 'normalh[3]', 'pointd[3]', 'pointf[3]', 'pointh[3]', 'quatd[4]', 'quatf[4]', 'quath[4]', 'texcoordd[2]', 'texcoordd[3]', 'texcoordf[2]', 'texcoordf[3]', 'texcoordh[2]', 'texcoordh[3]', 'timecode', 'token', 'transform[4]', 'uchar', 'uint', 'uint64', 'vectord[3]', 'vectorf[3]', 'vectorh[3]']``", "The current or last element of the array visited", "None" "outputs:finished", "``execution``", "Executed when the loop is finished", "None" "outputs:loopBody", "``execution``", "Executed for each element of the array", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.ForEach" "Version", "1" "Extension", "omni.graph.action" "Icon", "ogn/icons/omni.graph.action.ForEach.svg" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "For Each Loop" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnForEachDatabase" "Python Module", "omni.graph.action"
3,366
reStructuredText
45.123287
806
0.553179
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnAddPrimRelationship.rst
.. _omni_graph_action_AddPrimRelationship_1: .. _omni_graph_action_AddPrimRelationship: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Add Prim Relationship :keywords: lang-en omnigraph node sceneGraph WriteOnly action add-prim-relationship Add Prim Relationship ===================== .. <description> Adds a target path to a relationship property. If the relationship property does not exist it will be created. Duplicate targets will not be added. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:execIn", "``execution``", "The input execution port.", "None" "Relationship Name (*inputs:name*)", "``token``", "Name of the relationship property.", "" "Prim Path (*inputs:path*)", "``path``", "Path of the prim with the relationship property.", "" "Target Path (*inputs:target*)", "``path``", "The target path to be added, which may be a prim, attribute or another relationship.", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Is Successful (*outputs:isSuccessful*)", "``bool``", "Whether the node has successfully added the new target to the relationship.", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.AddPrimRelationship" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Add Prim Relationship" "Categories", "sceneGraph" "Generated Class Name", "OgnAddPrimRelationshipDatabase" "Python Module", "omni.graph.action"
2,100
reStructuredText
28.591549
147
0.601429