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.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/main_generator.py
""" Management for the functions that generate code from the .ogn files. """ import os import omni.graph.core as og import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn # ================================================================================ class Generator: """Class responsible for generating files from the current .ogn model""" def __init__(self, extension: ogn.OmniGraphExtension): """Initialize the model being used for generation Args: extension: Container with information needed to configure the parser """ self.ogn_file_path = None self.extension = extension self.node_interface_wrapper = None self.configuration = None # ---------------------------------------------------------------------- def parse(self, ogn_file_path: str): """Perform an initial parsing pass on a .ogn file, keeping the parse information locally for later generation Args: ogn_file_path: Path to the .ogn file to use for regeneration Raises: ParseError: File parsing failed FileNotFoundError: .ogn file did not exist """ ogt.dbg_ui(f"Parsing OGN file {ogn_file_path}") self.ogn_file_path = ogn_file_path # Parse the .ogn file with open(ogn_file_path, "r", encoding="utf-8") as ogn_fd: self.node_interface_wrapper = ogn.NodeInterfaceWrapper(ogn_fd, self.extension.extension_name) ogt.dbg_ui(f"Generated a wrapper {self.node_interface_wrapper}") # Set up the configuration to write into the correct directories base_name, _ = os.path.splitext(os.path.basename(ogn_file_path)) self.configuration = ogn.GeneratorConfiguration( ogn_file_path, self.node_interface_wrapper.node_interface, self.extension.import_path, self.extension.import_path, base_name, None, ogn.OGN_PARSE_DEBUG, og.Settings.generator_settings(), ) # ---------------------------------------------------------------------- def check_wrapper(self): """Check to see if the node_interface_wrapper was successfully parsed Raises: NodeGenerationError if a parsed interface was not available """ if self.node_interface_wrapper is None: raise ogn.NodeGenerationError(f"Cannot generate file due to parse error in {self.ogn_file_path}") # ---------------------------------------------------------------------- def generate_cpp(self): """Take the existing OGN model and generate the C++ database interface header file for it Returns: True if the file was successfully generated, else False """ ogt.dbg_ui("Generator::generate_cpp") self.check_wrapper() # Generate the C++ NODEDatabase.h file if this .ogn description allows it if self.node_interface_wrapper.can_generate("c++"): self.configuration.destination_directory = self.extension.ogn_include_directory ogn.generate_cpp(self.configuration) else: ogt.dbg_ui("...Skipping -> File cannot generate C++ database") # ---------------------------------------------------------------------- def generate_python(self): """Take the existing OGN model and generate the Python database interface file for it Returns: True if the file was successfully generated, else False """ ogt.dbg_ui("Generator::generate_python") self.check_wrapper() # Generate the Python NODEDatabase.py file if this .ogn description allows it if self.node_interface_wrapper.can_generate("python"): self.configuration.destination_directory = self.extension.ogn_python_directory ogn.generate_python(self.configuration) else: ogt.dbg_ui("...Skipping -> File cannot generate Python database") # ---------------------------------------------------------------------- def generate_documentation(self): """Take the existing OGN model and generate the documentation file for it Returns: True if the file was successfully generated, else False """ ogt.dbg_ui("Generator::generate_documentation") self.check_wrapper() # Generate the documentation NODE.rst file if this .ogn description allows it if self.node_interface_wrapper.can_generate("docs"): self.configuration.destination_directory = self.extension.ogn_docs_directory ogn.generate_documentation(self.configuration) else: ogt.dbg_ui("...Skipping -> File cannot generate documentation file") # ---------------------------------------------------------------------- def generate_tests(self): """Take the existing OGN model and generate the tests file for it Returns: True if the file was successfully generated, else False """ ogt.dbg_ui("Generator::generate_tests") self.check_wrapper() # Generate the tests TestNODE.py file if this .ogn description allows it if self.node_interface_wrapper.can_generate("tests"): self.configuration.destination_directory = self.extension.ogn_tests_directory ogn.generate_tests(self.configuration) else: ogt.dbg_ui("...Skipping -> File cannot generate tests file") # ---------------------------------------------------------------------- def generate_usd(self): """Take the existing OGN model and generate the usd file for it Returns: True if the file was successfully generated, else False """ ogt.dbg_ui("Generator::generate_usd") self.check_wrapper() # Generate the USD NODE_Template.usda file if this .ogn description allows it if self.node_interface_wrapper.can_generate("usd"): self.configuration.destination_directory = self.extension.ogn_usd_directory ogn.generate_usd(self.configuration) else: ogt.dbg_ui("...Skipping -> File cannot generate usd file") # ---------------------------------------------------------------------- def generate_template(self): """Take the existing OGN model and generate the template file for it Returns: True if the file was successfully generated, else False """ ogt.dbg_ui("Generator::generate_template") self.check_wrapper() # Generate the template NODE_Template.c++|py file if this .ogn description allows it if self.node_interface_wrapper.can_generate("template"): self.configuration.destination_directory = self.extension.ogn_nodes_directory ogn.generate_template(self.configuration) else: ogt.dbg_ui("...Skipping -> File cannot generate template file")
6,998
Python
40.414201
117
0.579737
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/attribute_tuple_count_manager.py
""" Manager class for the attribute tuple count combo box. """ from typing import Callable, Optional import omni.graph.tools as ogt from carb import log_warn from omni import ui from .ogn_editor_utils import ComboBoxOptions TupleChangeCallback = Optional[Callable[[int], None]] # ====================================================================== # ID values for widgets that are editable or need updating ID_ATTR_TYPE_TUPLE_COUNT = "attributeTypeTupleCount" # ====================================================================== # Tooltips for the editable widgets TOOLTIPS = {ID_ATTR_TYPE_TUPLE_COUNT: "Fixed number of basic elements, e.g. 3 for a float[3]"} # ====================================================================== class AttributeTupleComboBox(ui.AbstractItemModel): """Implementation of a combo box that shows attribute tuple counts available Internal Properties: __controller: Controller for the data of the attribute this will modify __legal_values: List of tuples the current attribute type supports __value_index: Dictionary of tuple-value to combobox index for reverse lookup __count_changed_callback: Option callback to execute when a new tuple count is chosen __current_index: Model for the currently selected value __subscription: Subscription object for the tuple count change callback __items: List of models for each legal value in the combobox """ def __init__(self, controller, count_changed_callback: TupleChangeCallback = None): """Initialize the attribute tuple count combo box details""" super().__init__() self.__controller = controller self.__legal_values = controller.tuples_supported self.__value_index = {} for (index, value) in enumerate(self.__legal_values): self.__value_index[value] = index self.__count_changed_callback = count_changed_callback self.__current_index = ui.SimpleIntModel() self.__current_index.set_value(self.__value_index[self.__controller.tuple_count]) self.__subscription = self.__current_index.subscribe_value_changed_fn(self.__on_tuple_count_changed) assert self.__subscription # Using a list comprehension instead of values() guarantees the ordering self.__items = [ComboBoxOptions(str(value)) for value in self.__legal_values] def destroy(self): """Cleanup when the combo box is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self.__count_changed_callback = None self.__subscription = None self.__legal_values = None self.__value_index = None ogt.destroy_property(self, "__current_index") ogt.destroy_property(self, "__items") def get_item_children(self, item): """Get the model children of this item""" return self.__items def get_item_value_model(self, item, column_id: int): """Get the model at the specified column_id""" if item is None: return self.__current_index return item.model def __on_tuple_count_changed(self, new_value: ui.SimpleIntModel): """Callback executed when a new tuple count was selected""" self._item_changed(None) new_selection = "Unknown" try: # The combo box new_value is the index of the selection within the list of legal values. # Report the index selected in case there isn't a corresponding selection value, then use the selection # value to define the new tuple count. ogt.dbg_ui(f"Set attribute tuple count to {new_value.as_int}") new_selection = self.__legal_values[new_value.as_int] if self.__count_changed_callback: self.__count_changed_callback(new_selection) except AttributeError as error: log_warn(f"Tuple count '{new_selection}' on attribute '{self.__controller.name}' was rejected - {error}") # ====================================================================== class AttributeTupleCountManager: """Handle the combo box and responses for getting and setting attribute tuple count values Properties: __widget: ComboBox widget controlling the tuple count __widget_model: Model for the ComboBox value """ def __init__(self, controller, count_changed_callback: TupleChangeCallback = None): """Set up the initial UI and model Args: controller: AttributePropertiesController in charge of the data for the attribute being managed count_changed_callback: Optional callback to execute when a new tuple count is chosen """ self.__widget_model = AttributeTupleComboBox(controller, count_changed_callback) self.__widget = ui.ComboBox( self.__widget_model, alignment=ui.Alignment.LEFT_BOTTOM, name=ID_ATTR_TYPE_TUPLE_COUNT, tooltip=TOOLTIPS[ID_ATTR_TYPE_TUPLE_COUNT], ) assert self.__widget def destroy(self): """Cleanup when the object is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") ogt.destroy_property(self, "__widget_model") ogt.destroy_property(self, "__widget")
5,300
Python
43.175
117
0.626038
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/file_manager.py
""" Support for all file operations initiated by the Editor interface """ from __future__ import annotations import asyncio import json import os from typing import Optional import omni.graph.tools as ogt from carb import log_error from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.widget.prompt import Prompt from omni.kit.window.filepicker import FilePickerDialog from .ogn_editor_utils import Callback, OptionalCallback, callback_name # ====================================================================== # Shared set of filters for the open and save dialogs OGN_FILTERS = [("*.ogn", ".ogn Files (*.ogn)")] # ====================================================================== class FileManager: """Manager of the file interface to .ogn files. External Properties: ogn_path: Full path to the .ogn file ogn_file: File component of ogn_path ogn_directory: Directory component of ogn_path Internal Properties: __controller: Controller class providing write access to the OGN data model __current_directory: Directory in which the current file lives. __current_file: Name of the .ogn file as of the last open or save. None if the data does not come from a file. __open_file_dialog: External window used for opening a new .ogn file __save_file_dialog: External window used for saving the .ogn file __unsaved_changes: True if there are changes in the file management that require the file to be saved again """ def __init__(self, controller): """Set up the default file picker dialogs to be used later""" ogt.dbg_ui("Initializing the file manager") self.__current_file = None self.__current_directory = None self.__controller = controller self.__unsaved_changes = controller.is_dirty() self.__open_file_dialog = None self.__save_file_dialog = None # ---------------------------------------------------------------------- def __on_filter_ogn_files(self, item: FileBrowserItem) -> bool: """Callback to filter the choices of file names in the open or save dialog""" if not item or item.is_folder: return True ogt.dbg_ui(f"Filtering OGN files on {item.path}") # Show only files with listed extensions return os.path.splitext(item.path)[1] == ".ogn" and os.path.basename(item.path).startswith("Ogn") # ---------------------------------------------------------------------- def __on_file_dialog_error(self, error: str): """Callback executed when there is an error in the file dialogs""" log_error(error) # ---------------------------------------------------------------------- def destroy(self): """Called when the FileManager is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self.__current_file = None self.__current_directory = None self.__controller = None self.__save_file_dialog = None # ---------------------------------------------------------------------- @property def ogn_path(self) -> Optional[str]: """Returns the current full path to the .ogn file, None if that path is not fully defined""" try: return os.path.join(self.__current_directory, self.__current_file) except TypeError: return None # ---------------------------------------------------------------------- @property def ogn_file(self) -> Optional[str]: """Returns the name of the current .ogn file""" return self.__current_file @ogn_file.setter def ogn_file(self, new_file: str): """Sets a new directory in which the .ogn file will reside. The base name of the file is unchanged""" ogt.dbg_ui(f"Setting new FileManager ogn_file to {new_file}") if new_file != self.__current_file: self.__unsaved_changes = True self.__current_file = new_file # ---------------------------------------------------------------------- @property def ogn_directory(self) -> Optional[str]: """Returns the current directory in which the .ogn file will reside""" return self.__current_directory @ogn_directory.setter def ogn_directory(self, new_directory: str): """Sets a new directory in which the .ogn file will reside. The base name of the file is unchanged""" ogt.dbg_ui(f"Setting new FileManager ogn_directory to {new_directory}") if self.__current_directory != new_directory: self.__current_directory = new_directory # ---------------------------------------------------------------------- @staticmethod def __on_remove_ogn_file(file_to_remove: str): """Callback executed when removal of the file is requested""" try: os.remove(file_to_remove) except Exception as error: # noqa: PLW0703 log_error(f"Could not remove existing file {file_to_remove} - {error}") # ---------------------------------------------------------------------- def remove_obsolete_file(self, old_file_path: Optional[str]): """Check to see if an obsolete file path exists and request deletion if it does""" if old_file_path is not None and os.path.isfile(old_file_path): old_file_name = os.path.basename(old_file_path) Prompt( "Remove old file", f"Delete the existing .ogn file with the old name {old_file_name}?", ok_button_text="Yes", cancel_button_text="No", cancel_button_fn=self.__on_remove_ogn_file(old_file_path), modal=True, ).show() # ---------------------------------------------------------------------- def has_unsaved_changes(self) -> bool: """Returns True if the file needs to be saved to avoid losing data""" return self.__controller.is_dirty() or self.__unsaved_changes # ---------------------------------------------------------------------- def save_failed(self) -> bool: """Returns True if the most recent save failed for any reason""" return self.has_unsaved_changes() # ---------------------------------------------------------------------- async def __show_prompt_to_save(self, job: Callback): """Show a prompt requesting to save the current file. If yes then save it and run the job. If no then just run the job. If cancel then do nothing """ ogt.dbg_ui(f"Showing save prompt with callback {job}") Prompt( title="Save OGN File", text="Would you like to save this file?", ok_button_text="Save", middle_button_text="Don't Save", cancel_button_text="Cancel", ok_button_fn=lambda: self.save(on_save_done=lambda *args: job()), middle_button_fn=lambda: job() if job is not None else None, ).show() # ---------------------------------------------------------------------- def __prompt_if_unsaved_data(self, data_is_dirty: bool, job: Callback): """Run a job if there is no unsaved OGN data, otherwise first prompt to save the current data.""" ogt.dbg_ui("Checking for unsaved data") if data_is_dirty: asyncio.ensure_future(self.__show_prompt_to_save(job)) elif job is not None: job() # ---------------------------------------------------------------------- def __on_click_open(self, file_name: str, directory_path: str, on_open_done: OptionalCallback): """Callback executed when the user selects a file in the open file dialog on_open_done() will be executed after the file is opened, if not None """ ogn_path = os.path.join(directory_path, file_name) ogt.dbg_ui(f"Trying to open the file {ogn_path}") def open_from_ogn(): """Open the OGN file into the currently managed model. Posts an informational dialog if the file could not be opened. """ ogt.dbg_ui(f"Opening data from OGN file {ogn_path} - {callback_name(on_open_done)}") try: self.__controller.set_ogn_data(ogn_path) (self.__current_directory, self.__current_file) = os.path.split(ogn_path) if on_open_done is not None: on_open_done() except Exception as error: # noqa: PLW0703 Prompt("Open Error", f"File open failed: {error}", "Okay").show() if self.has_unsaved_changes(): ogt.dbg_ui("...file is dirty, prompting to overwrite") asyncio.ensure_future(self.__show_prompt_to_save(open_from_ogn)) else: open_from_ogn() self.__open_file_dialog.hide() # ---------------------------------------------------------------------- def open(self, on_open_done: OptionalCallback = None): # noqa: A003 """Bring up a file picker to choose a USD file to open. If current data is dirty, a prompt will show to let you save it. Args: on_open_done: Function to call after the open is finished """ ogt.dbg_ui(f"Opening up file open dialog - {callback_name(on_open_done)}") def __on_click_cancel(file_name: str, directory_name: str): """Callback executed when the user cancels the file open dialog""" ogt.dbg_ui("Clicked cancel in file open") self.__open_file_dialog.hide() if self.__open_file_dialog is None: self.__open_file_dialog = FilePickerDialog( "Open .ogn File", allow_multi_selection=False, apply_button_label="Open", click_apply_handler=lambda filename, dirname: self.__on_click_open(filename, dirname, on_open_done), click_cancel_handler=__on_click_cancel, file_extension_options=OGN_FILTERS, item_filter_fn=self.__on_filter_ogn_files, error_handler=self.__on_file_dialog_error, ) self.__open_file_dialog.refresh_current_directory() self.__open_file_dialog.show(path=self.__current_directory) # ---------------------------------------------------------------------- def reset_ogn_data(self): """Initialize the OGN content to an empty node.""" ogt.dbg_ui("Resetting the content") self.__controller.set_ogn_data(None) self.__current_file = None # ---------------------------------------------------------------------- def new(self): """Initialize the OGN content to an empty node. If current data is dirty, a prompt will show to let you save it. """ ogt.dbg_ui("Creating a new node") self.__prompt_if_unsaved_data(self.has_unsaved_changes(), self.reset_ogn_data) # ---------------------------------------------------------------------- def __save_as_ogn(self, new_ogn_path: str, on_save_done: OptionalCallback): """Save the OGN content into the named file. Posts an informational dialog if the file could not be saved. """ ogt.dbg_ui(f"Saving OGN to file {new_ogn_path} - {callback_name(on_save_done)}") try: with open(new_ogn_path, "w", encoding="utf-8") as json_fd: json.dump(self.__controller.ogn_data, json_fd, indent=4) (self.__current_directory, self.__current_file) = os.path.split(new_ogn_path) self.__controller.set_clean() self.__unsaved_changes = False if on_save_done is not None: on_save_done() except Exception as error: # noqa: PLW0703 Prompt("Save Error", f"File save failed: {error}", "Okay").show() # ---------------------------------------------------------------------- def __on_click_save(self, file_name: str, directory_path: str, on_save_done: OptionalCallback): """Save the file, prompting to overwrite if it already exists. Args: on_save_done: Function to call after save is complete (None if nothing to do) """ (_, ext) = os.path.splitext(file_name) if ext != ".ogn": file_name = f"{file_name}.ogn" new_ogn_path = os.path.join(directory_path, file_name) ogt.dbg_ui(f"Saving OGN, checking existence first, to file {new_ogn_path} - {callback_name(on_save_done)}") if os.path.exists(new_ogn_path): Prompt( title="Overwrite OGN File", text=f"File {os.path.basename(new_ogn_path)} already exists, do you want to overwrite it?", ok_button_text="Yes", cancel_button_text="No", ok_button_fn=lambda: self.__save_as_ogn(new_ogn_path, on_save_done), ).show() else: self.__save_as_ogn(new_ogn_path, on_save_done) self.__save_file_dialog.hide() # ---------------------------------------------------------------------- def save(self, on_save_done: OptionalCallback = None, open_save_dialog: bool = False): """Save currently opened OGN data to file. Will call Save As for a newly created file""" ogt.dbg_ui(f"Opening up file save dialog - {callback_name(on_save_done)}") # If there are no unsaved changes then confirm the file exists to ensure the file system did not delete it # and if so then skip the save if not self.has_unsaved_changes and os.path.isfile(self.ogn_path): ogt.dbg_ui("... file is clean, no need to save") return def __on_click_cancel(file_name: str, directory_name: str): """Callback executed when the user cancels the file save dialog""" ogt.dbg_ui("Clicked cancel in file save") self.__save_file_dialog.hide() if self.ogn_path is None or open_save_dialog: if not os.path.isdir(self.__current_directory): raise ValueError("Populate extension before saving file") ogt.dbg_ui("Opening up the save file dialog") if self.__save_file_dialog is None: self.__save_file_dialog = FilePickerDialog( "Save .ogn File", allow_multi_selection=False, apply_button_label="Save", click_apply_handler=lambda filename, dirname: self.__on_click_save(filename, dirname, on_save_done), click_cancel_handler=__on_click_cancel, item_filter_fn=self.__on_filter_ogn_files, error_handler=self.__on_file_dialog_error, file_extension_options=OGN_FILTERS, current_file_extension=".ogn", ) self.__save_file_dialog.refresh_current_directory() self.__save_file_dialog.show(path=self.__current_directory) else: ogt.dbg_ui("Saving the file under the existing name") self.__save_as_ogn(self.ogn_path, on_save_done)
15,171
Python
45.82716
120
0.541494
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/ogn_editor_utils.py
""" Common functions used by all of the OmniGraph Node Editor implementation classes Exports: Callback callback_name ComboBoxOptions DestructibleButton FileCallback FileCallbackNested find_unique_name ghost_int ghost_text OptionalCallback PatternedStringModel set_widget_visible show_wip SubscriptionManager """ import asyncio import os from typing import Callable, Dict, Optional, Tuple import omni.graph.tools as ogt from carb import log_warn from omni import ui from omni.kit.app import get_app from omni.kit.ui import get_custom_glyph_code from ..style import STYLE_GHOST, name_value_label # noqa: PLE0402 # Imports from other places that look like they are coming from here from ..utils import DestructibleButton # noqa # ====================================================================== OGN_WIP = os.getenv("OGN_WIP") def show_wip() -> bool: """Returns True if work in progress should be visible""" return OGN_WIP # ====================================================================== # Glyph paths GLYPH_EXCLAMATION = f'{get_custom_glyph_code("${glyphs}/exclamation.svg")}' # ====================================================================== # Default values for initializing new data OGN_NEW_NODE_NAME = "NewNode" OGN_DEFAULT_CONTENT = {OGN_NEW_NODE_NAME: {"version": 1, "description": "", "language": "Python"}} # ====================================================================== # Typing information for callback functions Callback = Callable[[], None] OptionalCallback = [None, Callable[[], None]] FileCallback = [None, Callable[[str], None]] FileCallbackNested = [None, Callable[[str, Optional[Callable]], None]] # ====================================================================== def callback_name(job: Callable): """Return a string representing the possible None callback function""" return "No callback" if job is None else f"callback - {job.__name__}" # ====================================================================== def find_unique_name(base_name: str, names_taken: Dict): """Returns the base_name with a suffix that guarantees it does not appear as a key in the names_taken find_unique_name("fred", ["fred": "flintsone", "fred0": "mercury"]) -> "fred1" """ if base_name not in names_taken: return base_name index = 0 while f"{base_name}{index}" in names_taken: index += 1 return f"{base_name}{index}" # ===================================================================== def set_widget_visible(widget: ui.Widget, visible) -> bool: """ Utility for using in lambdas, changes the visibility of a widget. Returns True so that it can be combined with other functions in a lambda: lambda m: set_widget_visible(widget, not m.as_string) and callback(m.as_string) """ widget.visible = visible return True # ====================================================================== class GhostedWidgetInfo: """Container for the UI information pertaining to text with ghosted prompt text Attributes: begin_subscription: Subscription for callback when editing begins end_subscription: Subscription for callback when editing ends model: Main editing model prompt_widget: Widget that is layered above the main one to show the ghosted prompt text widget: Main editing widget """ def __init__(self): """Initialize the members""" self.begin_subscription = None self.end_subscription = None self.widget = None self.prompt_widget = None self.model = None # ====================================================================== def ghost_text( label: str, tooltip: str, widget_id: str, initial_value: str, ghosted_text: str, change_callback: Optional[Callable], validation: Optional[Tuple[Callable, str]] = None, ) -> GhostedWidgetInfo: """ Creates a Label/StringField value entry pair with ghost text to prompt the user when the field is empty. Args: label: Text for the label of the field tooltip: Tooltip for the label widget_id: Base ID for the string entry widget (append "_prompt" for the ghost prompt overlay) initial_value: Initial value for the string field ghosted_text: Text to appear when the string is empty change_callback: Function to call when the string changes validation: Optional function and string pattern used to check if the entered string is valid (no validation if None) Returns: 4-tuple (subscription, model, widget, prompt_widget) subscription: Subscription object for active callback model: The model managing the editable string widget: The widget containing the editable string prompt_widget: The widget containing the overlay shown when the string is empty """ prompt_widget_id = f"{widget_id}_prompt" name_value_label(label, tooltip) ghost_info = GhostedWidgetInfo() if validation is None: ghost_info.model = ui.SimpleStringModel(initial_value) else: ghost_info.model = ValidatedStringModel(initial_value, validation[0], validation[1]) def ghost_edit_begin(model, label_widget): """Called to hide the prompt label""" label_widget.visible = False def ghost_edit_end(model, label_widget, callback): """Called to show the prompt label and process the field edit""" if not model.as_string: label_widget.visible = True if callback is not None: callback(model.as_string) with ui.ZStack(height=0): ghost_info.widget = ui.StringField(model=ghost_info.model, name=widget_id, tooltip=tooltip) # Add a ghosted input prompt that only shows up when the attribute name is empty ghost_info.prompt_widget = ui.Label( ghosted_text, name=prompt_widget_id, style_type_name_override=STYLE_GHOST, visible=not initial_value ) ghost_info.begin_subscription = ghost_info.model.subscribe_begin_edit_fn( lambda model, widget=ghost_info.prompt_widget: ghost_edit_begin(model, widget) ) ghost_info.end_subscription = ghost_info.model.subscribe_end_edit_fn( lambda model: ghost_edit_end(model, ghost_info.prompt_widget, change_callback) ) if label: ghost_info.prompt_widget.visible = False return ghost_info # ====================================================================== def ghost_int( label: str, tooltip: str, widget_id: str, initial_value: int, ghosted_text: str, change_callback: Optional[Callable] ) -> GhostedWidgetInfo: """ Creates a Label/IntField value entry pair with ghost text to prompt the user when the field is empty. Args: label: Text for the label of the field tooltip: Tooltip for the label widget_id: Base ID for the integer entry widget (append "_prompt" for the ghost prompt overlay) initial_value: Initial value for the integer field ghosted_text: Text to appear when the integer is empty change_callback: Function to call when the integer changes Returns: 4-tuple (subscription, model, widget, prompt_widget) subscription: Subscription object for active callback model: The model managing the editable integer widget: The widget containing the editable integer prompt_widget: The widget containing the overlay shown when the integer is empty """ ghost_info = GhostedWidgetInfo() prompt_widget_id = f"{widget_id}_prompt" name_value_label(label, tooltip) ghost_info.model = ui.SimpleIntModel(initial_value) def ghost_edit_begin(model, label_widget): """Called to hide the prompt label""" label_widget.visible = False def ghost_edit_end(model, label_widget, callback): """Called to show the prompt label and process the field edit""" if not model.as_string: label_widget.visible = True if callback is not None: callback(model.as_int) with ui.ZStack(height=0): ghost_info.widget = ui.IntField(model=ghost_info.model, name=widget_id, tooltip=tooltip) # Add a ghosted input prompt that only shows up when the value is empty ghost_info.prompt_widget = ui.Label( ghosted_text, name=prompt_widget_id, style_type_name_override=STYLE_GHOST, visible=not initial_value ) ghost_info.begin_subscription = ghost_info.model.subscribe_begin_edit_fn( lambda model, widget=ghost_info.prompt_widget: ghost_edit_begin(model, widget) ) ghost_info.end_subscription = ghost_info.model.subscribe_end_edit_fn( lambda model: ghost_edit_end(model, ghost_info.prompt_widget, change_callback) ) return ghost_info # ====================================================================== class ComboBoxOptions(ui.AbstractItem): """Class that provides a conversion from simple text to a StringModel to use in ComboBox options""" def __init__(self, text: str): """Initialize the internal model to the string""" super().__init__() self.model = ui.SimpleStringModel(text) def destroy(self): """Called when the combobox option is being destroyed""" ogt.dbg_ui(f"destroy::{self.__class__.__name__}") self.model = None # ====================================================================== class SubscriptionManager: """Class that manages an AbstractValueModel subscription callback, allowing enabling and disabling. One potential use is to temporarily disable subscriptions when a change is being made in a callback that might recursively trigger that same callback. class ChangeMe: def __init__(self, model): self.model = model self.mgr = SubscriptionManager(model, SubscriptionManager.CHANGE, on_change) def on_change(self, new_value): if new_value.as_int > 5: # Resetting the value to clamp it to a range would recursively trigger this callback so shut it off self.mgr.disable() self.model.set_value(5) self.mgr.enable() """ # Enumeration of the different types of subscriptions available CHANGE = 0 BEGIN_EDIT = 1 END_EDIT = 2 # Model functions corresponding to the above subscription types FUNCTION_NAMES = ["subscribe_value_changed_fn", "subscribe_begin_edit_fn", "subscribe_end_edit_fn"] # ---------------------------------------------------------------------- def __init__(self, model: ui.AbstractValueModel, subscription_type: int, callback: callable): """Create an initial subscription to a model change""" ogt.dbg_ui(f"Create subscription manager on {model} of type {subscription_type} for callback {callback}") self.__model = model self.__subscription_type = subscription_type self.__callback = callback self.__subscription = None # On creation the subscription will be activated self.enable() # ---------------------------------------------------------------------- async def __do_enable(self): """Turn on the subscription of the given type""" ogt.dbg_ui("__do_enable") await get_app().next_update_async() try: self.__subscription = getattr(self.__model, self.FUNCTION_NAMES[self.__subscription_type])(self.__callback) assert self.__subscription except (KeyError, AttributeError, TypeError) as error: log_warn(f"Failed to create subscription type {self.__subscription_type} on {self.__model} - {error}") # ---------------------------------------------------------------------- def enable(self): """Turn on the subscription of the given type, syncing first to make sure no pending updates exist""" ogt.dbg_ui("Enable") asyncio.ensure_future(self.__do_enable()) # ---------------------------------------------------------------------- def disable(self): """Turn off the subscription of the given type""" ogt.dbg_ui("Disable") self.__subscription = None # ====================================================================== class ValidatedStringModel(ui.AbstractValueModel): """String model that insists the values entered match a certain pattern""" def __init__(self, initial_value: str, verify: Callable[[str], bool], explanation: str): """Initialize the legal values of the string, and human-readable explanation of the pattern Args: initial_value: Initial value of the string, nulled out if it is not legal verify: Function to call to check for validity of the string explanation: Human readable explanation of the RegEx """ super().__init__() self.__verify = verify self.__explanation = explanation self.__value = "" self.__initial_value = None self.set_value(initial_value) def get_value_as_string(self): """Get the internal value that has been filtered""" ogt.dbg_ui(f"Get value as string = {self.__value}") return self.__value def set_value(self, new_value): """Implementation of the value setting that filters new values based on the pattern Args: new_value: Potential new value of the string """ self.__value = str(new_value) self._value_changed() def begin_edit(self): """Called when the user starts editing.""" self.__initial_value = self.get_value_as_string() def end_edit(self): """Called when the user finishes editing.""" new_value = self.get_value_as_string() if not self.__verify(new_value): self.__value = self.__initial_value self._value_changed() log_warn(f"'{new_value}' is not legal - {self.__explanation.format(new_value)}")
14,153
Python
38.426184
120
0.603688
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/metaclass.py
from .._impl.metaclass import * # noqa: F401,PLW0401,PLW0614
62
Python
30.499985
61
0.725806
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/stage_picker_dialog.py
from .._impl.stage_picker_dialog import * # noqa: F401,PLW0401,PLW0614
72
Python
35.499982
71
0.736111
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_attribute_base.py
from .._impl.omnigraph_attribute_base import * # noqa: F401,PLW0401,PLW0614
77
Python
37.999981
76
0.753247
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/style.py
from .._impl.style import * # noqa: F401,PLW0401,PLW0614
58
Python
28.499986
57
0.706897
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/extension.py
from .._impl.extension import * # noqa: F401,PLW0401,PLW0614
62
Python
30.499985
61
0.725806
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/compute_node_widget.py
from .._impl.compute_node_widget import * # noqa: F401,PLW0401,PLW0614
72
Python
35.499982
71
0.736111
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/__init__.py
"""This module is deprecated. Use 'import omni.graph.ui as ogu' to access the OmniGraph UI API""" import omni.graph.tools as ogt ogt.DeprecatedImport("Import 'omni.graph.ui as ogu' to access the OmniGraph UI API")
215
Python
42.199992
97
0.75814
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_settings_editor.py
from .._impl.omnigraph_settings_editor import * # noqa: F401,PLW0401,PLW0614
78
Python
38.499981
77
0.75641
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_graph_selector.py
from .._impl.omnigraph_graph_selector import * # noqa: F401,PLW0401,PLW0614
77
Python
37.999981
76
0.753247
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/utils.py
from .._impl.utils import * # noqa: F401,PLW0401,PLW0614
58
Python
28.499986
57
0.706897
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/menu.py
from .._impl.menu import * # noqa: F401,PLW0401,PLW0614
57
Python
27.999986
56
0.701754
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/properties_widget.py
from .._impl.properties_widget import * # noqa: F401,PLW0401,PLW0614
70
Python
34.499983
69
0.742857
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_attribute_models.py
from .._impl.omnigraph_attribute_models import * # noqa: F401,PLW0401,PLW0614
79
Python
38.999981
78
0.759494
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/graph_variable_custom_layout.py
from .._impl.graph_variable_custom_layout import * # noqa: F401,PLW0401,PLW0614
81
Python
39.99998
80
0.753086
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_attribute_builder.py
from .._impl.omnigraph_attribute_builder import * # noqa: F401,PLW0401,PLW0614
80
Python
39.49998
79
0.7625
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/token_array_edit_widget.py
from .._impl.token_array_edit_widget import * # noqa: F401,PLW0401,PLW0614
76
Python
37.499981
75
0.736842
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_migrate_data.py
from ..._impl.omnigraph_toolkit.toolkit_migrate_data import * # noqa: F401,PLW0401,PLW0614
92
Python
45.499977
91
0.76087
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_window.py
from ..._impl.omnigraph_toolkit.toolkit_window import * # noqa: F401,PLW0401,PLW0614
86
Python
42.499979
85
0.755814
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/__init__.py
from ..._impl.omnigraph_toolkit.__init__ import * # noqa: F401,PLW0401,PLW0614
80
Python
39.49998
79
0.7
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_output.py
from ..._impl.omnigraph_toolkit.toolkit_frame_output import * # noqa: F401,PLW0401,PLW0614
92
Python
45.499977
91
0.76087
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_inspection.py
from ..._impl.omnigraph_toolkit.toolkit_frame_inspection import * # noqa: F401,PLW0401,PLW0614
96
Python
47.499976
95
0.770833
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_scene.py
from ..._impl.omnigraph_toolkit.toolkit_frame_scene import * # noqa: F401,PLW0401,PLW0614
91
Python
44.999978
90
0.758242
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_memory.py
from ..._impl.omnigraph_toolkit.toolkit_frame_memory import * # noqa: F401,PLW0401,PLW0614
92
Python
45.499977
91
0.76087
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/metadata_manager.py
from ..._impl.omnigraph_node_description_editor.metadata_manager import * # noqa
82
Python
40.49998
81
0.768293
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_controller.py
from ..._impl.omnigraph_node_description_editor.main_controller import * # noqa
81
Python
39.99998
80
0.765432
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/change_management.py
from ..._impl.omnigraph_node_description_editor.change_management import * # noqa
83
Python
40.99998
82
0.771084
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_list_manager.py
from ..._impl.omnigraph_node_description_editor.attribute_list_manager import * # noqa
88
Python
43.499978
87
0.772727
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/memory_type_manager.py
from ..._impl.omnigraph_node_description_editor.memory_type_manager import * # noqa
85
Python
41.999979
84
0.764706
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/node_language_manager.py
from ..._impl.omnigraph_node_description_editor.node_language_manager import * # noqa
87
Python
42.999979
86
0.770115
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_model.py
from ..._impl.omnigraph_node_description_editor.main_model import * # noqa
76
Python
37.499981
75
0.75
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/tests_data_manager.py
from ..._impl.omnigraph_node_description_editor.tests_data_manager import * # noqa
84
Python
41.499979
83
0.761905
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/node_properties.py
from ..._impl.omnigraph_node_description_editor.node_properties import * # noqa
81
Python
39.99998
80
0.765432
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_properties.py
from ..._impl.omnigraph_node_description_editor.attribute_properties import * # noqa
86
Python
42.499979
85
0.77907
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_union_type_adder_manager.py
from ..._impl.omnigraph_node_description_editor.attribute_union_type_adder_manager import * # noqa
100
Python
49.499975
99
0.78
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/extension_info_manager.py
from ..._impl.omnigraph_node_description_editor.extension_info_manager import * # noqa
88
Python
43.499978
87
0.772727
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_editor.py
from ..._impl.omnigraph_node_description_editor.main_editor import * # noqa
77
Python
37.999981
76
0.753247
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/test_configurations.py
from ..._impl.omnigraph_node_description_editor.test_configurations import * # noqa
85
Python
41.999979
84
0.776471
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_generator.py
from ..._impl.omnigraph_node_description_editor.main_generator import * # noqa
80
Python
39.49998
79
0.7625
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_base_type_manager.py
from ..._impl.omnigraph_node_description_editor.attribute_base_type_manager import * # noqa
93
Python
45.999977
92
0.774194
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_tuple_count_manager.py
from ..._impl.omnigraph_node_description_editor.attribute_tuple_count_manager import * # noqa
95
Python
46.999977
94
0.778947
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/file_manager.py
from ..._impl.omnigraph_node_description_editor.file_manager import * # noqa
78
Python
38.499981
77
0.75641
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/ogn_editor_utils.py
from ..._impl.omnigraph_node_description_editor.ogn_editor_utils import * # noqa
82
Python
40.49998
81
0.756098
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.ui as ogu from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphUiApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests", "omni"] async def test_api(self): _check_module_api_consistency(ogu, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(ogu.tests, is_test_module=True) # noqa: PLW0212 async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents( # noqa: PLW0212 ogu, [ "add_create_menu_type", "build_port_type_convert_menu", "ComputeNodeWidget", "find_prop", "GraphVariableCustomLayout", "OmniGraphAttributeModel", "OmniGraphTfTokenAttributeModel", "OmniGraphBase", "OmniGraphPropertiesWidgetBuilder", "PrimAttributeCustomLayoutBase", "PrimPathCustomLayoutBase", "RandomNodeCustomLayoutBase", "ReadPrimsCustomLayoutBase", "remove_create_menu_type", "SETTING_PAGE_NAME", ], self._UNPUBLISHED, only_expected_allowed=True, ) _check_public_api_contents(ogu.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
1,638
Python
39.974999
107
0.567155
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_widgets.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 pathlib from typing import List import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui from omni.kit import ui_test from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading from omni.ui.tests.test_base import OmniUiTest class TestOmniWidgets(OmniUiTest): """ Test class for testing omnigraph related widgets """ async def setUp(self): await super().setUp() usd_path = pathlib.Path(get_test_data_path(__name__)) self._golden_img_dir = usd_path.absolute().joinpath("golden_img").absolute() self._usd_path = usd_path.absolute() import omni.kit.window.property as p self._w = p.get_window() async def tearDown(self): await super().tearDown() async def __widget_image_test( self, file_path: str, prims_to_select: List[str], golden_img_name: str, width=450, height=500, ): """Helper to do generate a widget comparison test on a property panel""" usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, # noqa: PLE0211,PLW0212 width=width, height=height, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) test_file_path = self._usd_path.joinpath(file_path).absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(prims_to_select, True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name, threshold=0.15) # Close the stage to avoid dangling references to the graph. (OM-84680) await omni.usd.get_context().close_stage_async() async def test_compound_node_type_widget_ui(self): """Tests the compound node type property pane matches the expected image""" await self.__widget_image_test( file_path="compound_node_test.usda", prims_to_select=["/World/Compounds/TestCompound"], golden_img_name="test_compound_widget.png", height=600, ) async def test_graph_with_variables_widget(self): """Tests the variable property pane on a graph prim""" await self.__widget_image_test( file_path="test_variables.usda", prims_to_select=["/World/ActionGraph"], golden_img_name="test_graph_variables.png", height=300, ) async def test_instance_with_variables_widget(self): """Tests the variable property pane on an instance prim""" await self.__widget_image_test( file_path="test_variables.usda", prims_to_select=["/World/Instance"], golden_img_name="test_instance_variables.png", height=450, )
3,577
Python
34.78
118
0.649427
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_property_widget.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import tempfile from pathlib import Path import omni.graph.core as og import omni.graph.tools.ogn as ogn import omni.graph.ui._impl.omnigraph_attribute_base as ogab import omni.graph.ui._impl.omnigraph_attribute_models as ogam import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd from omni.kit import ui_test from omni.ui.tests.test_base import OmniUiTest from pxr import Sdf, Usd _MATRIX_DIMENSIONS = {4: 2, 9: 3, 16: 4} # ---------------------------------------------------------------------- class TestOmniGraphWidget(OmniUiTest): """ Tests for OmniGraphBase and associated models in this module, the custom widget for the kit property panel uses these models which are customized for OmniGraphNode prims. """ TEST_GRAPH_PATH = "/World/TestGraph" # Before running each test async def setUp(self): await super().setUp() # Ensure we have a clean stage for the test await omni.usd.get_context().new_stage_async() # Give OG a chance to set up on the first stage update await omni.kit.app.get_app().next_update_async() og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) extension_root_folder = Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) self._golden_img_dir = extension_root_folder.joinpath("data/tests/golden_img") import omni.kit.window.property as p self._w = p.get_window() # After running each test async def tearDown(self): # Close the stage to avoid dangling references to the graph. (OM-84680) await omni.usd.get_context().close_stage_async() await super().tearDown() def __attribute_type_to_name(self, attribute_type: og.Type) -> str: """Converts an attribute type into the canonical attribute name used by the test nodes. The rules are: - prefix of a_ - followed by name of attribute base type - followed by optional _N if the component count N is > 1 - followed by optional '_array' if the type is an array Args: type: OGN attribute type to deconstruct Returns: Canonical attribute name for the attribute with the given type """ attribute_name = f"a_{og.Type(attribute_type.base_type, 1, 0, attribute_type.role).get_ogn_type_name()}" attribute_name = attribute_name.replace("prim", "bundle") if attribute_type.tuple_count > 1: if attribute_type.role in [og.AttributeRole.TRANSFORM, og.AttributeRole.FRAME, og.AttributeRole.MATRIX]: attribute_name += f"_{_MATRIX_DIMENSIONS[attribute_type.tuple_count]}" else: attribute_name += f"_{attribute_type.tuple_count}" array_depth = attribute_type.array_depth while array_depth > 0 and attribute_type.role not in [og.AttributeRole.TEXT, og.AttributeRole.PATH]: attribute_name += "_array" array_depth -= 1 return attribute_name async def test_target_attribute(self): """ Exercise the target-attribute customizations for Property Panel. The related code is in omnigraph_attribute_builder.py and targets.py """ usd_context = omni.usd.get_context() keys = og.Controller.Keys controller = og.Controller() (_, (get_parent_prims,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("GetParentPrims", "omni.graph.nodes.GetParentPrims"), ], }, ) # The OG attribute-base UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # Select the node. usd_context.get_selection().set_selected_prim_paths([get_parent_prims.get_prim_path()], True) # Wait for property panel to converge await ui_test.human_delay(5) # Click the Add-Relationship button attr_name = "inputs:prims" await ui_test.find( f"Property//Frame/**/Button[*].identifier=='sdf_relationship_array_{attr_name}.add_relationships'" ).click() # Wait for dialog to show up await ui_test.human_delay(5) # push the select-graph-target button and wait for dialog to close await ui_test.find("Select Targets//Frame/**/Button[*].identifier=='select_graph_target'").click() await ui_test.human_delay(5) # Resize to fit the property panel, and take a snapshot await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) await ui_test.human_delay(5) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute.png") # ---------------------------------------------------------------------- async def test_target_attribute_browse(self): """ Test the changing an existing selection via the dialog works """ usd_context = omni.usd.get_context() keys = og.Controller.Keys controller = og.Controller() prim_paths = ["/World/Prim"] (_, (read_prims_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadPrims", "omni.graph.nodes.ReadPrimsV2"), ], keys.CREATE_PRIMS: [(prim_path, {}) for prim_path in prim_paths], }, ) attr_name = "inputs:prims" usd_context.get_stage().GetPrimAtPath(read_prims_node.get_prim_path()).GetRelationship(attr_name).AddTarget( prim_paths[0] ) # The OG attribute-base UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # Select the node. usd_context.get_selection().set_selected_prim_paths([read_prims_node.get_prim_path()], True) # Wait for property panel to converge await ui_test.human_delay(5) # Click the Browse button model_index = 0 await ui_test.find( f"Property//Frame/**/Button[*].identifier=='sdf_browse_relationship_{attr_name}[{model_index}]'" ).click() # Wait for dialog to show up await ui_test.human_delay(5) # push the select-graph-target button and wait for dialog to close await ui_test.find("Select Targets//Frame/**/Button[*].identifier=='select_graph_target'").click() await ui_test.human_delay(5) # Resize to fit the property panel, and take a snapshot await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) await ui_test.human_delay(5) try: await self.capture_and_compare( golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute_browse.png" ) # Now edit the path to verify it displays as expected test_path = f"{og.INSTANCING_GRAPH_TARGET_PATH}/foo" # FIXME: This input call doesn't work - set with USD instead # await ui_test.find( # f"Property//Frame/**/StringField[*].identifier=='sdf_relationship_{attr_name}[{model_index}]'" # ).input(test_path) usd_context.get_stage().GetPrimAtPath(read_prims_node.get_prim_path()).GetRelationship( attr_name ).SetTargets([Sdf.Path(f"{read_prims_node.get_prim_path()}/{test_path}")]) await ui_test.human_delay(5) # Check the USD path has the token after the prim path, before the relative path self.assertEqual( usd_context.get_stage() .GetPrimAtPath(read_prims_node.get_prim_path()) .GetRelationship(attr_name) .GetTargets()[0], Sdf.Path(f"{read_prims_node.get_prim_path()}/{test_path}"), ) # Check that the composed path from OG is relative to the graph path self.assertEqual( str(og.Controller.get(f"{read_prims_node.get_prim_path()}.{attr_name}")[0]), f"{self.TEST_GRAPH_PATH}/foo", ) # Verify the widget display await self.capture_and_compare( golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute_edit.png" ) finally: await self.finalize_test_no_image() # ---------------------------------------------------------------------- async def test_prim_node_template(self): """ Tests the prim node template under different variations of selected prims to validate the the user does not get into a state where the attribute name cannot be edited """ usd_context = omni.usd.get_context() keys = og.Controller.Keys controller = og.Controller() (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadPrim_Path_ValidTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Path_InvalidTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Path_Connected", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Prim_ValidTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Prim_InvalidTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Prim_Connected", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Prim_OGTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ConstPrims", "omni.graph.nodes.ConstantPrims"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ], keys.CONNECT: [ ("ConstToken.inputs:value", "ReadPrim_Path_Connected.inputs:primPath"), ("ConstPrims.inputs:value", "ReadPrim_Prim_Connected.inputs:prim"), ], keys.SET_VALUES: [ ("ConstToken.inputs:value", "/World/Target"), ("ReadPrim_Path_ValidTarget.inputs:usePath", True), ("ReadPrim_Path_ValidTarget.inputs:primPath", "/World/Target"), ("ReadPrim_Path_ValidTarget.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Path_InvalidTarget.inputs:usePath", True), ("ReadPrim_Path_InvalidTarget.inputs:primPath", "/World/MissingTarget"), ("ReadPrim_Path_InvalidTarget.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Path_Connected.inputs:usePath", True), ("ReadPrim_Path_Connected.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Prim_ValidTarget.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Prim_InvalidTarget.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Prim_Connected.inputs:name", "size"), ("ReadPrim_Prim_OGTarget.inputs:name", "fileFormatVersion"), ], keys.CREATE_PRIMS: [ ("/World/Target", "Xform"), ("/World/Cube", "Cube"), ("/World/MissingTarget", "Xform"), ], }, ) # Change the pipeline stage to On demand to prevent the graph from running and producing errors og.cmds.ChangePipelineStage(graph=graph, new_pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND) # The OG attribute-base UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # add relationships to all graph_path = self.TEST_GRAPH_PATH stage = omni.usd.get_context().get_stage() rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_ValidTarget.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Target") rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_OGTarget.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=og.INSTANCING_GRAPH_TARGET_PATH) rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_InvalidTarget.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/MissingTarget") rel = stage.GetPropertyAtPath(f"{graph_path}/ConstPrims.inputs:value") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Target") # avoids an error by removing the invalid prim after the graph is created omni.kit.commands.execute("DeletePrims", paths=["/World/MissingTarget"]) # Go through all the ReadPrim variations and validate that the image is expected. # In the case of a valid target the widget for the attribute should be a dropdown # Otherwise it should be a text field for node in nodes: node_name = node.get_prim_path().split("/")[-1] if not node_name.startswith("ReadPrim"): continue with self.subTest(node_name=node_name): test_img_name = f"test_{node_name.lower()}.png" # Select the node. usd_context.get_selection().set_selected_prim_paths([node.get_prim_path()], True) # Wait for property panel to converge await ui_test.human_delay(5) # Resize to fit the property panel, and take a snapshot await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=test_img_name) # ---------------------------------------------------------------------- async def test_extended_attributes(self): """ Exercise the OG properties widget with extended attributes """ usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) keys = og.Controller.Keys controller = og.Controller() # OGN Types that we will test resolving the inputs:value to supported_types = [ "half", "timecode", "half[]", "timecode[]", "double[2]", "double[3]", "double[4]", "double[2][]", "double[3][]", "double[4][]", "float[2]", "float[3]", "float[4]", "float[2][]", "float[3][]", "float[4][]", "half[2]", "half[3]", "half[4]", "half[2][]", "half[3][]", "half[4][]", "int[2]", "int[3]", "int[4]", "int[2][]", "int[3][]", "int[4][]", "matrixd[2]", "matrixd[3]", "matrixd[4]", "matrixd[2][]", "matrixd[3][]", "matrixd[4][]", "double", "double[]", "frame[4]", "frame[4][]", "quatd[4]", "quatf[4]", "quath[4]", "quatd[4][]", "quatf[4][]", "quath[4][]", "colord[3]", "colord[3][]", "colorf[3]", "colorf[3][]", "colorh[3]", "colorh[3][]", "colord[4]", "colord[4][]", "colorf[4]", "colorf[4][]", "colorh[4]", "colorh[4][]", "normald[3]", "normald[3][]", "normalf[3]", "normalf[3][]", "normalh[3]", "normalh[3][]", "pointd[3]", "pointd[3][]", "pointf[3]", "pointf[3][]", "pointh[3]", "pointh[3][]", "vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]", "texcoordd[2]", "texcoordd[2][]", "texcoordf[2]", "texcoordf[2][]", "texcoordh[2]", "texcoordh[2][]", "texcoordd[3]", "texcoordd[3][]", "texcoordf[3]", "texcoordf[3][]", "texcoordh[3]", "texcoordh[3][]", "string", "token[]", "token", ] attribute_names = [ self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name)) for type_name in supported_types ] expected_values = [ ogn.get_attribute_manager_type(type_name).sample_values()[0:2] for type_name in supported_types ] (graph, (_, write_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_PRIMS: [ ( "/World/Prim", { attrib_name: (usd_type, expected_value[0]) for attrib_name, usd_type, expected_value in zip( attribute_names, supported_types, expected_values ) }, ) ], keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Write", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Write.inputs:execIn"), ], keys.SET_VALUES: [ ("Write.inputs:name", "acc"), ("Write.inputs:primPath", "/World/Prim"), ("Write.inputs:usePath", True), ], }, ) await controller.evaluate(graph) # Select the prim. usd_context.get_selection().set_selected_prim_paths([write_node.get_prim_path()], True) # The UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # Test for attrib types that use OmniGraphAttributeValueModel async def test_numeric(name, value1, value2): controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]}) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(2) for base in ogab.OmniGraphBase._instances: # noqa: PLW0212 if base._object_paths[0].name == "inputs:value" and ( # noqa: PLW0212 isinstance(base, (ogam.OmniGraphGfVecAttributeSingleChannelModel, ogam.OmniGraphAttributeModel)) ): base.begin_edit() base.set_value(value1) await ui_test.human_delay(1) base.set_value(value2) await ui_test.human_delay(1) base.end_edit() await ui_test.human_delay(1) break # Test for attrib types that use ui.AbstractItemModel async def test_item(name, value1, value2): controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]}) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(2) for base in ogab.OmniGraphBase._instances: # noqa: PLW0212 if base._object_paths[0].name == "inputs:value": # noqa: PLW0212 base.begin_edit() base.set_value(value1) await ui_test.human_delay(1) base.set_value(value2) await ui_test.human_delay(1) base.end_edit() await ui_test.human_delay(1) break # Test for read-only array value - just run the code, no need to verify anything async def test_array(name, val): controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]}) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(2) for attrib_name, test_values in zip(attribute_names, expected_values): if attrib_name.endswith("_array"): await test_array(attrib_name, test_values[1]) elif attrib_name in ("string", "token"): await test_item(attrib_name, test_values[1], test_values[0]) else: # The set_value for some types take a component, others take the whole vector/matrix if isinstance(test_values[0], tuple) and not ( attrib_name.startswith("a_matrix") or attrib_name.startswith("a_frame") or attrib_name.startswith("a_quat") ): await test_numeric(attrib_name, test_values[1][0], test_values[0][0]) else: await test_numeric(attrib_name, test_values[1], test_values[0]) # Sanity check the final widget state display await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_extended_attributes.png") async def test_extended_output_attributes(self): """ Exercise the OG properties widget with extended attributes on read nodes """ usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) keys = og.Controller.Keys controller = og.Controller() (graph, (_, read_node, _,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_PRIMS: [(("/World/Prim", {"a_token": ("token", "Ahsoka")}))], keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Read", "omni.graph.nodes.ReadPrimAttribute"), ("Write", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Write.inputs:execIn"), ("Read.outputs:value", "Write.inputs:value"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("Read.inputs:name", "a_token"), ("Read.inputs:primPath", "/World/Prim"), ("Read.inputs:usePath", True), ("Write.inputs:name", "a_token"), ("Write.inputs:primPath", "/World/Prim"), ("Write.inputs:usePath", True), ], }, ) await controller.evaluate(graph) # Select the prim. usd_context.get_selection().set_selected_prim_paths([read_node.get_prim_path()], True) await ui_test.human_delay(5) # The UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # Sanity check the final widget state display await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="test_extended_output_attributes.png" ) async def test_layer_identifier_resolver(self): """ Test layer identifier resolver using WritePrimsV2 node /root.usda /sub/sublayer.usda (as a sublayer of root.usda) The OG graph will be created on /sub/sublayer.usda with layer identifier set to "./sublayer.usda" Then open /root.usda to test the relative path is successfully resolved relative to root.usda instead """ with tempfile.TemporaryDirectory() as tmpdirname: usd_context = omni.usd.get_context() controller = og.Controller() keys = og.Controller.Keys await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) sub_dir = os.path.join(tmpdirname, "sub") sublayer_fn = os.path.join(sub_dir, "sublayer.usda") sublayer = Sdf.Layer.CreateNew(sublayer_fn) sublayer.Save() root_fn = os.path.join(tmpdirname, "root.usda") root_layer = Sdf.Layer.CreateNew(root_fn) root_layer.subLayerPaths.append("./sub/sublayer.usda") root_layer.Save() success, error = await usd_context.open_stage_async(str(root_fn)) self.assertTrue(success, error) stage = usd_context.get_stage() # put the graph on sublayer # only need WritePrimsV2 node for UI tests with Usd.EditContext(stage, sublayer): (_, [write_prims_node], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Write.inputs:layerIdentifier", "./sublayer.usda"), ], }, ) # exit the "with" and switch edit target back to root layer usd_context.get_selection().set_selected_prim_paths([write_prims_node.get_prim_path()], True) await ui_test.human_delay(5) # Check the final widget state display # The "Layer Identifier" section should show "./sub/sublayer.usda" without any "<Invalid Layer>"" tag await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="test_layer_identifier_resolver.png" )
27,911
Python
39.926686
120
0.54294
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_action.py
""" Tests that verify action UI-dependent nodes """ import unittest import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from omni.kit.test.teamcity import is_running_in_teamcity from omni.kit.viewport.utility import get_active_viewport from omni.kit.viewport.utility.camera_state import ViewportCameraState from pxr import Gf # ====================================================================== class TestOmniGraphAction(ogts.OmniGraphTestCase): """Encapsulate simple sanity tests""" # ---------------------------------------------------------------------- @unittest.skipIf(is_running_in_teamcity(), "Crashes on TC / Linux") async def test_camera_nodes(self): """Test camera-related node basic functionality""" keys = og.Controller.Keys controller = og.Controller() viewport_api = get_active_viewport() active_cam = viewport_api.camera_path persp_cam = "/OmniverseKit_Persp" self.assertEqual(active_cam.pathString, persp_cam) (graph, _, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("SetCam", "omni.graph.ui.SetActiveViewportCamera"), ], keys.SET_VALUES: [ ("SetCam.inputs:primPath", "/OmniverseKit_Top"), ], keys.CONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")], }, ) await controller.evaluate() active_cam = viewport_api.camera_path self.assertEqual(active_cam.pathString, "/OmniverseKit_Top") # be nice - set it back viewport_api.camera_path = persp_cam # Tests moving the camera and camera target controller.edit( graph, { keys.DISCONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")], }, ) await controller.evaluate() (graph, (_, _, get_pos, get_target), _, _) = controller.edit( graph, { keys.CREATE_NODES: [ ("SetPos", "omni.graph.ui.SetCameraPosition"), ("SetTarget", "omni.graph.ui.SetCameraTarget"), ("GetPos", "omni.graph.ui.GetCameraPosition"), ("GetTarget", "omni.graph.ui.GetCameraTarget"), ], keys.SET_VALUES: [ ("SetPos.inputs:primPath", persp_cam), ("SetPos.inputs:position", Gf.Vec3d(1.0, 2.0, 3.0)), # Target should be different than position ("SetTarget.inputs:target", Gf.Vec3d(-1.0, -2.0, -3.0)), ("SetTarget.inputs:primPath", persp_cam), ("GetPos.inputs:primPath", persp_cam), ("GetTarget.inputs:primPath", persp_cam), ], keys.CONNECT: [ ("OnTick.outputs:tick", "SetPos.inputs:execIn"), ("SetPos.outputs:execOut", "SetTarget.inputs:execIn"), ], }, ) await controller.evaluate() # XXX: May need to force these calls through legacy_viewport as C++ nodes call through to that interface. camera_state = ViewportCameraState(persp_cam) # , viewport=viewport_api, force_legacy_api=True) x, y, z = camera_state.position_world for a, b in zip([x, y, z], [1.0, 2.0, 3.0]): self.assertAlmostEqual(a, b, places=5) x, y, z = camera_state.target_world for a, b in zip([x, y, z], [-1.0, -2.0, -3.0]): self.assertAlmostEqual(a, b, places=5) # evaluate again, because push-evaluator may not have scheduled the getters after the setters await controller.evaluate() get_pos = og.Controller.get(controller.attribute(("outputs:position", get_pos))) for a, b in zip(get_pos, [1.0, 2.0, 3.0]): self.assertAlmostEqual(a, b, places=5) get_target = og.Controller.get(controller.attribute(("outputs:target", get_target))) for a, b in zip(get_target, [-1.0, -2.0, -3.0]): self.assertAlmostEqual(a, b, places=5) # ---------------------------------------------------------------------- @unittest.skipIf(is_running_in_teamcity(), "Flaky - needs investigation") async def test_on_new_frame(self): """Test OnNewFrame node""" keys = og.Controller.Keys controller = og.Controller() # Check that the NewFrame node is getting updated when frames are being generated (_, (new_frame_node,), _, _) = controller.edit( "/TestGraph", {keys.CREATE_NODES: [("NewFrame", "omni.graph.ui.OnNewFrame")]} ) attr = controller.attribute(("outputs:frameNumber", new_frame_node)) await og.Controller.evaluate() frame_num = og.Controller.get(attr) # Need to tick Kit before evaluation in order to update for _ in range(5): await omni.kit.app.get_app().next_update_async() await og.Controller.evaluate() self.assertLess(frame_num, og.Controller.get(attr))
5,247
Python
43.10084
113
0.545836
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_ui_sanity.py
""" Tests that do basic sanity checks on the OmniGraph UI """ import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools as ogt import omni.kit.test import omni.usd from carb import log_warn from .._impl.menu import MENU_WINDOWS, Menu from .._impl.omnigraph_node_description_editor.main_editor import Editor # Data-driven information to allow creation of all windows without specifics. # This assumes every class has a static get_name() method so that prior existence can be checked, # and a show_window() or show() method which displays the window. # # Dictionary key is the attribute name in the test class under which this window is stored. # Value is a list of [class, args] where: # ui_class: Class type that instantiates the window # args: Arguments to be passed to the window's constructor # ALL_WINDOW_INFO = {"_ogn_editor_window": [Editor, []]} # ====================================================================== class TestOmniGraphUiSanity(ogts.OmniGraphTestCase): """Encapsulate simple sanity tests""" # ---------------------------------------------------------------------- async def test_open_and_close_all_omnigraph_ui(self): """Open and close all of the OmniGraph UI windows as a basic sanity check In order for this test to work all of the UI management classes must support these methods: show(): Build and display the window contents destroy(): Close the window and destroy the window elements And the classes must derive from (metaclass=Singleton) to avoid multiple instantiations """ class AllWindows: """Encapsulate all of the windows to be tested in an object for easier destruction""" def __init__(self): """Open and remember all of the windows (closing first if they were already open)""" # The graph window needs to be passed a graph. graph_path = "/World/TestGraph" og.Controller.edit({"graph_path": graph_path, "evaluator_name": "push"}) for (member, (ui_class, args)) in ALL_WINDOW_INFO.items(): setattr(self, member, ui_class(*args)) async def show_all(self): """Find all of the OmniGraph UI windows and show them""" for (member, (ui_class, _)) in ALL_WINDOW_INFO.items(): window = getattr(self, member) show_fn = getattr(window, "show_window", getattr(window, "show", None)) if show_fn: show_fn() # Wait for an update to ensure the window has been opened await omni.kit.app.get_app().next_update_async() else: log_warn(f"Not testing type {ui_class.__name__} - no show_window() or show() method") def destroy(self): """Destroy the members, which cleanly destroys the windows""" for member in ALL_WINDOW_INFO: ogt.destroy_property(self, member) all_windows = AllWindows() await all_windows.show_all() await omni.kit.app.get_app().next_update_async() all_windows.destroy() all_windows = None # ---------------------------------------------------------------------- async def test_omnigraph_ui_menu(self): """Verify that the menu operations all work""" menu = Menu() for menu_path in MENU_WINDOWS: menu.set_window_state(menu_path, True) await omni.kit.app.get_app().next_update_async() menu.set_window_state(menu_path, False) async def test_omnigraph_ui_node_creation(self): """Check that all of the registered omni.graph.ui nodes can be created without error.""" graph_path = "/World/TestGraph" (graph, *_) = og.Controller.edit({"graph_path": graph_path, "evaluator_name": "push"}) # Add one of every type of omni.graph.ui node to the graph. node_types = [t for t in og.get_registered_nodes() if t.startswith("omni.graph.ui")] prefix_len = len("omni.graph.ui_nodes.") node_names = [name[prefix_len:] for name in node_types] (_, nodes, _, _) = og.Controller.edit( graph, {og.Controller.Keys.CREATE_NODES: list(zip(node_names, node_types))} ) self.assertEqual(len(nodes), len(node_types), "Check that all nodes were created.") for i, node in enumerate(nodes): self.assertEqual( node.get_prim_path(), graph_path + "/" + node_names[i], f"Check node type '{node_types[i]}'" )
4,694
Python
43.292452
109
0.585854
omniverse-code/kit/exts/omni.graph.ui/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.24.2] - 2023-02-06 - Fix for test failure ## [1.24.1] - 2022-12-08 ### Fixed - Make sure variable colour widgets use AbstractItemModel - Fixed tab not working on variable vector fields - Fixed UI update issues with graph variable widgets ## [1.24.0] - 2022-11-10 ### Added - Display initial and runtime values of graph variables ## [1.23.1] - 2022-10-28 ### Fixed - Undo on node attributes ## [1.23.0] - 2022-09-29 ### Changed - Added OmniGraphAttributeModel to public API ## [1.22.0] - 2022-09-27 ### Added - Widget for reporting timing information related to extension processing by OmniGraph ## [1.21.4] - 2022-09-14 ### Added - Instance variable properties remove underlying attribute when reset to default ## [1.21.3] - 2022-09-10 ### Added - Use id paramteter for Viewport picking request so a node will only generate request. ## [1.21.2] - 2022-08-25 ### Fixed - Modified the import path acceptance pattern to adhere to PEP8 guidelines - Fixed hot reload for the editors by correctly destroying menu items - Added FIXME comments recommended in a prior review ### Added - Button for Save-As to support being able to add multiple nodes in a single session ## [1.21.1] - 2022-08-25 ### Changed - Refactored scene frame to be widget-based instead of monolithic ## [1.21.0] - 2022-08-25 ### Added - UI for controlling new setting that turns deprecations into errors ## [1.20.0] - 2022-08-17 ### Added - Toolkit button for dumping out the extension information for OmniGraph users ### Removed - Obsolete migration buttons ### Changed - Refactored toolkit inspection frame to be widget-based instead of monolithic ## [1.19.0] - 2022-08-11 ### Added - ReadWindowSize node - 'widgetPath' inputs to ReadWidgetProperty, WriteWidgetProperty and WriteWidgetStyle nodes. ### Changed - WriteWidgetStyle now reports the full details of style sytax errors. ## [1.18.1] - 2022-08-10 ### Fixed - Applied formatting to all of the Python files ## [1.18.0] - 2022-08-09 ### Changed - Removed unused graph editor modules - Removed omni.kit.widget.graph and omni.kit.widget.fast_search dependencies ## [1.17.1] - 2022-08-06 ### Changed - OmniGraph(API) references changed to 'Visual Scripting' ## [1.17.0] - 2022-08-05 ### Added - Mouse press gestures to picking nodes ## [1.16.4] - 2022-08-05 ### Changed - Fixed bug related to parameter-tagged properties ## [1.16.3] - 2022-08-03 ### Fixed - All of the lint errors reported on the Python files in this extension ## [1.16.2] - 2022-07-28 ### Fixed - Spurious error messages about 'Node compute request is ignored because XXX is not request-driven' ## [1.16.1] - 2022-07-28 ### Changed - Fixes for OG property panel - compute_node_widget no longer flushes prim to FC ## [1.16.0] - 2022-07-25 ### Added - Viewport mouse event nodes for click, press/release, hover, and scroll ### Changed - Behavior of drag and picking nodes to be consistent ## [1.15.3] - 2022-07-22 ### Changed - Moving where custom metadata is set on the usd property so custom templates have access to it ## [1.15.2] - 2022-07-15 ### Added - test_omnigraph_ui_node_creation() ### Fixed - Missing graph context in test_open_and_close_all_omnigraph_ui() ### Changed - Set all of the old Action Graph Window code to be omitted from pyCoverage ## [1.15.1] - 2022-07-13 - OM-55771: File browser button ## [1.15.0] - 2022-07-12 ### Added - OnViewportDragged and ReadViewportDragState nodes ### Changed - OnPicked and ReadPickState, most importantly how OnPicked handles an empty picking event ## [1.14.0] - 2022-07-08 ### Fixed - ReadMouseState not working with display scaling or multiple workspace windows ### Changed - Added 'useRelativeCoordinates' input and 'window' output to ReadMouseState ## [1.13.0] - 2022-07-08 ### Changed - Refactored imports from omni.graph.tools to get the new locations ### Added - Added test for public API consistency ## [1.12.0] - 2022-07-07 ### Changed - Overhaul of SetViewportMode - Changed default viewport for OnPicked/ReadPickState to 'Viewport' - Allow templates in omni.graph.ui to be loaded ## [1.11.0] - 2022-07-04 ### Added - OgnSetViewportMode.widgetPath attribute ### Changed - OgnSetViewportMode does not enable execOut if there's an error ## [1.10.1] - 2022-06-28 ### Changed - Change default viewport for SetViewportMode/OnPicked/ReadPickState to 'Viewport Next' ## [1.10.0] - 2022-06-27 ### Changed - Move ReadMouseState into omni.graph.ui - Make ReadMouseState coords output window-relative ## [1.9.0] - 2022-06-24 ### Added - Added PickingManipulator for prim picking nodes controlled from SetViewportMode - Added OnPicked and ReadPickState nodes for prim picking ## [1.8.5] - 2022-06-17 ### Added - Added instancing ui elements ## [1.8.4] - 2022-06-07 ### Changed - Updated imports to remove explicit imports - Added explicit generator settings ## [1.8.3] - 2022-05-24 ### Added - Remove dependency on Viewport for Camera Get/Set operations - Run tests with omni.hydra.pxr/Storm instead of RTX ## [1.8.2] - 2022-05-23 ### Added - Use omni.kit.viewport.utility for Viewport nodes and testing. ## [1.8.1] - 2022-05-20 ### Fixed - Change cls.default_model_table to correctly set model_cls in _create_color_or_drag_per_channel for vec2d, vec2f, vec2h, and vec2i omnigraph attributes - Infer default values from type for OG attributes when not provided in metadata ## [1.8.0] - 2022-05-05 ### Added - Support for enableLegacyPrimConnections setting, used by DS but deprecated ### Fixed - Tooltips and descriptions for settings that are interdependent ## [1.7.1] - 2022-04-29 ### Changed - Made tests derive from OmniGraphTestCase ## [1.7.0] - 2022-04-26 ### Added - GraphVariableCustomLayout property panel widget moved from omni.graph.instancing ## [1.6.1] - 2022-04-21 ### Fixed - Some broken and out of date tests. ## [1.6.0] - 2022-04-18 ### Changed - Property Panel widget for OG nodes now reads attribute values from Fabric backing instead of USD. ## [1.5.0] - 2022-03-17 ### Added - Added _add\_create\_menu\_type_ and _remove\_create\_menu\_type_ functions to allow kit-graph extensions to add their corresponding create graph menu item ### Changed - _Menu.create\_graph_ now return the wrapper node, and will no longer pops up windows - _Menu_ no longer creates the three menu items _Create\Visual Sciprting\Action Graph_, _Create\Visual Sciprting\Push Graph_, _Create\Visual Sciprting\Lazy Graph_ at extension start up - Creating a graph now will directly create a graph with default title and open it ## [1.4.4] - 2022-03-11 ### Added - Added glyph icons for menu items _Create/Visual Scripting/_ and items under this submenu - Added Create Graph context menu for viewport and stage windows. ## [1.4.3] - 2022-03-11 ### Fixed - Node is written to backing store when the custom widget is reset to ensure that view is up to date with FC. ## [1.4.2] - 2022-03-07 ### Changed - Add spliter for items in submenu _Window/Visual Scripting_ - Renamed menu item _Create/Graph_ to _Create/Visual Scripting_ - Changed glyph icon for _Create/Visual Scripting_ and added glyph icons for all sub menu items under ## [1.4.1] - 2022-02-22 ### Changed - Change _Window/Utilities/Attribute Connection_, _Window/Visual Scripting/Node Description Editor_ and _Window/Visual Scripting/Toolkit_ into toggle buttons - Added OmniGraph.svg glyph for _Create/Graph_ ## [1.4.0] - 2022-02-16 ### Changes - Decompose the original OmniGraph menu in toolbar into several small menu items under correct categories ## [1.3.0] - 2022-02-10 ### Added - Toolkit access to the setting that uses schema prims in graphs, and a migration tool for same ## [1.2.2] - 2022-01-28 ### Fixed - Potential crash when handling menu or stage changes ## [1.2.1] - 2022-01-21 ### Fixed - ReadPrimAttribute/WritePrimAttribute property panel when usePath is true ## [1.2.0] - 2022-01-06 ### Fixed - Property window was generating exceptions when a property is added to an OG prim. ## [1.1.0] - 2021-12-02 ### Changes - Fixed compute node widget bug with duplicate graphs ## [1.0.2] - 2021-11-24 ### Changes - Fixed compute node widget to work with scoped graphs ## [1.0.1] - 2021-02-10 ### Changes - Updated StyleUI handling ## [1.0.0] - 2021-02-01 ### Initial Version - Started changelog with initial released version of the OmniGraph core
8,560
Markdown
29.575
184
0.725234
omniverse-code/kit/exts/omni.graph.ui/docs/OmniGraphSettingsEditor.rst
.. _omnigraph_settings_editor: OmniGraph Settings Editor ========================= The settings editor provides a method of modifying settings which affect the OmniGraph appearance and evaluation.
199
reStructuredText
27.571425
113
0.718593
omniverse-code/kit/exts/omni.graph.ui/docs/README.md
# OmniGraph UI [omni.graph.ui] OmniGraph is a graph system that provides a compute framework for Omniverse through the use of nodes and graphs. This extension contains some supporting UI-related components and nodes for OmniGraph.
232
Markdown
45.599991
112
0.814655
omniverse-code/kit/exts/omni.graph.ui/docs/index.rst
OmniGraph User Interfaces ######################### .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension**: omni.graph.ui,**Documentation Generated**: |today| While other UI elements allow indirect interaction with the OmniGraph, the ones listed here provide direct manipulation of OmniGraph nodes, attributes, and connections. .. toctree:: :maxdepth: 1 :glob: *
404
reStructuredText
20.315788
99
0.653465
omniverse-code/kit/exts/omni.graph.ui/docs/OmniGraphNodeDescriptionEditor.rst
.. _omnigraph_node_description_editor: OmniGraph Node Description Editor ================================= The node description editor is the user interface to create and edit the code that implements OmniGraph Nodes, as well as providing a method for creating a minimal extension that can be used to bring them into Kit. Follow along with the tutorials `here <https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.graph.core/docs/nodes.html>` to see how this editor can be used to create an OmniGraph node in Python.
531
reStructuredText
47.363632
131
0.749529
omniverse-code/kit/exts/omni.graph.ui/docs/Overview.md
# OmniGraph User Interfaces ```{csv-table} **Extension**: omni.graph.ui,**Documentation Generated**: {sub-ref}`today` ``` While other UI elements allow indirect interaction with the OmniGraph, the ones listed here provide direct manipulation of OmniGraph nodes, attributes, and connections.
292
Markdown
35.624996
99
0.773973
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/aov_actions.py
import omni.kit.actions.core def register_actions(extension_id, cls): action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "AOV Menu Actions" # actions action_registry.register_action( "omni.kit.menu.aov", "create_single_aov", cls._on_create_single_aov, display_name="Create->AOV", description="Create AOV", 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)
598
Python
26.227272
70
0.673913
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/aov.py
import omni.ext import omni.kit.menu.utils import omni.kit.context_menu import omni.kit.commands from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder from pxr import Sdf, Usd, UsdUtils, Gf from .aov_actions import register_actions, deregister_actions class AOVMenuExtension(omni.ext.IExt): def __init__(self): self._aov_menu_list = [] def on_startup(self, ext_id): self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name, AOVMenuExtension) self._register_menu() self._register_context_menu() def on_shutdown(self): deregister_actions(self._ext_name) omni.kit.menu.utils.remove_menu_items(self._aov_menu_list, "Create") self._aov_menu_list = None self._context_menu = None def _register_menu(self): self._aov_menu_list = [ MenuItemDescription(name="AOV", glyph="AOV_dark.svg", appear_after=[MenuItemOrder.LAST], onclick_action=("omni.kit.menu.aov", "create_single_aov")) ] omni.kit.menu.utils.add_menu_items(self._aov_menu_list, "Create") def _register_context_menu(self): menu_dict = { 'glyph': "AOV_dark.svg", 'name': 'AOV', 'show_fn': [], 'onclick_fn': AOVMenuExtension._on_create_single_aov } self._context_menu = omni.kit.context_menu.add_menu(menu_dict, "CREATE") @staticmethod def _create_render_prim(prim_type, prim_path): import omni.usd from omni.kit.widget.layers import LayerUtils stage = omni.usd.get_context().get_stage() session_layer = stage.GetSessionLayer() current_edit_layer = Sdf.Find(LayerUtils.get_edit_target(stage)) swap_edit_targets = current_edit_layer != session_layer rendervar_list = [ ("ldrColor", {"sourceName": "LdrColor"}), ("hdrColor", {"sourceName": "HdrColor"}), ("PtDirectIllumation", {"sourceName": "PtDirectIllumation"}), ("PtGlobalIllumination", {"sourceName": "PtGlobalIllumination"}), ("PtReflections", {"sourceName": "PtReflections"}), ("PtRefractions", {"sourceName": "PtRefractions"}), ("PtSelfIllumination", {"sourceName": "PtSelfIllumination"}), ("PtBackground", {"sourceName": "PtBackground"}), ("PtWorldNormal", {"sourceName": "PtWorldNormal"}), ("PtWorldPos", {"sourceName": "PtWorldPos"}), ("PtZDepth", {"sourceName": "PtZDepth"}), ("PtVolumes", {"sourceName": "PtVolumes"}), ("PtMultiMatte0", {"sourceName": "PtMultiMatte0"}), ("PtMultiMatte1", {"sourceName": "PtMultiMatte1"}), ("PtMultiMatte2", {"sourceName": "PtMultiMatte2"}), ("PtMultiMatte3", {"sourceName": "PtMultiMatte3"}), ("PtMultiMatte4", {"sourceName": "PtMultiMatte4"}), ("PtMultiMatte5", {"sourceName": "PtMultiMatte5"}), ("PtMultiMatte6", {"sourceName": "PtMultiMatte6"}), ("PtMultiMatte7", {"sourceName": "PtMultiMatte7"}), ] ## create prim. /Render is on session layer but need new prims in currrent layer try: if not current_edit_layer.GetPrimAtPath('/Render'): omni.kit.commands.execute("CreatePrim", prim_path="/Render", prim_type="Scope", attributes={}, select_new_prim=False) if not current_edit_layer.GetPrimAtPath('/Render/Vars'): omni.kit.commands.execute("CreatePrim", prim_path="/Render/Vars", prim_type="Scope", attributes={}, select_new_prim=False) omni.kit.commands.execute("CreatePrim", prim_path=prim_path, prim_type="RenderProduct", attributes={}, select_new_prim=False) for var_name, attributes in rendervar_list: if not current_edit_layer.GetPrimAtPath(f"/Render/Vars/{var_name}"): omni.kit.commands.execute("CreatePrim", prim_path=f"/Render/Vars/{var_name}", prim_type="RenderVar", attributes=attributes, select_new_prim=False) if swap_edit_targets: LayerUtils.set_edit_target(stage, session_layer.identifier) # set /Render visible & non-deletable in stage window... render_prim = stage.GetPrimAtPath("/Render") omni.usd.editor.set_hide_in_stage_window(render_prim, False) omni.usd.editor.set_no_delete(render_prim, True) # set /Render/Vars visible & non-deletable in stage window... vars_prim = stage.GetPrimAtPath("/Render/Vars") omni.usd.editor.set_hide_in_stage_window(vars_prim, False) omni.usd.editor.set_no_delete(vars_prim, True) finally: if swap_edit_targets: LayerUtils.set_edit_target(stage, current_edit_layer.identifier) prim = stage.GetPrimAtPath(prim_path) if prim: for var_name, attributes in rendervar_list: omni.kit.commands.execute("AddRelationshipTarget", relationship=prim.GetRelationship('orderedVars'), target=f"/Render/Vars/{var_name}") prim.CreateAttribute("resolution", Sdf.ValueTypeNames.Int2, False).Set(Gf.Vec2i(1280, 720)) @staticmethod def _on_create_single_aov(objects=None): with omni.kit.undo.group(): stage = omni.usd.get_context().get_stage() prim_path = Sdf.Path(omni.usd.get_stage_next_free_path(stage, "/Render/RenderView", False)) AOVMenuExtension._create_render_prim("RenderProduct", prim_path)
5,872
Python
48.352941
166
0.585831
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/__init__.py
from .aov import *
19
Python
8.999996
18
0.68421
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/tests/aov_tests.py
import sys import re import asyncio import unittest import carb import omni.kit.test import omni.ui as ui from omni.kit import ui_test class WindowStub(): """stub window class for use with WidgetRef & """ def undock(_): pass def focus(_): pass window_stub = WindowStub() class TestMenuAOVs(omni.kit.test.AsyncTestCase): async def setUp(self): import omni.kit.material.library # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() await ui_test.human_delay() async def tearDown(self): pass def get_menubar(self) -> ui_test.WidgetRef: from omni.kit.mainwindow import get_main_window window = get_main_window() return ui_test.WidgetRef(widget=window._ui_main_window.main_menu_bar, path="MainWindow//Frame/MenuBar") def find_menu(self, menubar: ui_test.WidgetRef, path: str) -> ui_test.WidgetRef: for widget in menubar.find_all("**/"): if isinstance(widget.widget, ui.Menu) or isinstance(widget.widget, ui.MenuItem): if widget.widget.text.encode('ascii', 'ignore').decode().strip() == path: return ui_test.WidgetRef(widget.widget, path="xxx", window=window_stub) return None async def test_aov_menus(self): from omni.kit.menu.aov import AOVMenuExtension # get root menu menubar = self.get_menubar() # new stage await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # verify one prim prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']] self.assertTrue(prim_list == ['/Sphere']) # use menu Create/AOV create_widget = self.find_menu(menubar, "Create") await create_widget.click(pos=create_widget.position+ui_test.Vec2(0, 5)) aov_widget = self.find_menu(create_widget, "AOV") await aov_widget.click(pos=aov_widget.position+ui_test.Vec2(50, 5)) # verify multiple prims prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']] self.assertFalse(prim_list == ['/Sphere']) # undo changes omni.kit.undo.undo() # verify one prim prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']] self.assertTrue(prim_list == ['/Sphere']) # new stage to prevent layout dialogs await omni.usd.get_context().new_stage_async()
2,868
Python
34.419753
143
0.643305
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/tests/__init__.py
from .aov_tests import *
25
Python
11.999994
24
0.72
omniverse-code/kit/exts/omni.kit.usda_edit/config/extension.toml
[package] title = "USDA Editor" description = "Context menu to edit USD layers as USDA files" authors = ["NVIDIA"] version = "1.1.10" changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" readme = "docs/README.md" icon = "data/icon.png" category = "Internal" feature = true [[python.module]] name = "omni.kit.usda_edit" [dependencies] "omni.kit.pip_archive" = {} "omni.ui" = {} "omni.usd" = {} "omni.usd.libs" = {} # Additional python module with tests, to make them discoverable by test system. [[python.module]] name = "omni.kit.usda_edit.tests"
564
TOML
20.730768
80
0.689716
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/content_browser_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.usd from . import editor from .layer_watch import LayerWatch from .usda_edit_utils import is_extension_loaded import os def content_browser_available() -> bool: """Returns True if the extension "omni.kit.widget.content_browser" is loaded""" return is_extension_loaded("omni.kit.window.content_browser") class ContentBrowserMenu: """ When this object is alive, Layers 2.0 has the additional context menu with the items that allow to edit the layer in the external editor. """ def __init__(self): import omni.kit.window.content_browser as content self._content_window = content.get_content_window() self.__start_name = self._content_window.add_context_menu( "Edit...", "menu_rename.svg", ContentBrowserMenu.start_editing, ContentBrowserMenu.is_not_editing ) self.__end_name = self._content_window.add_context_menu( "Finish editing", "menu_delete.svg", ContentBrowserMenu.stop_editing, ContentBrowserMenu.is_editing ) def destroy(self): """Stop all watchers and remove the menu from Layers 2.0""" if content_browser_available(): self._content_window.delete_context_menu(self.__start_name) self._content_window.delete_context_menu(self.__end_name) self.__start_name = None self.__end_name = None self._content_window = None LayerWatch().stop_all() @staticmethod def start_editing(menu: str, content_url: str): """Start watching for the layer and run the editor""" usda_filename = LayerWatch().start_watch(content_url) editor.run_editor(usda_filename) @staticmethod def stop_editing(menu: str, content_url: str): """Stop watching for the layer and remove the temporary files""" LayerWatch().stop_watch(content_url) @staticmethod def is_editing(content_url: str) -> bool: """Returns true if the layer is already watched""" return LayerWatch().has_watch(content_url) @staticmethod def is_not_editing(content_url: str) -> bool: """Returns true if the layer is not watched""" return omni.usd.is_usd_writable_filetype(content_url) and not ContentBrowserMenu.is_editing(content_url)
2,709
Python
38.275362
112
0.689184
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/extension_usda.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .layers_menu import layers_available from .layers_menu import LayersMenu from .content_menu import ContentMenu from .content_browser_menu import content_browser_available from .content_browser_menu import ContentBrowserMenu import omni.ext import omni.kit.app class UsdaEditExtension(omni.ext.IExt): def on_startup(self, ext_id): # Setup a callback for the event app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() self.__extensions_subscription = ext_manager.get_change_event_stream().create_subscription_to_pop( self._on_event, name="omni.kit.usda_edit" ) self.__layers_menu = None self.__content_menu = None self.__content_browser_menu = None self._on_event(None) # When kit exits we won't get a change event for content_browser unloading so we need to resort to # an explicit subscription to its enable/disable events. # # If content_browser is already enabled then we will immediately get a callback for it, so we want # to do this last. self.__content_browser_hook = ext_manager.subscribe_to_extension_enable( self._on_browser_enabled, self._on_browser_disabled, 'omni.kit.window.content_browser') def _on_browser_enabled(self, ext_id: str): if not self.__content_browser_menu: self.__content_browser_menu = ContentBrowserMenu() def _on_browser_disabled(self, ext_id: str): if self.__content_browser_menu: self.__content_browser_menu.destroy() self.__content_browser_menu = None def _on_event(self, event): # Create/destroy the menu in the Layers window if self.__layers_menu: if not layers_available(): self.__layers_menu.destroy() self.__layers_menu = None else: if layers_available(): self.__layers_menu = LayersMenu() # TODO: Create/destroy the menu in the Content Browser if self.__content_menu: self.__content_menu.destroy() self.__content_menu = None def on_shutdown(self): self.__extensions_subscription = None self.__content_browser_hook = None if self.__layers_menu: self.__layers_menu.destroy() self.__layers_menu = None if self.__content_menu: self.__content_menu.destroy() self.__content_menu = None if self.__content_browser_menu: self.__content_browser_menu.destroy() self.__content_browser_menu = None
3,068
Python
37.3625
106
0.648305
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/layer_watch.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from pathlib import Path from pxr import Sdf from pxr import Tf from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer import asyncio import carb import functools import omni.kit.app import os.path import random import string import tempfile import traceback def handle_exception(func): """ Decorator to print exception in async functions """ @functools.wraps(func) async def wrapper(*args, **kwargs): try: return await func(*args, **kwargs) except asyncio.CancelledError: # We always cancel the task. It's not a problem. pass except Exception as e: carb.log_error(f"Exception when async '{func}'") carb.log_error(f"{e}") carb.log_error(f"{traceback.format_exc()}") return wrapper def Singleton(class_): """ A singleton decorator. TODO: It's also available in omni.kit.widget.stage. We need a utility extension where we can put the utilities like this. """ instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @Singleton class LayerWatch: """ Singleton object that contains all the layer watchers. When the watcher is removed, the tmp file and directory are also removed. """ def __init__(self): self.__items = {} def start_watch(self, identifier): """ Create a temporary usda file and watch it. When this file is changed, the layer with the given identifier will be updated. """ watch_item = self.__items.get(identifier, None) if not watch_item: watch_item = LayerWatchItem(identifier) self.__items[identifier] = watch_item return watch_item.file_name def stop_watch(self, identifier): """ Stop watching to the temporary file created to the layer with the given identifier. It will remove the temporary file. """ if identifier in self.__items: self.__items[identifier].destroy() del self.__items[identifier] def has_watch(self, identifier): """ Return true if the layer with the given identifier is watched. """ return identifier in self.__items def stop_all(self): """ Stop watching for all the layers. """ for _, watch in self.__items.items(): watch.destroy() self.__items = {} @handle_exception async def wait_import_async(self, identifier): """ Wait for the importing of the layer. It happens when the layer is changed. """ if identifier in self.__items: await self.__items[identifier].wait_import_async() class LayerWatchItem(FileSystemEventHandler): def __init__(self, identifier): super().__init__() # SdfLayer self.__layer = Sdf.Layer.FindOrOpen(identifier) # Generate random name for temp directory while True: letters = string.ascii_lowercase dir_name = "kit_usda_" + "".join(random.choice(letters) for i in range(8)) tmp_path = Path(tempfile.gettempdir()).joinpath(dir_name) if not tmp_path.exists(): break # Create temporary directory tmp_path.mkdir() # Create temporary usda file tmp_file_path = tmp_path.joinpath(Tf.MakeValidIdentifier(Path(identifier).stem) + ".usda") self.__file_name = tmp_file_path.resolve().__str__() self.__layer.Export(self.__file_name) # Save the timestamp self.__last_mtime = os.path.getmtime(self.__file_name) self.__build_task = None self.__loop = asyncio.get_event_loop() # Watch the file self.__observer = Observer() self.__observer.schedule(self, path=tmp_path, recursive=False) self.__observer.start() # This event is set when the layer is re-imported. self.__imported_event = asyncio.Event() @property def file_name(self): """Return the temporary file name""" return self.__file_name def on_modified(self, event): """Called by watchdog when the temporary file is changed""" # Check it's the file we are watching. if event.src_path != self.file_name: return # Check the modification time. mtime = os.path.getmtime(self.file_name) if self.__last_mtime == mtime: return self.__last_mtime = mtime # Watchdog calls callback from different thread and USD doesn't like # it. We need to import USDA from the main thread. if self.__build_task: self.__build_task.cancel() self.__build_task = asyncio.ensure_future(self.__import(), loop=self.__loop) @handle_exception async def __import(self): """Import temporary file to the USD layer""" # Wait one frame on the case there was multiple events at the same time await omni.kit.app.get_app().next_update_async() file_name = self.file_name # The file extension. For anonymous layers it's ".sdf" format_id = f".{self.__layer.GetFileFormat().formatId}" if format_id == ".omni_usd" or format_id == ".usd_omni_wrapper": # The layer is on the omni server # Import is not implemented in the Omniverse file format. So we # clear it and transfer the content to the layer on the server. usda = Sdf.Layer.FindOrOpen(file_name) self.__layer.Clear() self.__layer.TransferContent(usda) else: # USD can't do cross-format Import, but it can do cross-format # export. if Path(file_name).suffix != format_id: # Export usda to the format of the layer. usda = Sdf.Layer.FindOrOpen(file_name) file_name = file_name + format_id usda.Export(file_name) # Import self.__layer.Import(file_name) if not self.__layer.anonymous: # Save if it's not an anonymous layer. So the edit goes directly to # the server or to the filesystem. self.__layer.Save() self.__imported_event.set() self.__imported_event.clear() @handle_exception async def wait_import_async(self): """ Wait for the importing of the layer. It happens when the layer is changed. """ await self.__imported_event.wait() def destroy(self): """Stop watching. Delete the temporary file and the temporary directory.""" if self.__observer: self.__observer.stop() # Wait when it stops. # TODO: We need to stop all of them and then join all of them. self.__observer.join() self.__observer = None if self.__layer: self.__layer = None # Remove tmp file and tmp folder if os.path.exists(self.__file_name): tmp_path = Path(self.__file_name).parent for f in tmp_path.iterdir(): if f.is_file(): f.unlink() tmp_path.rmdir() self.__imported_event.set() def __del__(self): self.destroy()
7,901
Python
30.73494
98
0.599291
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/layers_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from . import editor from .layer_watch import LayerWatch from .usda_edit_utils import is_extension_loaded def layers_available() -> bool: """Returns True if the extension "omni.kit.widget.layers" is loaded""" return is_extension_loaded("omni.kit.widget.layers") class LayersMenu: """ When this object is alive, Layers 2.0 has the additional context menu with the items that allow to edit the layer in the external editor. """ def __init__(self): import omni.kit.widget.layers as layers self.__menu_subscription = layers.ContextMenu.add_menu( [ {"name": ""}, { "name": "Edit...", "glyph": "menu_rename.svg", "show_fn": [ layers.ContextMenu.is_layer_item, layers.ContextMenu.is_not_missing_layer, layers.ContextMenu.is_layer_writable, layers.ContextMenu.is_layer_not_locked_by_other, layers.ContextMenu.is_layer_and_parent_unmuted, LayersMenu.is_not_editing, ], "onclick_fn": LayersMenu.start_editing, }, { "name": "Finish editing", "glyph": "menu_delete.svg", "show_fn": [layers.ContextMenu.is_layer_item, LayersMenu.is_editing], "onclick_fn": LayersMenu.stop_editing, }, ] ) def destroy(self): """Stop all watchers and remove the menu from Layers 2.0""" self.__menu_subscription = None LayerWatch().stop_all() @staticmethod def start_editing(objects): """Start watching for the layer and run the editor""" item = objects["item"] identifier = item().identifier usda_filename = LayerWatch().start_watch(identifier) editor.run_editor(usda_filename) @staticmethod def stop_editing(objects): """Stop watching for the layer and remove the temporary files""" item = objects["item"] identifier = item().identifier LayerWatch().stop_watch(identifier) @staticmethod def is_editing(objects): """Returns true if the layer is already watched""" item = objects["item"] identifier = item().identifier return LayerWatch().has_watch(identifier) @staticmethod def is_not_editing(objects): """Returns true if the layer is not watched""" return not LayersMenu.is_editing(objects)
3,067
Python
34.264367
89
0.592762
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/editor.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Optional import carb.settings import os import shutil import subprocess def _is_exe(path): """Return true if the path is executable""" return os.path.isfile(path) and os.access(path, os.X_OK) def run_editor(usda_filename: str): """Open text editor with usda_filename in it""" settings = carb.settings.get_settings() # Find out which editor it's necessary to use # Check the settings editor: Optional[str] = settings.get("/app/editor") if not editor: # If settings doesn't have it, check the environment variable EDITOR. # It's the standard way to set the editor in Linux. editor = os.environ.get("EDITOR", None) if not editor: # VSCode is the default editor editor = "code" # Remove quotes because it's a common way for windows to specify paths if editor[0] == '"' and editor[-1] == '"': editor = editor[1:-1] if not _is_exe(editor): try: # Check if we can run the editor editor = shutil.which(editor) except shutil.Error: editor = None if not editor: if os.name == "nt": # All Windows have notepad editor = "notepad" else: # Most Linux systems have gedit editor = "gedit" if os.name == "nt": # Using cmd on the case the editor is bat or cmd file call_command = ["cmd", "/c"] else: call_command = [] call_command.append(editor) call_command.append(usda_filename) # Non blocking call subprocess.Popen(call_command)
2,054
Python
29.671641
77
0.642648
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/content_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from . import editor from .layer_watch import LayerWatch from .usda_edit_utils import is_extension_loaded from omni.kit.ui import get_custom_glyph_code from pathlib import Path class ContentMenu: """ When this object is alive, Content Browser has the additional context menu with the items that allow to edit the USD files in the external editor. """ def __init__(self): import omni.kit.content as content self._content_window = content.get_content_window() edit_menu_name = f'{get_custom_glyph_code("${glyphs}/menu_rename.svg")} Edit...' self.__edit_menu_subscription = self._content_window.add_icon_menu( edit_menu_name, self._on_start_editing, self._is_edit_visible ) stop_menu_name = f'{get_custom_glyph_code("${glyphs}/menu_delete.svg")} Finish editing' self.__stop_menu_subscription = self._content_window.add_icon_menu( stop_menu_name, self._on_stop_editing, self._is_stop_visible ) def _is_edit_visible(self, content_url): '''True if we can show the menu item "Edit"''' for ext in ["usd", "usda", "usdc"]: if content_url.endswith(f".{ext}"): return not LayerWatch().has_watch(content_url) def _on_start_editing(self, menu, value): """Start watching for the layer and run the editor""" file_path = self._content_window.get_selected_icon_path() usda_filename = LayerWatch().start_watch(file_path) editor.run_editor(usda_filename) def _is_stop_visible(self, content_url): """Returns true if the layer is already watched""" return LayerWatch().has_watch(content_url) def _on_stop_editing(self, menu, value): """Stop watching for the layer and remove the temporary files""" file_path = self._content_window.get_selected_icon_path() LayerWatch().stop_watch(file_path) def destroy(self): """Stop all watchers and remove the menu from the content browser""" del self.__edit_menu_subscription self.__edit_menu_subscription = None del self.__stop_menu_subscription self.__stop_menu_subscription = None self._content_window = None LayerWatch().stop_all()
2,699
Python
39.298507
96
0.669507
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/tests/usda_test.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from ..layer_watch import LayerWatch from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from pxr import Usd from pxr import UsdGeom import omni.client import omni.kit import omni.usd import os import time import unittest OMNI_SERVER = "omniverse://kit.nucleus.ov-ci.nvidia.com" OMNI_USER = "omniverse" OMNI_PASS = "omniverse" class TestUsdaEdit(OmniUiTest): def __set_omni_credentials(self): # Save the environment to be able to restore it self.__OMNI_USER = os.environ.get("OMNI_USER", None) self.__OMNI_PASS = os.environ.get("OMNI_PASS", None) # Set the credentials os.environ["OMNI_USER"] = OMNI_USER os.environ["OMNI_PASS"] = OMNI_PASS def __restore_omni_credentials(self): if self.__OMNI_USER is not None: os.environ["OMNI_USER"] = self.__OMNI_USER else: os.environ.pop("OMNI_USER") if self.__OMNI_PASS is not None: os.environ["OMNI_PASS"] = self.__OMNI_PASS else: os.environ.pop("OMNI_PASS") async def test_open_file(self): # New stage with a sphere await omni.usd.get_context().new_stage_async() omni.kit.commands.execute("CreatePrim", prim_path="/Sphere", prim_type="Sphere", select_new_prim=False) stage = omni.usd.get_context().get_stage() # Create USDA usda_filename = LayerWatch().start_watch(stage.GetRootLayer().identifier) # Check it's a valid stage duplicate = Usd.Stage.Open(usda_filename) self.assertTrue(duplicate) # Check it has the sphere sphere = duplicate.GetPrimAtPath("/Sphere") self.assertTrue(sphere) UsdGeom.Cylinder.Define(duplicate, '/Cylinder') duplicate.Save() await omni.kit.app.get_app().next_update_async() # Check cylinder is created cylinder = duplicate.GetPrimAtPath("/Cylinder") self.assertTrue(cylinder) # Remove USDA LayerWatch().stop_watch(stage.GetRootLayer().identifier) # Check the file is removed self.assertFalse(Path(usda_filename).exists()) await omni.kit.app.get_app().next_update_async() @unittest.skip("Works locally, but fails on TC for server connection in linux -> flaky") async def test_edit_file_on_nucleus(self): self.__set_omni_credentials() # Create a new stage on server temp_usd_folder = f"{OMNI_SERVER}/Users/test_usda_edit_{str(time.time())}" temp_usd_file_path = f"{temp_usd_folder}/test_edit_file_on_nucleus.usd" # cleanup first await omni.client.delete_async(temp_usd_folder) # create the folder result = await omni.client.create_folder_async(temp_usd_folder) self.assertEqual(result, omni.client.Result.OK) stage = Usd.Stage.CreateNew(temp_usd_file_path) await omni.kit.app.get_app().next_update_async() UsdGeom.Xform.Define(stage, '/xform') UsdGeom.Sphere.Define(stage, '/xform/sphere') await omni.kit.app.get_app().next_update_async() stage.Save() # Start watching and edit the temp stage usda_filename = LayerWatch().start_watch(stage.GetRootLayer().identifier) temp_stage = Usd.Stage.Open(usda_filename) # Create another sphere UsdGeom.Sphere.Define(temp_stage, '/xform/sphere1') # Save the stage temp_stage.Save() # UsdStage saves the temorary file and renames it to usda, so we need # to touch it to let LayerWatch know it's changed. Path(usda_filename).touch() # Small delay because watchdog in LayerWatch doesn't call the callback # right away. So we need to give it some time. await LayerWatch().wait_import_async(stage.GetRootLayer().identifier) # Remove USDA LayerWatch().stop_watch(stage.GetRootLayer().identifier) stage.Reload() # Check the second sphere is there sphere = stage.GetPrimAtPath("/xform/sphere1") self.assertTrue(sphere) # Remove the temp folder result = await omni.client.delete_async(temp_usd_folder) self.assertEqual(result, omni.client.Result.OK) self.__restore_omni_credentials()
4,700
Python
34.885496
111
0.657021
omniverse-code/kit/exts/omni.kit.usda_edit/docs/CHANGELOG.md
# Changelog This document records all notable changes to ``omni.kit.usda_edit`` extension. ## [1.1.10] - 2022-02-02 ### Changed - Removed explicit pip dependency requirement on `watchdog`. It's now pre-bundled with Kit SDK. ## [1.1.9] - 2021-12-22 ### Fixed - content_browser context menu is now destroyed when content_browser unloaded first during kit exit ## [1.1.8] - 2021-02-23 ### Changed - The test waits for import instead of 15 frames ## [1.1.7] - 2021-02-17 ### Added - Support for the file format `usd_omni_wrapper` which is from Nucleus ### Changed - The call of the editor is not blocking ### Fixed - The path to editor can contain quotation marks ## [1.1.6] - 2020-12-08 ### Added - Preview image and description ## [1.1.5] - 2020-12-03 ### Added - Dependency on watchdog ## [1.1.4] - 2020-11-12 ### Changed - Fixed exception in Create ## [1.1.3] - 2020-11-11 ### Changed - Fixed the bug when the USD file destroyed when it's on the server and has the asset metadata ### Added - Menu to `omni.kit.window.content_browser` ## [1.1.2] - 2020-07-09 ### Changed - Join the observer before destroy it. It should fix the exception when exiting Kit. ## [1.1.1] - 2020-07-08 ### Added - Added dependency to `omni.kit.pipapi` ## [1.1.0] - 2020-07-06 ### Added - The editor executable is set using settings `/app/editor` or `EDITOR` environment variable. ## [1.0.0] - 2020-07-06 ### Added - CHANGELOG.rst - Added the context menu to Content Browser window to edit USDA files ## [0.1.0] - 2020-06-29 ### Added - Ability to edit USD layers as USDA files - Added the context menu to Layers window to edit USDA files
1,628
Markdown
23.681818
99
0.689189
omniverse-code/kit/exts/omni.kit.usda_edit/docs/README.md
# USDA Editor [omni.kit.usda_edit] The tool to view end edit USD layers in a text editor. Convert a USD file to the USD ASCII format in a temporary location and run an editor on it. After saving the editor, the edited file will be converted back to the original format and reload the corresponding layer in Kit, invoking the stage's update. The context menu to edit layer appears in Layers and Content windows. The editor can be configured with a setting `/app/editor` or environment variable `EDITOR`. By default, the editor is either `code` or `notepad`/`gedit`, depending on the availability.
601
Markdown
36.624998
77
0.777038
omniverse-code/kit/exts/omni.usd.config/omni/usd_config/extension.py
import os from glob import glob from pathlib import Path import carb import carb.dictionary import carb.settings import omni.ext import omni.kit.app from omni.mtlx import get_mtlx_stdlib_search_path ENABLE_NESTED_GPRIMS_SETTINGS_PATH = "/usd/enableNestedGprims" DISABLE_CAMERA_ADAPTER_SETTINGS_PATH = "/usd/disableCameraAdapter" MDL_SEARCH_PATHS_REQUIRED = "/renderer/mdl/searchPaths/required" MDL_SEARCH_PATHS_TEMPLATES = "/renderer/mdl/searchPaths/templates" class Extension(omni.ext.IExt): def __init__(self): super().__init__() pass def on_startup(self): self._app = omni.kit.app.get_app() self._settings = carb.settings.acquire_settings_interface() self._settings.set_default_bool(ENABLE_NESTED_GPRIMS_SETTINGS_PATH, True) self._usd_enable_nested_gprims = self._settings.get(ENABLE_NESTED_GPRIMS_SETTINGS_PATH) self._settings.set_default_bool(DISABLE_CAMERA_ADAPTER_SETTINGS_PATH, False) self._usd_disable_camera_adapter = self._settings.get(DISABLE_CAMERA_ADAPTER_SETTINGS_PATH) self._setup_usd_env_settings() self._setup_usd_material_env_settings() def on_shutdown(self): self._settings = None self._app = None # This must be invoked before USD's TfRegistry for env settings gets initialized. # See https://gitlab-master.nvidia.com/carbon/Graphene/merge_requests/3115#note_5019170 def _setup_usd_env_settings(self): is_release_build = not self._app.is_debug_build() if is_release_build: # Disable TfEnvSetting banners (alerting users to local environment overriding Usd defaults) in release builds. os.environ["TF_ENV_SETTING_ALERTS_ENABLED"] = "0" # Preferring translucent over additive shaders for opacity mapped preview shaders in HdStorm. os.environ["HDST_USE_TRANSLUCENT_MATERIAL_TAG"] = "1" if self._usd_disable_camera_adapter: # Disable UsdImaging camera support. os.environ["USDIMAGING_DISABLE_CAMERA_ADAPTER"] = "1" # Experiment with sparse light updates. # https://github.com/PixarAnimationStudios/USD/commit/1a82d34b1144caa85909b417d18148197fba551c # Remove this when nv-usd 20.11+ is enabled in the build. os.environ["USDIMAGING_ENABLE_SPARSE_LIGHT_UPDATES"] = "1" if self._usd_enable_nested_gprims: # Enable imaging refresh for nested gprims (needed for light gizmos). # https://nvidia-omniverse.atlassian.net/browse/OM-9446 os.environ["USDIMAGING_ENABLE_NESTED_GPRIMS"] = "1" # Enable support for querying doubles in XformCommonAPI::GetXformVectors os.environ["USDGEOM_XFORMCOMMONAPI_ALLOW_DOUBLES"] = "1" # Allow material networks to be defined under IDs which are not known to SdrRegistry until we have a registration # mechnism for mdl. os.environ["USDIMAGING_ALLOW_UNREGISTERED_SHADER_IDS"] = "1" # Continue supporting old mdl schema in UsdShade for now. os.environ["USDSHADE_OLD_MDL_SCHEMA_SUPPORT"] = "1" # Disable primvar invalidation in UsdImagingGprimAdapter so that Kit's scene delegate can perform its own primvar # analysis. os.environ["USDIMAGING_GPRIMADAPTER_PRIMVAR_INVALIDATION"] = "0" # OM-18759 # Disable auto-scaling of time samples from layers whose timeCodesPerSecond do not match that of # the stage's root layer. # Eventually Pixar will retire this runtime switch; we'll need tooling to find and fix all # non-compliant assets to maintain their original animated intent. # OM-28725 # Enable auto-scaling because more and more animation content, e.g. Machinima contents, need # this feature. Kit now has property window to adjust timeCodePerSecond for each layer so it won't # be a big issue if animator brings in two layers with different timeCodePerSecond. Need a validator # to notify the authors such info though. os.environ["PCP_DISABLE_TIME_SCALING_BY_LAYER_TCPS"] = "0" # OM-18814 # Temporarily disable notification when setting interpolation mode. # This needs to be investigated further after Ampere demos are delivered. os.environ["USDSTAGE_DISABLE_INTERP_NOTICE"] = "1" # Properties which are unknown to UsdImagingGprimAdapter do not invalidate the rprim (disabled for now- # see OM-9049. Use whitelist, blacklist, and carb logging in # omni::usd::hydra::SceneDelegate::ProcessNonAdapterBasedPropertyChange to help contribute to re-enabling it). # os.environ["USDIMAGING_UNKNOWN_PROPERTIES_ARE_CLEAN] = "1" # OM-38943 # Enable parallel sync for non-material sprims (i.e., lights). os.environ["HD_ENABLE_MULTITHREADED_NON_MATERIAL_SPRIM_SYNC"] = "1" # OM-39636 # Disable scene index emulation until we have integated it with our HdMaterialNode changes for MDL support. os.environ["HD_ENABLE_SCENE_INDEX_EMULATION"] = "0" # OM-47199 # Disable the MDL Builtin Bypass for omni_usd_resolver os.environ["OMNI_USD_RESOLVER_MDL_BUILTIN_BYPASS"] = "1" # OM-62080 # Use NV-specific maps for optimized Hydra change tracking os.environ["HD_CHANGETRACKER_USE_CONTIGUOUS_VALUES_MAP"] = "1" # OM-93197 # Suppress warning spew about material bindings until assets are addressed os.environ["USD_SHADE_MATERIAL_BINDING_API_CHECK"] = "allowMissingAPI" def _setup_usd_material_env_settings(self): def gather_mdl_modules(path, prefix=""): try: if not path.exists(): return except: return for child in path.iterdir(): if child.is_file() and (child.suffix == ".mdl"): mdl_modules.add(prefix + child.name) elif child.is_dir(): gather_mdl_modules(child, prefix + child.stem + "/") def process_mdl_search_path(settings_path): paths = self._settings.get(settings_path) if not paths: carb.log_warn(f"Unable to query '{settings_path}' from carb.settings.") return paths = [Path(p.strip()) for p in paths.split(";") if p.strip()] for p in paths: gather_mdl_modules(p) # use a set to avoid dupliate module names # if Neuray finds multiple modules with the same name only the first is loaded into the database mdl_modules = set() process_mdl_search_path(MDL_SEARCH_PATHS_REQUIRED) process_mdl_search_path(MDL_SEARCH_PATHS_TEMPLATES) os.environ["OMNI_USD_RESOLVER_MDL_BUILTIN_PATHS"] = ",".join(mdl_modules) # OM-19420, OM-88291 # Set the MaterialX library path in order to add mtlx nodes to the NDR mtlx_library_path = get_mtlx_stdlib_search_path() if "PXR_MTLX_STDLIB_SEARCH_PATHS" in os.environ: os.environ["PXR_MTLX_STDLIB_SEARCH_PATHS"] += os.pathsep + mtlx_library_path else: os.environ["PXR_MTLX_STDLIB_SEARCH_PATHS"] = mtlx_library_path
7,242
Python
42.113095
123
0.660039
omniverse-code/kit/exts/omni.mdl.usd_converter/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "MDL to USD converter" description="MDL to USD converter extension." # 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 = "Services" # Keywords for the extension keywords = ["kit", "mdl", "Python bindings"] # 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 for this extension: [dependencies] "omni.usd" = {} "omni.mdl.neuraylib" = {} "omni.mdl" = {} # Main python module this extension provides, it will be publicly available as "import omni.mdl.usd_converter". [[python.module]] name = "omni.mdl.usd_converter" # Extension test settings [[test]] args = [] dependencies = [] stdoutFailPatterns.include = [] stdoutFailPatterns.exclude = []
1,654
TOML
30.826922
118
0.737606
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/__init__.py
from .usd_converter import *
29
Python
13.999993
28
0.758621
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/usd_converter.py
# ***************************************************************************** # Copyright 2021 NVIDIA Corporation. All rights reserved. # ***************************************************************************** import omni.ext import carb import os import shutil import tempfile import carb.settings from omni.mdl import pymdlsdk from omni.mdl import pymdl import omni.mdl.neuraylib from . import mdl_usd import asyncio from pxr import Usd from pxr import UsdShade MDL_AUTOGEN_PATH = "${data}/shadergraphs/mdl_usd" class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def add_search_path_to_system_path(searchPath: str): if not searchPath == None and not searchPath == "": MDL_SYSTEM_PATH = "/app/mdl/additionalSystemPaths" settings = carb.settings.get_settings() mdl_custom_paths: List[str] = settings.get(MDL_SYSTEM_PATH) or [] mdl_custom_paths.append(searchPath) mdl_custom_paths = list(set(mdl_custom_paths)) settings.set_string_array(MDL_SYSTEM_PATH, mdl_custom_paths) # Functions and vars are available to other extension as usual in python: `omni.mdl.usd_converter.mdl_to_usd(x)` # # mdl_to_usd(moduleName, targetFolder, targetFilename) # moduleName: module to convert (example: "nvidia/core_definitions.mdl") # searchPath: MDL search path to be able to load MDL modules referenced by moduleName # targetFolder: Destination folder for USD stage (default = "${data}/shadergraphs/mdl_usd") # targetFilename: Destination stage filename (default is module name, example: "core_definitions.usda") # output: What to output: # a shader: omni.mdl.usd_converter.mdl_usd.OutputType.SHADER # a material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL # geometry and material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY # nestedShaders: Do we want nested shaders or flat (default = False) # def mdl_to_usd( moduleName: str, searchPath: str = None, targetFolder: str = MDL_AUTOGEN_PATH, targetFilename: str = None, output: mdl_usd.OutputType = mdl_usd.OutputType.SHADER, nestedShaders: bool = False): print(f"[omni.mdl.usd_converter] mdl_to_usd was called with {moduleName}") # acquire neuray instance from OV ovNeurayLib = omni.mdl.neuraylib.get_neuraylib() ovNeurayLibHandle = ovNeurayLib.getNeurayAPI() # feed the neuray instance into the python binding neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle) neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status() print(f"Neuray Status: {neurayStatus}") # Set carb.settings with new MDL search path add_search_path_to_system_path(searchPath) # Select a view on the database used for the rtx renderer for. # It should be fine to use this one always. Hydra will deal with applying the changes to the # other renderer. It would be possible to use an own space entirely but this would double module loading. # In the long, we want to load modules only into one scope. dbScopeName = "rtx_scope" # we need to load modules to OV using the omni.mdl.neuraylib # on the c++ side this is async, here it is blocking! print(f"createMdlModule called with: {moduleName}") ovModule = ovNeurayLib.createMdlModule(moduleName) print(f"CoreDefinitions: {ovModule.valid()}") if ovModule.valid(): print(f" dbScopeName: {ovModule.dbScopeName}") print(f" dbName: {ovModule.dbName}") print(f" qualifiedName: {ovModule.qualifiedName}") else: print(f" createMdlModule failed : {moduleName}") # after the module is loaded we create a new transaction that can see the loaded module ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName) trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle) print(f"Transaction Open: {trans.is_open()}") # try out the high level binding module = pymdl.Module._fetchFromDb(trans, ovModule.dbName) if module: print(f"MDL Qualified Name: {module.mdlName}") print(f"MDL Simple Name: {module.mdlSimpleName}") print(f"MDL DB Name: {module.dbName}") print(f"MDL Module filename: {module.filename}") else: print("MDL Module: None") print(f"Failed to convert: {moduleName}") return False try: stage = mdl_usd.Usd.Stage.CreateInMemory() except: trans.abort() trans = None return False stage.SetMetadata('comment', 'MDL to USD conversion') # create context for the conversion of the scene context = mdl_usd.ConverterContext() context.set_neuray(neuray) context.set_transaction(trans) context.set_stage(stage) context.mdl_to_usd_output = output context.mdl_to_usd_output_material_nested_shaders = nestedShaders context.ov_neuray = ovNeurayLib mdl_usd.module_to_stage(context, module) # Workaround the issue creating stage under "${data}/shadergraphs/mdl_usd" # by creating the stage in a temp folder and copying it to dest folder with TemporaryDirectory() as temp_dir: unmangle_helper = mdl_usd.Unmangle(context) # Demangle instance name (unmangled_flag, simple_name) = unmangle_helper.unmangle_mdl_identifier(module.dbName) simple_name = simple_name.replace("::", "_") filename = os.path.join(temp_dir, simple_name + ".usda") if targetFilename is not None: if targetFilename[-4:] == ".usd" or targetFilename[-5:] == ".usda": filename = os.path.join(temp_dir, targetFilename) else: filename = os.path.join(temp_dir, targetFilename + ".usda") stage.GetRootLayer().Export(filename) # Copy file to destination folder path = targetFolder token = carb.tokens.get_tokens_interface() mdlUSDPath = token.resolve(path) dest = os.path.abspath(mdlUSDPath) # Create folder if it does not exist if not os.path.exists(dest): os.makedirs(dest) try: shutil.copy2(filename, dest) print(f"Stage saved as: {os.path.join(dest, os.path.basename(filename))}") except: print(f"Failed to save stage as: {os.path.join(dest, os.path.basename(filename))}") pass try: omni.kit.window.material_graph.GraphExtension.refresh_compounds() except: pass ovNeurayLib.destroyMdlModule(ovModule) # since we have been reading only, abort trans.abort() trans = None return True def test_mdl_prim_to_usd(primPath: str): stage = omni.usd.get_context().get_stage() if stage: prim = stage.GetPrimAtPath(primPath) if prim: mdl_prim_to_usd(stage, prim) def mdl_prim_to_usd(stage: Usd.Stage, prim: Usd.Prim): # Only handle material for the time beeing if not UsdShade.Material(prim): return # acquire neuray instance from OV ovNeurayLib = omni.mdl.neuraylib.get_neuraylib() ovNeurayLibHandle = ovNeurayLib.getNeurayAPI() # feed the neuray instance into the python binding neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle) neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status() print(f"Neuray Status: {neurayStatus}") # after the module is loaded we create a new transaction that can see the loaded module dbScopeName = "rtx_scope" ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName) trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle) print(f"Transaction Open: {trans.is_open()}") # create context for the conversion of the scene context = mdl_usd.ConverterContext() context.set_neuray(neuray) context.set_transaction(trans) context.set_stage(stage) context.mdl_to_usd_output = mdl_usd.OutputType = mdl_usd.OutputType.MATERIAL context.mdl_to_usd_output_material_nested_shaders = False context.ov_neuray = ovNeurayLib mdl_usd.mdl_prim_to_usd(context, stage, prim) # since we have been reading only, abort trans.abort() trans = None return True # usd_prim_to_mdl(usdStage, usdPrim, searchPath) # usdStage: Input stage containing the Prim to convert # usdPrim: Prim to convert (default = not set, use stage default Prim) # searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set) # forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False) # async def usd_prim_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None, forceNotOV: bool = False): print(f"[omni.mdl.usd_converter] usd_prim_to_mdl was called with {usdStage} / {usdPrim} / {searchPath} / {forceNotOV}") rtncode = True # acquire neuray instance from OV ovNeurayLib = omni.mdl.neuraylib.get_neuraylib() ovNeurayLibHandle = ovNeurayLib.getNeurayAPI() # feed the neuray instance into the python binding neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle) neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status() print(f"Neuray Status: {neurayStatus}") # Set carb.settings with new MDL search path add_search_path_to_system_path(searchPath) # Select a view on the database used for the rtx renderer for. # It should be fine to use this one always. Hydra will deal with applying the changes to the # other renderer. It would be possible to use an own space entirely but this would double module loading. # In the long, we want to load modules only into one scope. dbScopeName = "rtx_scope" # create a new transaction ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName) trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle) print(f"Transaction Open: {trans.is_open()}") try: stage = mdl_usd.Usd.Stage.Open(usdStage) except: rtncode = False if rtncode: if usdPrim == None: try: # Determine default Prim usdPrim = stage.GetDefaultPrim().GetPath() except: pass if usdPrim == None: print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage") rtncode = False if rtncode: # create context for the conversion of the scene context = mdl_usd.ConverterContext() context.set_neuray(neuray) context.set_transaction(trans) context.set_stage(stage) if not forceNotOV: context.ov_neuray = ovNeurayLib inst_name = await mdl_usd.convert_usd_to_mdl(context, usdPrim, None) rtncode = (inst_name is not None) # transaction might have changed internally trans = context.transaction if not rtncode: print(f"[omni.mdl.usd_converter] error: Conversion failure") trans.abort() trans = None return rtncode # test_export_to_mdl(usdStage, usdPrim, searchPath) # usdStage: Input stage containing the Prim to convert # usdPrim: Prim to convert (default = not set, use stage default Prim) # searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set) # async def test_export_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None): # pragma: no cover # Set carb.settings with new MDL search path add_search_path_to_system_path(searchPath) stage = None try: stage = mdl_usd.Usd.Stage.Open(usdStage) except: return False if usdPrim == None: try: # Determine default Prim usdPrim = stage.GetDefaultPrim().GetPath() except: pass if usdPrim == None: print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage") return False prim = stage.GetPrimAtPath(usdPrim) path = "c:/temp/new_module.mdl" return asyncio.ensure_future(export_to_mdl(path, prim)) # export_to_mdl(path, prim) # path: Output file name # prim: Prim to convert # # Note: The MDL modules referenced by the prim must be in the MDL searchPath # async def export_to_mdl(path: str, prim: mdl_usd.Usd.Prim, forceNotOV: bool = False): if prim == None: print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage") return False # acquire neuray instance from OV ovNeurayLib = omni.mdl.neuraylib.get_neuraylib() ovNeurayLibHandle = ovNeurayLib.getNeurayAPI() # feed the neuray instance into the python binding neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle) neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status() print(f"Neuray Status: {neurayStatus}") # Select a view on the database used for the rtx renderer for. # It should be fine to use this one always. Hydra will deal with applying the changes to the # other renderer. It would be possible to use an own space entirely but this would double module loading. # In the long, we want to load modules only into one scope. dbScopeName = "rtx_scope" # create a new transaction ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName) trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle) print(f"Transaction Open: {trans.is_open()}") stage = prim.GetStage() # create context for the conversion of the scene context = mdl_usd.ConverterContext() context.set_neuray(neuray) context.set_transaction(trans) context.set_stage(stage) if not forceNotOV: context.ov_neuray = ovNeurayLib usd_prim = prim.GetPath() inst_name = await mdl_usd.convert_usd_to_mdl(context, usd_prim, path) rtncode = (inst_name is not None) if rtncode: print(f"[omni.mdl.usd_converter] Export to MDL success") else: print(f"[omni.mdl.usd_converter] Error: Export to MDL failure") context.transaction.abort() context.set_transaction(None) return rtncode def find_tokens(lines, filter_import_lines = False): return mdl_usd.find_tokens(lines, filter_import_lines) # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class DiscoveryExtension(omni.ext.IExt): # pragma: no cover # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.mdl.usd_converter] MDL to USD converter startup") def on_shutdown(self): print("[omni.mdl.usd_converter] MDL to USD converter shutdown")
15,345
Python
36.798029
123
0.676442
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/mdl_usd.py
#***************************************************************************** # Copyright 2022 NVIDIA Corporation. All rights reserved. #***************************************************************************** import sys import os import gc import platform import traceback from enum import Enum from pxr import Usd from pxr import Plug from pxr import Sdr from pxr import Sdf from pxr import Tf from pxr import UsdShade from pxr import Gf from pxr import UsdGeom from pxr import Kind from pxr import UsdUI import numpy # used to represent Vectors, Matrices, and Colors import re # For command line args from copy import deepcopy # Dictionary merging import tempfile # load the binding module print("MDL python binding about to load ...") #################### # Omniverse code from omni.mdl import pymdlsdk from omni.mdl import pymdl import omni.client async def copy_async(texture_path, dst_path): result = await omni.client.copy_async(texture_path, dst_path) return (result == omni.client.Result.OK) # Omniverse code #################### # TODO: loading fails for debug builds of the pymdlsdk.pyd (or pymdlsdk.so on unix) module print("MDL python binding loaded") def str2bool(v): return str(v).lower() in ("true", "1") def str2MDL_TO_USD_OUTPUT(v): if v == '1': return OutputType.SHADER if v == '2': return OutputType.MATERIAL if v == '3': return OutputType.MATERIAL_AND_GEOMETRY #-------------------------------------------------------------------------------------------------- # Command line arguments #-------------------------------------------------------------------------------------------------- class Args: # pragma: no cover display_usage = False options = dict() def __init__(self): self.options["SEARCH_PATH"] = get_examples_search_path() self.options["MODULE"] = "::nvidia::sdk_examples::tutorials" self.options["PRIM"] = "/example_material" # Used for USD to MDL conversion self.options["STAGE"] = "tutorials.usda" self.options["OUT"] = "tutorials.usda" # Set FOR_OV to False if a Material/Shader hierarchy is required in the output USD stage # SHADER = 1 # MATERIAL = 2 # MATERIAL_AND_GEOMETRY = 3 self.options["MDL_TO_USD_OUTPUT"] = 1 self.options["NESTED_SHADERS"] = False # See mdl_to_usd_output_material_nested_shaders self.options["MDL_TO_USD"] = True for a in sys.argv: if a == "-help" or a == "-h" or a == "-?": self.display_usage = True break match = re.search("(.+)=(.+)", a) if match: self.options[match.group(1)] = match.group(2) # Convert paths self.options["SEARCH_PATH"] = os.path.abspath(self.options["SEARCH_PATH"]) self.options["OUT"] = os.path.abspath(self.options["OUT"]) # Convert string args to bool self.options["MDL_TO_USD"] = str2bool(self.options["MDL_TO_USD"]) self.options["NESTED_SHADERS"] = str2bool(self.options["NESTED_SHADERS"]) # Convert string args to int self.options["MDL_TO_USD_OUTPUT"] = str2MDL_TO_USD_OUTPUT(self.options["MDL_TO_USD_OUTPUT"]) def usage(self): print("usage: " + os.path.basename(sys.argv[0]) + " [-help|-h|-?] [SEARCH_PATH=<path>] [MODULE=<string>] [PRIM=<string>] [STAGE=<string>] [OUT=<string>] [MDL_TO_USD_OUTPUT=<int>] [NESTED_SHADERS=<bool>] [MDL_TO_USD=<bool>]") print("\n") print(" -help|-h|-?:\t Display usage") print(" SEARCH_PATH:\t Use this as MDL search path (default: {})".format(self.options["SEARCH_PATH"])) print(" MODULE:\t Module to load (default: {})".format(self.options["MODULE"])) print(" PRIM:\t\t USD prim to convert to MDL (default: {})".format(self.options["PRIM"])) print(" STAGE:\t USD stage to load and convert (default: {})".format(self.options["STAGE"])) print(" OUT:\t\t Output file (default: {})".format(self.options["OUT"])) print(" MDL_TO_USD_OUTPUT:\t Output either a shader (1) or material (2) or material and geometry (3) (default: {})".format(self.options["MDL_TO_USD_OUTPUT"])) print(" NESTED_SHADERS:\t Output nested shader tree, vs. flat shader tree (default: {})".format(self.options["NESTED_SHADERS"])) print(" MDL_TO_USD:\t MDL to USD conversion ortherwise USD to MDL (default: {})".format(self.options["MDL_TO_USD"])) #-------------------------------------------------------------------------------------------------- # USD and misc utilities #-------------------------------------------------------------------------------------------------- MdlIValueKindToUSD = { pymdlsdk.IValue.Kind.VK_BOOL: Sdf.ValueTypeNames.Bool, pymdlsdk.IValue.Kind.VK_INT : Sdf.ValueTypeNames.Int, pymdlsdk.IValue.Kind.VK_ENUM : Sdf.ValueTypeNames.Int, pymdlsdk.IValue.Kind.VK_FLOAT : Sdf.ValueTypeNames.Float, pymdlsdk.IValue.Kind.VK_DOUBLE : Sdf.ValueTypeNames.Double, pymdlsdk.IValue.Kind.VK_STRING : Sdf.ValueTypeNames.String, pymdlsdk.IValue.Kind.VK_COLOR : Sdf.ValueTypeNames.Color3f, pymdlsdk.IValue.Kind.VK_STRUCT : Sdf.ValueTypeNames.Token, pymdlsdk.IValue.Kind.VK_TEXTURE : Sdf.ValueTypeNames.Asset, pymdlsdk.IValue.Kind.VK_LIGHT_PROFILE : Sdf.ValueTypeNames.Asset, pymdlsdk.IValue.Kind.VK_BSDF_MEASUREMENT : Sdf.ValueTypeNames.Asset } MdlITypeKindToUSD = { pymdlsdk.IType.Kind.TK_BOOL: Sdf.ValueTypeNames.Bool, pymdlsdk.IType.Kind.TK_INT : Sdf.ValueTypeNames.Int, pymdlsdk.IType.Kind.TK_ENUM : Sdf.ValueTypeNames.Int, pymdlsdk.IType.Kind.TK_FLOAT : Sdf.ValueTypeNames.Float, pymdlsdk.IType.Kind.TK_DOUBLE : Sdf.ValueTypeNames.Double, pymdlsdk.IType.Kind.TK_STRING : Sdf.ValueTypeNames.String, pymdlsdk.IType.Kind.TK_COLOR : Sdf.ValueTypeNames.Color3f, pymdlsdk.IType.Kind.TK_STRUCT : Sdf.ValueTypeNames.Token, pymdlsdk.IType.Kind.TK_TEXTURE : Sdf.ValueTypeNames.Asset, pymdlsdk.IType.Kind.TK_LIGHT_PROFILE : Sdf.ValueTypeNames.Asset, pymdlsdk.IType.Kind.TK_BSDF_MEASUREMENT : Sdf.ValueTypeNames.Asset } # TODO: # mi::neuraylib::IType::TK_BSDF # mi::neuraylib::IType::TK_EDF # mi::neuraylib::IType::TK_VDF def python_vector_to_usd_type(dtype, size): if dtype == numpy.int32 or dtype == bool: if size == 2: return Sdf.ValueTypeNames.Int2 elif size == 3: return Sdf.ValueTypeNames.Int3 elif size == 4: return Sdf.ValueTypeNames.Int4 elif dtype == numpy.float32: if size == 2: return Sdf.ValueTypeNames.Float2 elif size == 3: return Sdf.ValueTypeNames.Float3 elif size == 4: return Sdf.ValueTypeNames.Float4 elif dtype == numpy.float64: if size == 2: return Sdf.ValueTypeNames.Double2 elif size == 3: return Sdf.ValueTypeNames.Double3 elif size == 4: return Sdf.ValueTypeNames.Double4 return None def python_vector_to_usd_value(value): dtype = value.dtype size = value.size out = None if dtype == numpy.int32 or dtype == bool: if size == 2: out = Gf.Vec2i(0) elif size == 3: out = Gf.Vec3i(0) elif size == 4: out = Gf.Vec4i(0) if out != None: for i in range(size): out[i] = int(value[i][0]) elif dtype == numpy.float32: if size == 2: out = Gf.Vec2f(0) elif size == 3: out = Gf.Vec3f(0) elif size == 4: out = Gf.Vec4f(0) if out != None: for i in range(size): out[i] = float(value[i][0]) elif dtype == numpy.float64: if size == 2: out = Gf.Vec2d(0) elif size == 3: out = Gf.Vec3d(0) elif size == 4: out = Gf.Vec4d(0) if out != None: for i in range(size): out[i] = numpy.float64(value[i][0]) return out def custom_data_from_python_vector(value): dtype = value.dtype out = dict() if dtype == bool: size = value.size out = dict({"mdl":{"type" : "bool{}".format(size)}}) return out def python_matrix_to_usd_type(dtype, nrow, ncol): # numpyType Column Row OutType m = { 'float32' : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2d, 3 : Sdf.ValueTypeNames.Float3Array, 4 : Sdf.ValueTypeNames.Float4Array}, 3 : { 2 : Sdf.ValueTypeNames.Float2Array, 3 : Sdf.ValueTypeNames.Matrix3d, 4 : Sdf.ValueTypeNames.Float4Array}, 4 : { 2 : Sdf.ValueTypeNames.Float2Array, 3 : Sdf.ValueTypeNames.Float3Array, 4 : Sdf.ValueTypeNames.Matrix4d }}, 'float64' : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2d, 3 : Sdf.ValueTypeNames.Double3Array, 4 : Sdf.ValueTypeNames.Double4Array}, 3 : { 2 : Sdf.ValueTypeNames.Double2Array, 3 : Sdf.ValueTypeNames.Matrix3d, 4 : Sdf.ValueTypeNames.Double4Array}, 4 : { 2 : Sdf.ValueTypeNames.Double2Array, 3 : Sdf.ValueTypeNames.Double3Array, 4 : Sdf.ValueTypeNames.Matrix4d }}} return m[dtype.name][ncol][nrow] def python_matrix_to_usd_value(value): dtype = value.dtype nrow = value.shape[0] ncol = value.shape[1] out = None if dtype == numpy.float32: if ncol == 2: if nrow == 2: out = Gf.Matrix2d(0) out.SetColumn(0, Gf.Vec2d(float(value[0][0]), float(value[0][1]))) out.SetColumn(1, Gf.Vec2d(float(value[1][0]), float(value[1][1]))) elif nrow == 3: out = [Gf.Vec3f(float(value[0][0]), float(value[1][0]), float(value[2][0])), Gf.Vec3f(float(value[0][1]), float(value[1][1]), float(value[2][1]))] elif nrow == 4: out = [Gf.Vec4f(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])), Gf.Vec4f(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1]))] elif ncol == 3: if nrow == 2: out = [Gf.Vec2f(float(value[0][0]), float(value[1][0])), Gf.Vec2f(float(value[0][1]), float(value[1][1])), Gf.Vec2f(float(value[0][2]), float(value[1][2]))] elif nrow == 3: out = Gf.Matrix3d(0) out.SetColumn(0, Gf.Vec3d(float(value[0][0]), float(value[0][1]), float(value[0][2]))) out.SetColumn(1, Gf.Vec3d(float(value[1][0]), float(value[1][1]), float(value[1][2]))) out.SetColumn(2, Gf.Vec3d(float(value[2][0]), float(value[2][1]), float(value[2][2]))) elif nrow == 4: out = [Gf.Vec4f(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])), Gf.Vec4f(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1])), Gf.Vec4f(float(value[0][2]), float(value[1][2]), float(value[2][2]), float(value[3][2]))] elif ncol == 4: if nrow == 2: out = [Gf.Vec2f(float(value[0][0]), float(value[1][0])), Gf.Vec2f(float(value[0][1]), float(value[1][1])), Gf.Vec2f(float(value[0][2]), float(value[1][2])), Gf.Vec2f(float(value[0][3]), float(value[1][3]))] elif nrow == 3: out = [Gf.Vec3f(float(value[0][0]), float(value[1][0]), float(value[2][0])), Gf.Vec3f(float(value[0][1]), float(value[1][1]), float(value[2][1])), Gf.Vec3f(float(value[0][2]), float(value[1][2]), float(value[2][2])), Gf.Vec3f(float(value[0][3]), float(value[1][3]), float(value[2][3]))] elif nrow == 4: out = Gf.Matrix4d(0) out.SetColumn(0, Gf.Vec4d(float(value[0][0]), float(value[0][1]), float(value[0][2]), float(value[0][3]))) out.SetColumn(1, Gf.Vec4d(float(value[1][0]), float(value[1][1]), float(value[1][2]), float(value[1][3]))) out.SetColumn(2, Gf.Vec4d(float(value[2][0]), float(value[2][1]), float(value[2][2]), float(value[2][3]))) out.SetColumn(3, Gf.Vec4d(float(value[3][0]), float(value[3][1]), float(value[3][2]), float(value[3][3]))) elif dtype == numpy.float64: if ncol == 2: if nrow == 2: out = Gf.Matrix2d(0) out.SetColumn(0, Gf.Vec2d(float(value[0][0]), float(value[0][1]))) out.SetColumn(1, Gf.Vec2d(float(value[1][0]), float(value[1][1]))) elif nrow == 3: out = [Gf.Vec3d(float(value[0][0]), float(value[1][0]), float(value[2][0])), Gf.Vec3d(float(value[0][1]), float(value[1][1]), float(value[2][1]))] elif nrow == 4: out = [Gf.Vec4d(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])), Gf.Vec4d(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1]))] elif ncol == 3: if nrow == 2: out = [Gf.Vec2d(float(value[0][0]), float(value[1][0])), Gf.Vec2d(float(value[0][1]), float(value[1][1])), Gf.Vec2d(float(value[0][2]), float(value[1][2]))] elif nrow == 3: out = Gf.Matrix3d(0) out.SetColumn(0, Gf.Vec3d(float(value[0][0]), float(value[0][1]), float(value[0][2]))) out.SetColumn(1, Gf.Vec3d(float(value[1][0]), float(value[1][1]), float(value[1][2]))) out.SetColumn(2, Gf.Vec3d(float(value[2][0]), float(value[2][1]), float(value[2][2]))) elif nrow == 4: out = [Gf.Vec4d(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])), Gf.Vec4d(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1])), Gf.Vec4d(float(value[0][2]), float(value[1][2]), float(value[2][2]), float(value[3][2]))] elif ncol == 4: if nrow == 2: out = [Gf.Vec2d(float(value[0][0]), float(value[1][0])), Gf.Vec2d(float(value[0][1]), float(value[1][1])), Gf.Vec2d(float(value[0][2]), float(value[1][2])), Gf.Vec2d(float(value[0][3]), float(value[1][3]))] elif nrow == 3: out = [Gf.Vec3d(float(value[0][0]), float(value[1][0]), float(value[2][0])), Gf.Vec3d(float(value[0][1]), float(value[1][1]), float(value[2][1])), Gf.Vec3d(float(value[0][2]), float(value[1][2]), float(value[2][2])), Gf.Vec3d(float(value[0][3]), float(value[1][3]), float(value[2][3]))] elif nrow == 4: out = Gf.Matrix4d(0) out.SetColumn(0, Gf.Vec4d(float(value[0][0]), float(value[0][1]), float(value[0][2]), float(value[0][3]))) out.SetColumn(1, Gf.Vec4d(float(value[1][0]), float(value[1][1]), float(value[1][2]), float(value[1][3]))) out.SetColumn(2, Gf.Vec4d(float(value[2][0]), float(value[2][1]), float(value[2][2]), float(value[2][3]))) out.SetColumn(3, Gf.Vec4d(float(value[3][0]), float(value[3][1]), float(value[3][2]), float(value[3][3]))) return out def python_array_to_usd_type(value): array_simple_conversion = { bool : Sdf.ValueTypeNames.BoolArray, int : Sdf.ValueTypeNames.IntArray, # TODO: enum? # AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_ENUM, SdfValueTypeNames->IntArray); float : Sdf.ValueTypeNames.FloatArray, # TODO: double ? # AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_DOUBLE, SdfValueTypeNames->DoubleArray); str : Sdf.ValueTypeNames.StringArray, pymdlsdk.IType.Kind.TK_COLOR : Sdf.ValueTypeNames.Color3fArray # TODO: AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_STRUCT, SdfValueTypeNames->TokenArray); # TODO: AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_TEXTURE, SdfValueTypeNames->AssetArray); } array_of_vector_conversion = { numpy.bool_ : { 2 : Sdf.ValueTypeNames.Int2Array, 3 : Sdf.ValueTypeNames.Int3Array, 4 : Sdf.ValueTypeNames.Int4Array }, numpy.int32 : { 2 : Sdf.ValueTypeNames.Int2Array, 3 : Sdf.ValueTypeNames.Int3Array, 4 : Sdf.ValueTypeNames.Int4Array }, numpy.float32 : { 2 : Sdf.ValueTypeNames.Float2Array, 3 : Sdf.ValueTypeNames.Float3Array, 4 : Sdf.ValueTypeNames.Float4Array }, numpy.float64 : { 2 : Sdf.ValueTypeNames.Double2Array, 3 : Sdf.ValueTypeNames.Double3Array, 4 : Sdf.ValueTypeNames.Double4Array } } # // Array of matrix # numpyType Column Row OutType array_of_matrix = \ { numpy.float32 : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2dArray, 3 : Sdf.ValueTypeNames.FloatArray, 4 : Sdf.ValueTypeNames.FloatArray}, 3 : { 2 : Sdf.ValueTypeNames.FloatArray, 3 : Sdf.ValueTypeNames.Matrix3dArray, 4 : Sdf.ValueTypeNames.FloatArray}, 4 : { 2 : Sdf.ValueTypeNames.FloatArray, 3 : Sdf.ValueTypeNames.FloatArray, 4 : Sdf.ValueTypeNames.Matrix4dArray }}, numpy.float64 : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2dArray, 3 : Sdf.ValueTypeNames.DoubleArray, 4 : Sdf.ValueTypeNames.DoubleArray}, 3 : { 2 : Sdf.ValueTypeNames.DoubleArray, 3 : Sdf.ValueTypeNames.Matrix3dArray, 4 : Sdf.ValueTypeNames.DoubleArray}, 4 : { 2 : Sdf.ValueTypeNames.DoubleArray, 3 : Sdf.ValueTypeNames.DoubleArray, 4 : Sdf.ValueTypeNames.Matrix4dArray }}} dtype = type(value[0]) if dtype in array_simple_conversion: return array_simple_conversion[dtype] elif dtype == numpy.ndarray: shape = value[0].shape # Array if len(shape) > 1 and shape[1] > 1: # Array of matrices elemtype = type(value[0][0][0]) if elemtype in array_of_matrix: if shape[1] in array_of_matrix[elemtype]: if shape[0] in array_of_matrix[elemtype][shape[1]]: return array_of_matrix[elemtype][shape[1]][shape[0]] elif type(value[0][0]) == numpy.ndarray: # Array of vectors etype = type(value[0][0][0]) size = len(value[0]) if etype in array_of_vector_conversion: if size in array_of_vector_conversion[etype]: return array_of_vector_conversion[etype][size] else: print("Array of vector type not supported for type/size: {}/{}".format(etype, size)) elif len(value[0]) == 3: # Assume this is a color return array_simple_conversion[pymdlsdk.IType.Kind.TK_COLOR] else: print("Array type not supported for type/shape: {}/{}".format(dtype, shape)) else: print("Type not supported for type: {}".format(dtype)) def python_array_to_usd_value(value): dtype = type(value[0]) out = None if dtype == bool or \ dtype == int or \ dtype == float or \ dtype == str: return value elif dtype == numpy.ndarray: # Array shape = value[0].shape if len(shape) > 1 and shape[1] > 1: # Array of matrices elemtype = type(value[0][0][0]) nrow = shape[0] ncol = shape[1] out = None arraysize = len(value) if ncol == nrow: if ncol == 2: mattype = Gf.Matrix2d if ncol == 3: mattype = Gf.Matrix3d if ncol == 4: mattype = Gf.Matrix4d out = [] for i in range(arraysize): mat = mattype(0) for c in range(ncol): row = [] for r in range(nrow): row.append(float(value[i][c][r])) mat.SetColumn(c, row) out.append(mat) else: if elemtype == numpy.float32: otype = float elif elemtype == numpy.float64: otype = numpy.float64 out = [] for i in range(arraysize): for c in range(ncol): for r in range(nrow): out.append(otype(value[i][r][c])) elif type(value[0][0]) == numpy.ndarray: # Array of vectors etype = type(value[0][0][0]) size = len(value) out = [] if etype == numpy.bool_ or \ etype == numpy.int32: otype = int elif etype == numpy.float32: otype = float elif etype == numpy.float64: otype = numpy.float64 itemsize = len(value[0]) for i in range(size): ll = [] for j in range(itemsize): ll.append(otype(value[i][j])) out.append(ll) elif len(value[0]) == 3: # Assume this is a color size = len(value) out = [] for i in range(size): out.append([value[0][0], value[0][1], value[0][2]]) return out def custom_data_from_python_array(value): # type = dict({"mdl":{"type" : "array of matrix"}}) out = dict() dtype = type(value[0]) arraysize = len(value) if dtype == numpy.ndarray: # Array shape = value[0].shape if len(shape) > 1 and shape[1] > 1: # Array of matrices elemtype = type(value[0][0][0]) nrow = shape[0] ncol = shape[1] elemtype = type(value[0][0][0]) if ncol != nrow or elemtype == numpy.float32: # Non square matrices typename = "" if elemtype == numpy.float32: typename = "float" elif elemtype == numpy.float64: typename = "double" out = dict({"mdl":{"type" : "{}{}x{}[{}]".format(typename, ncol, nrow, arraysize)}}) elif type(value[0][0]) == numpy.ndarray: # Array of vectors etype = type(value[0][0][0]) if etype == numpy.bool_: itemsize = len(value[0]) out = dict({"mdl":{"type" : "bool{}[{}]".format(itemsize, arraysize)}}) return out def mdl_type_to_usd_type(val : pymdl.ArgumentConstant): if not val: return None kind = val.type.kind if kind in MdlITypeKindToUSD: return MdlITypeKindToUSD[kind] else: # A bit more work is required to derive the type if kind == pymdlsdk.IType.Kind.TK_VECTOR: return python_vector_to_usd_type(val.value.dtype, val.value.size) elif kind == pymdlsdk.IType.Kind.TK_MATRIX: return python_matrix_to_usd_type(val.value.dtype, val.value.shape[0], val.value.shape[1]) elif kind == pymdlsdk.IType.Kind.TK_ARRAY: return python_array_to_usd_type(val.value) return None class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def top(self): return self.items[len(self.items)-1] def size(self): return len(self.items) # When converting from MDL to USD user can choose the USD output format # SHADER: A single shader is output at the root of the USD Stage # MATERIAL: A single material is output at the root of the USD Stage # MATERIAL_AND_GEOMETRY: Geometry and Material (bound to the geometry) are output in the USD Stage class OutputType(Enum): SHADER = 1 MATERIAL = 2 MATERIAL_AND_GEOMETRY = 3 class ConverterContext(): def __init__(self): self.neuray = None self.transaction = None self.stage = None self.modules = Stack() self.usd_materials = Stack() self.parameter_names = Stack() self.usd_shaders = Stack() self.custom_data = Stack() self.type_annotation = True self.mdl_to_usd_output = OutputType.SHADER self.mdl_to_usd_output_material_nested_shaders = False # Nested/deep or flat shader tree self.ov_neuray = None GetUniqueNameInStage.s_uniqueID = 0 # Reset the unique name counter to get same output between 2 runs def enable_type_annotation(self): self.type_annotation = True def disable_type_annotation(self): self.type_annotation = False def is_type_annotation_enabled(self): return self.type_annotation == True def set_neuray(self, neuray): self.neuray = neuray def set_transaction(self, transaction): self.transaction = transaction def set_stage(self, stage): self.stage = stage def push_module(self, module): self.modules.push(module) def pop_module(self): return self.modules.pop() def current_module(self): return self.modules.top() def push_usd_material(self, material): self.usd_materials.push(material) def pop_usd_material(self): return self.usd_materials.pop() def current_usd_material(self): return self.usd_materials.top() def push_parameter_name(self, parm): self.parameter_names.push(parm) def pop_parameter_name(self): return self.parameter_names.pop() def current_parameter_name(self): return self.parameter_names.top() def push_usd_shader(self, shader): self.usd_shaders.push(shader) def pop_usd_shader(self): return self.usd_shaders.pop() def current_usd_shader(self): return self.usd_shaders.top() def push_custom_data(self, custom_data): self.custom_data.push(custom_data) def pop_custom_data(self): return self.custom_data.pop() def current_custom_data(self): return self.custom_data.top() # Example: 'mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase' # Return: 'OmniSurface/OmniSurfaceBase.mdl' def prototype_to_source_asset(prototype): source_asset = prototype if source_asset[:5] == "mdl::": source_asset = source_asset[3:] # Remove leading "mdl" if source_asset[:2] == "::": source_asset = source_asset[2:] # Remove leading "::" ll = source_asset.split("::") source_asset = '/'.join(ll[0:-1]) # Drop last part which is material name source_asset = source_asset + ".mdl" # Append ".mdl" extension return source_asset def module_mdl_name_to_source_asset(context, module_mdl_name): # Hack to convert builtin module functions if module_mdl_name == '::scene' or module_mdl_name == '::state': return 'nvidia/support_definitions.mdl' unmangle_helper = UnmangleAndFixMDLSearchPath(context) (isMangled, wasSuccess, newmodule_mdl_name) = unmangle_helper.unmangle_mdl_module(module_mdl_name) if wasSuccess and newmodule_mdl_name != module_mdl_name: return newmodule_mdl_name + '.mdl' if isMangled and not wasSuccess: # Better return empty asset than garbage asset return '' source_asset = module_mdl_name if source_asset[:5] == "mdl::": source_asset = source_asset[3:] # Remove leading "mdl" if source_asset[:2] == "::": source_asset = source_asset[2:] # Remove leading "::" source_asset = source_asset.replace("::", "/") # Replace "::" with "/" source_asset = source_asset + ".mdl" # Append ".mdl" extension return source_asset def source_asset_to_module_name(source_asset, context): module_name = source_asset module_name = os.path.normpath(module_name) if os.path.isabs(module_name): # Absolute path, try to find a mathing search path and remove it with context.neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg: if cfg.is_valid_interface(): for i in range(cfg.get_mdl_paths_length()): sp = cfg.get_mdl_path(i) sp = os.path.normpath(sp.get_c_str()) if module_name.find(sp) == 0: module_name = module_name[len(sp):] break # Split path ll = module_name.split(os.sep) # Concat path using '::' separator module_name = "::".join(ll) if not module_name[0:2] == "::": # Prepend '::' module_name = "::" + module_name if module_name[-4:] == ".mdl": # Remove '.mdl' extension module_name = module_name[0:-4] return module_name def db_name_to_prim_name(dbname): name = dbname name = name.split("(")[0] # Remove arguments name = name.split("::")[-1] # Remove package, module name = name.replace(".", "_") # Replace '.' return name def mdl_name_to_sub_identifier(mdl_name, fct_call=False): sub_id = mdl_name if sub_id[:5] == "mdl::": sub_id = sub_id[3:] # Remove leading "mdl" # split the identifier from the arguments names = sub_id.split("(") # keep only the last name from the identifier sub_id = names[0].split("::")[-1] if fct_call: # concat with args if len(names) > 1: sub_id = sub_id + "(" + names[1] return sub_id # Return a unique SdfPath for the current stage class GetUniqueNameInStage: s_uniqueID = 0 @staticmethod def get(stage, path): unique_path = path while stage.GetPrimAtPath(unique_path).IsValid(): unique_path = Sdf.Path(str(path) + str(GetUniqueNameInStage.s_uniqueID)) GetUniqueNameInStage.s_uniqueID += 1 return unique_path class GetUniqueName: s_uniqueID = 0 @staticmethod def get(transaction, prefix_in): prefix = prefix_in if len(prefix)==0: prefix = "elt" if not transaction.access_as(pymdlsdk.IInterface, prefix).is_valid_interface(): return prefix while True: prefix = prefix_in + "_" + str(GetUniqueName.s_uniqueID) GetUniqueName.s_uniqueID += 1 if not transaction.access_as(pymdlsdk.IInterface, prefix).is_valid_interface(): return prefix def create_stage(args): stageName = args.options["OUT"] stage = Usd.Stage.CreateNew(stageName) stage.SetMetadata('comment', 'MDL to USD conversion') return stage def load_stage(stageName): stage = None try: stage = Usd.Stage.Open(stageName) except: print("Error:\tFailed to load stage: {}".format(stageName)) return stage def save_stage(stage): stage.GetRootLayer().Save() def export_stage(stage, filename): stage.GetRootLayer().Export(filename) def material_to_stage_output_material(context, function: pymdl.FunctionDefinition): return material_to_stage_output_material_and_geo(context, function, want_geometry = False) def material_to_stage_output_material_and_geo(context, function: pymdl.FunctionDefinition, want_geometry = True): neuray = context.neuray transaction = context.transaction stage = context.stage db_name = function.dbName materialName = db_name_to_prim_name(db_name) # Start at root rootPath = Sdf.Path('/') spherePrim = None if want_geometry: xform = UsdGeom.Xform.Define(stage,"/World") # Add geometry spherePrim = UsdGeom.Sphere.Define(stage, xform.GetPath().AppendChild('Geom')) model = Usd.ModelAPI(xform) model.SetKind(Kind.Tokens.component) # Create Looks scope # Scope is the simplest grouping primitive... scope = UsdGeom.Scope.Define(stage, xform.GetPath().AppendChild('Looks')) rootPath = scope.GetPath() model = Usd.ModelAPI(scope) model.SetKind(Kind.Tokens.model) material = None # Create material material = UsdShade.Material.Define(stage, rootPath.AppendChild(materialName)) if spherePrim != None: # Bind material to geometry UsdShade.MaterialBindingAPI(spherePrim).Bind(material) # Create surface shader surfaceShader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("Shader")) # Create surface shader output port outPort = surfaceShader.CreateOutput('out', Sdf.ValueTypeNames.Token) # Create material output port terminal = material.CreateOutput('mdl:surface', Sdf.ValueTypeNames.Token) # Connect material output to shader output terminal.ConnectToSource(outPort) terminal = material.CreateOutput('mdl:volume', Sdf.ValueTypeNames.Token) terminal.ConnectToSource(outPort) terminal = material.CreateOutput('mdl:displacement', Sdf.ValueTypeNames.Token) terminal.ConnectToSource(outPort) # Determine module asset module_interface : pymdl.Module module_interface = context.current_module() module = module_interface.mdlName source_asset = module_mdl_name_to_source_asset(context, module) # Example: # uniform token info:implementationSource = "sourceAsset" # uniform asset info:mdl:sourceAsset = @nvidia/core_definitions.mdl@ # uniform token info:mdl:sourceAsset:subIdentifier = "::nvidia::core_definitions::flex_material" surfaceShader.GetImplementationSourceAttr().Set("sourceAsset") surfaceShader.SetSourceAsset(Sdf.AssetPath(source_asset), "mdl") node_identifier = mdl_name_to_sub_identifier(db_name) surfaceShader.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier) context.stage.SetDefaultPrim(material.GetPrim()) context.push_usd_material(material) context.push_usd_shader(surfaceShader) context.push_custom_data(dict()) definition_to_stage(context, function) # Annotations anno_dict = get_annotations_dict(context, function) add_annotations_to_prim(surfaceShader.GetPrim(), anno_dict) add_annotations_to_node(surfaceShader, anno_dict) context.pop_custom_data() context.pop_usd_shader() context.pop_usd_material() def material_to_stage_output_shader(context, function: pymdl.FunctionDefinition): neuray = context.neuray transaction = context.transaction stage = context.stage db_name = function.dbName materialName = db_name_to_prim_name(db_name) # Start at root rootPath = Sdf.Path('/') material = UsdShade.Shader.Define(stage, rootPath.AppendChild(materialName)) # Create output port outPort = material.CreateOutput('out', Sdf.ValueTypeNames.Token).SetRenderType("material") # Determine module asset module_interface : pymdl.Module module_interface = context.current_module() module = module_interface.mdlName source_asset = module_mdl_name_to_source_asset(context, module) # Example: # uniform token info:implementationSource = "sourceAsset" # uniform asset info:mdl:sourceAsset = @nvidia/core_definitions.mdl@ # uniform token info:mdl:sourceAsset:subIdentifier = "::nvidia::core_definitions::flex_material" material.GetImplementationSourceAttr().Set("sourceAsset") material.SetSourceAsset(Sdf.AssetPath(source_asset), "mdl") node_identifier = mdl_name_to_sub_identifier(db_name) material.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier) context.stage.SetDefaultPrim(material.GetPrim()) context.push_usd_material(material) context.push_usd_shader(material) context.push_custom_data(dict()) definition_to_stage(context, function) # Annotations anno_dict = get_annotations_dict(context, function) add_annotations_to_prim(material.GetPrim(), anno_dict) add_annotations_to_node(material, anno_dict) context.pop_custom_data() context.pop_usd_shader() context.pop_usd_material() def material_to_stage(context, function: pymdl.FunctionDefinition): if context.mdl_to_usd_output == OutputType.SHADER: return material_to_stage_output_shader(context, function) elif context.mdl_to_usd_output == OutputType.MATERIAL: return material_to_stage_output_material(context, function) elif context.mdl_to_usd_output == OutputType.MATERIAL_AND_GEOMETRY: return material_to_stage_output_material_and_geo(context, function) def module_to_stage(context, module: pymdl.Module): context.push_module(module) for simple_name, overloads in module.functions.items(): f: pymdl.FunctionDefinition for f in overloads: material_to_stage(context, f) anno_dict = get_annotations_dict(context, module) add_annotations_to_stage(context, context.stage, anno_dict) context.pop_module() def mdl_prim_to_usd(context : ConverterContext, stage: Usd.Stage, prim: Usd.Prim, createNewMaterial: bool = False): inst_name = None mdl_entity = None mdl_entity_snapshot = None if context.ov_neuray == None: return # Get the shader prim from Material shader_prim = get_shader_prim(context.stage, prim.GetPath()) mdl_entity = context.ov_neuray.createMdlEntity(shader_prim.GetPath().pathString) mdl_entity_snapshot = None if not mdl_entity.getMdlModule() == None: mdl_entity_snapshot = context.ov_neuray.createMdlEntitySnapshot(mdl_entity) inst_name = mdl_entity_snapshot.dbName source_asset = Sdf.AssetPath("") shader = UsdShade.Shader(shader_prim) if shader: imp_source = shader.GetImplementationSourceAttr().Get() if imp_source == "sourceAsset": # Retrieve module name source_asset = shader.GetSourceAsset("mdl") material = UsdShade.Material(prim) if createNewMaterial: rootPath = Sdf.Path(prim.GetPath().GetParentPath()) # Create material materialName = prim.GetName() + "_converted" # Find unique name materialName = GetUniqueNameInStage.get(stage, rootPath.AppendChild(materialName)) material = UsdShade.Material.Define(stage, materialName) # Create surface shader surfaceShader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild(shader_prim.GetName())) # Create output port outPort = surfaceShader.CreateOutput('out', Sdf.ValueTypeNames.Token) # Create material output port terminal = material.CreateOutput('mdl:surface', Sdf.ValueTypeNames.Token) # Connect material output to shader output terminal.ConnectToSource(outPort) terminal = material.CreateOutput('mdl:volume', Sdf.ValueTypeNames.Token) terminal.ConnectToSource(outPort) terminal = material.CreateOutput('mdl:displacement', Sdf.ValueTypeNames.Token) terminal.ConnectToSource(outPort) context.push_usd_material(material) context.push_usd_shader(surfaceShader) context.push_custom_data(dict()) fctCall = pymdl.FunctionCall._fetchFromDb(context.transaction, inst_name) handle_function_call(context, fctCall) context.pop_usd_material() context.pop_usd_shader() context.pop_custom_data() if not mdl_entity_snapshot == None: context.ov_neuray.destroyMdlEntitySnapshot(mdl_entity_snapshot) if not mdl_entity == None: context.ov_neuray.destroyMdlEntity(mdl_entity) #-------------------------------------------------------------------------------------------------- # Utilities #-------------------------------------------------------------------------------------------------- def get_examples_search_path(): """Try to get the example search path or returns 'mdl' sub folder of the current directory if it failed.""" # get the environment variable that is used in all MDL SDK examples example_sp = os.getenv('MDL_SAMPLES_ROOT') # fall back to a path relative to this script file if example_sp == None or not os.path.exists(example_sp): example_sp = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') # go down into the mdl folder example_sp = os.path.join(example_sp, 'mdl') # fall back to the current folder if not os.path.exists(example_sp): example_sp = './mdl' return os.path.abspath(example_sp) #-------------------------------------------------------------------------------------------------- # MDL Python Example #-------------------------------------------------------------------------------------------------- # return usd_value, connection, usd_type def get_usd_value_and_type(context, val : pymdl.ArgumentConstant): if not val: return (None, None, None) kind = val.type.kind usd_type = mdl_type_to_usd_type(val) if usd_type == None: return (None, None, None) usd_val = None connection = None # -------------------------------- Atomic --------------------------------- if kind == pymdlsdk.IType.Kind.TK_BOOL or \ kind == pymdlsdk.IType.Kind.TK_INT or \ kind == pymdlsdk.IType.Kind.TK_FLOAT or \ kind == pymdlsdk.IType.Kind.TK_DOUBLE or \ kind == pymdlsdk.IType.Kind.TK_STRING: usd_val = val.value elif kind == pymdlsdk.IType.Kind.TK_ENUM: usd_val = val.value[1] # -------------------------------- Compound --------------------------------- elif kind == pymdlsdk.IType.Kind.TK_VECTOR: usd_val = python_vector_to_usd_value(val.value) if context.is_type_annotation_enabled(): custom_data = custom_data_from_python_vector(val.value) context.current_custom_data().update(custom_data) elif kind == pymdlsdk.IType.Kind.TK_MATRIX: usd_val = python_matrix_to_usd_value(val.value) elif kind == pymdlsdk.IType.Kind.TK_COLOR: usd_val = Gf.Vec3f(val.value[0], val.value[1], val.value[2]) elif kind == pymdlsdk.IType.Kind.TK_ARRAY: usd_val = python_array_to_usd_value(val.value) if context.is_type_annotation_enabled(): custom_data = custom_data_from_python_array(val.value) context.current_custom_data().update(custom_data) elif kind == pymdlsdk.IType.Kind.TK_STRUCT: parm_name = context.current_parameter_name() shader = context.current_usd_shader() usd_mat = context.current_usd_shader() new_shader = UsdShade.Shader.Define(context.stage, GetUniqueNameInStage.get(context.stage, usd_mat.GetPath().AppendChild("ShaderAttachement_" + parm_name))) connection = new_shader.CreateOutput('out', Sdf.ValueTypeNames.Token) context.push_usd_shader(new_shader) for item in val.value: field_name = item context.push_parameter_name(field_name) context.push_custom_data(dict()) v = val.value[item] handle_value(context, v) context.pop_custom_data() context.pop_parameter_name() context.pop_usd_shader() # -------------------------------- Resource --------------------------------- elif kind == pymdlsdk.IType.Kind.TK_TEXTURE: ftex = val.value[0] gamma = val.value[1] with context.transaction.access_as(pymdlsdk.ITexture, ftex) as text: if text.is_valid_interface(): with context.transaction.access_as(pymdlsdk.IImage, text.get_image()) as image: if image.is_valid_interface(): usd_val = image.get_filename(0,0) elif kind == pymdlsdk.IType.Kind.TK_LIGHT_PROFILE: v = val.value with context.transaction.access_as(pymdlsdk.ILightprofile, v) as obj: if obj.is_valid_interface(): usd_val = obj.get_filename() elif kind == pymdlsdk.IType.Kind.TK_BSDF_MEASUREMENT: v = val.value with context.transaction.access_as(pymdlsdk.IBsdf_measurement, v) as obj: if obj.is_valid_interface(): usd_val = obj.get_filename() else: print("Error: Unknown IValue Kind for parm/kind: {}/{}".format(context.current_parameter_name(), kind)) return (usd_val, connection, usd_type) def dict_of_dicts_merge(x, y): z = {} overlapping_keys = x.keys() & y.keys() for key in overlapping_keys: z[key] = dict_of_dicts_merge(x[key], y[key]) for key in x.keys() - overlapping_keys: z[key] = deepcopy(x[key]) for key in y.keys() - overlapping_keys: z[key] = deepcopy(y[key]) return z # Return a dictionary of pair [string, value] # def get_annotations_dict(context, val): main_dict = dict() # We do not want to collect type annotations during conversion of annotation expressions # Otherwise the type for the annotations is mized with the parameter annotations context.disable_type_annotation() try: # Handle annotations if val.annotations: anno_dict = dict() # print(f" Annotations:") anno: pymdl.Annotation for anno in val.annotations: # print(f" - Simple Name: {anno.simpleName}") # print(f" Qualified Name: {anno.name}") # // Special case of annotations without expressions, e.g. ::anno::hidden() # // We create a boolean VtValue and set it to true # // Annotation: # // ::anno::hidden() # // becomes: # // bool "::anno::hidden()" = 1 if len(anno.arguments.items()) == 0: usd_value = True usd_type = bool anno_dict[anno.name] = usd_value arg: pymdl.val for arg_name, arg in anno.arguments.items(): # print(f" ({arg.type.kind}) {arg_name}: {arg.value}") (usd_value, connection, usd_type) = get_usd_value_and_type(context, arg) # print(f" ({usd_value}) {connection}: {usd_type}") if usd_value != None and usd_type != None: anno_dict[anno.name+"::"+arg_name] = usd_value if len(anno_dict) > 0: main_dict.update(dict({"mdl" : {"annotations": anno_dict}})) # Handle special values, concat (possibly empty) context dictionary main_dict = dict_of_dicts_merge(main_dict, context.current_custom_data()) except Exception as e: print("Error while retrieving annotations") finally: context.enable_type_annotation() return main_dict def add_annotations_to_stage(context, stage, anno_dict): try: if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]: stage.SetMetadata('comment', 'Conversion from MDL module: ' + anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"]) else: if context.current_module() != None: stage.SetMetadata('comment', 'Conversion from MDL module: ' + context.current_module().mdlName) # TODO: Add more annotations to Stage as Metadata: version, ... except: pass def add_annotations_to_node(node, anno_dict): # display name, group and description # # sdrMetadata = { # dictionary ui = { # string displayGroup = "float2_parm group" # } # } # if "mdl" in anno_dict and "annotations" in anno_dict["mdl"]: for anno, key in ( \ ("::anno::display_name(string)::name", "ui:displayName"), \ ("::anno::in_group(string)::group", "ui:displayGroup"), \ ("::anno::in_group(string,string)::group", "ui:displayGroup"), \ ("::anno::in_group(string,string,string)::group", "ui:displayGroup"), \ ("::anno::description(string)::description", "ui:description")): if anno in anno_dict["mdl"]["annotations"]: node.SetSdrMetadataByKey( key, anno_dict["mdl"]["annotations"][anno]) # # See Also: # # ui = Usd.SceneGraphPrimAPI(minput.GetAttr()) # a = ui.CreateDisplayNameAttr() # # TODO: Could also use? # # minput.GetAttr().SetDisplayName("FOOBAR") # minput.GetAttr().SetDisplayGroup("GROUP") try: if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]: node.GetAttr().SetDisplayName(anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"]) for anno in ( \ "::anno::in_group(string)::group", \ "::anno::in_group(string,string)::group", \ "::anno::in_group(string,string,string)::group" \ ): if anno in anno_dict["mdl"]["annotations"]: node.GetAttr().SetDisplayGroup(anno_dict["mdl"]["annotations"][anno]) except: pass def add_annotations_to_prim(usd_prim, anno_dict): if len(anno_dict) > 0: cd = usd_prim.GetCustomData() cd.update(anno_dict) usd_prim.SetCustomData(cd) try: ui = UsdUI.UsdUIBackdrop(usd_prim) if "::anno::description(string)::description" in anno_dict["mdl"]["annotations"]: ui.CreateDescriptionAttr(anno_dict["mdl"]["annotations"]["::anno::description(string)::description"]) except: pass try: ui = UsdUI.SceneGraphPrimAPI(usd_prim) if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]: ui.CreateDisplayNameAttr(anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"]) for anno in ( \ "::anno::in_group(string)::group", \ "::anno::in_group(string,string)::group", \ "::anno::in_group(string,string,string)::group" \ ): if anno in anno_dict["mdl"]["annotations"]: ui.CreateDisplayGroupAttr(anno_dict["mdl"]["annotations"][anno]) except: pass # Hidden if "mdl" in anno_dict and "annotations" in anno_dict["mdl"]: if "::anno::hidden()" in anno_dict["mdl"]["annotations"]: if anno_dict["mdl"]["annotations"]["::anno::hidden()"]: usd_prim.SetHidden(True) def handle_value(context, val : pymdl.ArgumentConstant): if not val: return (usd_value, connection, usd_type) = get_usd_value_and_type(context, val) if (usd_value == None and connection == None) or usd_type == None: return parm_name = context.current_parameter_name() shader = context.current_usd_shader() minput = shader.CreateInput(parm_name, usd_type) if usd_value != None: minput.Set(usd_value) else: minput.ConnectToSource(connection) anno_dict = get_annotations_dict(context, val) add_annotations_to_prim(minput.GetAttr(), anno_dict) add_annotations_to_node(minput, anno_dict) if val.type.kind == pymdlsdk.IType.Kind.TK_ENUM: minput.SetRenderType(val.type.symbol) def handle_expression_constant(context, expression_constant : pymdl.ArgumentConstant): if not expression_constant: return handle_value(context, expression_constant) def handle_function_call(context, function_call : pymdl.FunctionCall): if not function_call: return # print("* Function definition: {}".format(function_call.functionDefinition)) # print("* MDL function definition: {}".format(function_call.mdlFunctionDefinition)) # print("* Parameter count: {}".format(len(function_call.parameters))) fdef_db_name = function_call.functionDefinition function_def = pymdl.FunctionDefinition._fetchFromDb(context.transaction, fdef_db_name) if not function_def: return sourceAsset = module_mdl_name_to_source_asset(context, function_def.mdlModuleName) node_identifier = mdl_name_to_sub_identifier( function_def.mdlName, True ) # Determine if function definition is variant fctdef = context.transaction.access_as(pymdlsdk.IFunction_definition, function_def.dbName) prototype = fctdef.get_prototype() if prototype: node_identifier = mdl_name_to_sub_identifier(prototype) sourceAsset = prototype_to_source_asset(prototype) shader = context.current_usd_shader() shader.GetImplementationSourceAttr().Set("sourceAsset") shader.SetSourceAsset(Sdf.AssetPath(sourceAsset), "mdl") shader.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier) for name, argument in function_call.parameters.items(): # print(f"* Name: {name}") # print(f" Type: {argument.type.kind}") # if argument.type.symbol: # print(f" Type Symbol: {argument.type.symbol}") # print(f" Value: {argument.value}") # print(f" Value is Constant: {isinstance(argument, pymdl.ArgumentConstant)}") # print(f" Value is Attachment: {isinstance(argument, pymdl.ArgumentCall)}") context.push_parameter_name(name) context.push_custom_data(dict()) handle_expression(context, argument) context.pop_custom_data() context.pop_parameter_name() def handle_material_instance(context, minst): if not minst.is_valid_interface(): return pass def handle_expression_call(context, expression_call : pymdl.ArgumentCall): if not expression_call: return neuray = context.neuray transaction = context.transaction # NEW fcall : pymdl.FunctionCall fcall = pymdl.FunctionCall._fetchFromDb(transaction, expression_call.value) if fcall: handle_function_call(context, fcall) return # TODO? # minst = transaction.access_as(pymdlsdk.IFunction_call, expression_call.get_call()) # if minst.is_valid_interface(): # handle_material_instance(context, minst) def handle_expression_parameter(context, expression_parameter): if not expression_parameter.is_valid_interface(): return pass def handle_expression_direct_call(context, expression_direct_call): if not expression_direct_call.is_valid_interface(): return pass def handle_expression_temporary(context, expression_temporary): if not expression_temporary.is_valid_interface(): return pass def handle_expression(context, argument : pymdl.Argument): if not argument: return if isinstance(argument, pymdl.ArgumentConstant): # A constant expression. See #mi::neuraylib::IExpression_constant. # argument_cst = pymdl.ArgumentConstant(argument) # FAILS argument_cst : pymdl.ArgumentConstant argument_cst = argument handle_expression_constant(context, argument_cst) elif isinstance(argument, pymdl.ArgumentCall): # Need to: # - create a parameter of the given type # - create a new shader in the current material # - Connect the parameter to the new shader # - Evaluate the expression expression_kind = argument.type.kind # If the exact return type can not be determined (e.g. vectors, where to get the size?) set the parm type to Token by default parm_type = Sdf.ValueTypeNames.Token parm_name = context.current_parameter_name() if expression_kind in MdlITypeKindToUSD: parm_type = MdlITypeKindToUSD[expression_kind] else: print("Warning: Indirect call expression parm/kind : {}/{}".format(parm_name,argument.type.kind)) # - create a parameter of the given type usd_shader = context.current_usd_shader() minput = usd_shader.CreateInput(parm_name, parm_type) # By default shaders are not nested, they are created immediately under the material usd_mat = context.current_usd_material() if context.mdl_to_usd_output_material_nested_shaders == True: # Nested shaders case, create under current shader usd_mat = context.current_usd_shader() # - create a new shader in thecurrent material (or current shader in the nested case) shName = GetUniqueNameInStage.get(context.stage, usd_mat.GetPath().AppendChild(parm_name)) shader = UsdShade.Shader.Define(context.stage, shName) outPort = shader.CreateOutput('out', Sdf.ValueTypeNames.Token) # - Connect the parameter to the new shader minput.ConnectToSource(outPort) context.push_usd_shader(shader) # - Evaluate the expression argument_call : pymdl.ArgumentCall argument_call = argument handle_expression_call(context, argument_call) # Annotations anno_dict = get_annotations_dict(context, argument_call) add_annotations_to_prim(minput.GetAttr(), anno_dict) add_annotations_to_node(minput, anno_dict) context.pop_usd_shader() # TODO # elif kind == pymdlsdk.IExpression.Kind.EK_PARAMETER: # # A parameter reference expression. See #mi::neuraylib::IExpression_parameter. # # handle_expression_parameter(context, expression.get_interface(pymdlsdk.IExpression_parameter)) # pass # elif kind == pymdlsdk.IExpression.Kind.EK_DIRECT_CALL: # # A direct call expression. See #mi::neuraylib::IExpression_direct_call. # # handle_expression_direct_call(context, expression.get_interface(pymdlsdk.IExpression_direct_call)) # pass # elif kind == pymdlsdk.IExpression.Kind.EK_TEMPORARY: # # A temporary reference expression. See #mi::neuraylib::IExpression_temporary. # # handle_expression_temporary(context, expression.get_interface(pymdlsdk.IExpression_temporary)) # pass def definition_to_stage(context, function: pymdl.FunctionDefinition): neuray = context.neuray transaction = context.transaction argument: pymdl.Argument for name, argument in function.parameters.items(): # print(f"* Name: {name}") # print(f" Type: {argument.type.kind}") # if argument.type.symbol: # print(f" Type Symbol: {argument.type.symbol}") # print(f" Value: {argument.value}") # print(f" Value is Constant: {isinstance(argument, pymdl.ArgumentConstant)}") # print(f" Value is Attachment: {isinstance(argument, pymdl.ArgumentCall)}") context.push_parameter_name(name) context.push_custom_data(dict()) handle_expression(context, argument) context.pop_custom_data() context.pop_parameter_name() def get_db_module_name(neuray, module_mdl_name): """Return the db name of the given module.""" module_db_name = None # When the module is loaded we can access it and all its definitions by accessing the DB # for that we need to get a the database name of the module using the factory with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory: with factory.get_db_module_name(module_mdl_name) as istring: if istring.is_valid_interface(): module_db_name = istring.get_c_str() # note, even though this name simple and could # be constructed by string operations, use the # factory to be save in case of unicode encodings # and potential upcoming changes in the future # # shortcut for the function above # # this chaining is a bit special. In the C++ interface it's not possible without # # leaking memory. Here we create the smart pointer automatically. However, the IString # # which is created temporay here is released at the end the `load_module` function, right? # # This might be unexpected, especially when we rely on the RAII pattern and that # # objects are disposed at certain points in time (usually before committing a transaction) # module_db_name_2 = factory.get_db_module_name(module_mdl_name).get_c_str() # # note, we plan to map compatible types to python. E.g. the IString class may disappear # return module_db_name_2 return module_db_name #-------------------------------------------------------------------------------------------------- def get_db_definition_name(neuray, function_mdl_name): """Return the db name of the given function definition.""" with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory: with factory.get_db_definition_name(function_mdl_name) as istring: if istring.is_valid_interface(): return istring.get_c_str() return None #-------------------------------------------------------------------------------------------------- def load_module(context, source_asset): success = False module_db_name = "" if not context.ov_neuray == None: # We are in OV if context.transaction: context.transaction.commit() context.transaction = None module_db_name = load_module_from_ov(context.ov_neuray, source_asset.path) dbScopeName = "rtx_scope" rtxTransactionReadHandle = context.ov_neuray.createReadingTransaction(dbScopeName) context.transaction: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(rtxTransactionReadHandle) module = pymdl.Module._fetchFromDb(context.transaction, module_db_name) success = (not module == None) else: module_mdl_name = source_asset_to_module_name(source_asset.path, context) success = load_module_from_neuray(context.neuray, context.transaction, module_mdl_name) if success: module_db_name = get_db_module_name(context.neuray, module_mdl_name) module = pymdl.Module._fetchFromDb(context.transaction, module_db_name) print(f'Loaded module (from omni.mdl.neuraylib={context.ov_neuray} / source asset={source_asset}): {module.filename}') return (success, module_db_name) #-------------------------------------------------------------------------------------------------- def load_module_from_neuray(neuray, transaction, module_mdl_name): """Load the module given its name. Returns true if the module is loaded to database""" with neuray.get_api_component(pymdlsdk.IMdl_impexp_api) as imp_exp: with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory: # for illustation, we don't use a `with` block for the `context`, instead we release manually context = factory.create_execution_context() res = imp_exp.load_module(transaction, module_mdl_name, context) context.release() return res >= 0 #-------------------------------------------------------------------------------------------------- def load_module_from_ov(rtxneuray, module_path): """Load the module given its name. Returns rtxModule.dbName if the module is loaded to database, otherwise return empty string """ rtxModule = None try: rtxModule = rtxneuray.createMdlModule(module_path) except: return "" return rtxModule.dbName #-------------------------------------------------------------------------------------------------- class ConvertVectorAndArray: def create_type_or_value(self, usd_type, factory): if usd_type in (\ Sdf.ValueTypeNames.Float2,\ Sdf.ValueTypeNames.Float2Array,\ Sdf.ValueTypeNames.Float3,\ Sdf.ValueTypeNames.Float3Array,\ Sdf.ValueTypeNames.Float4,\ Sdf.ValueTypeNames.Float4Array,\ Sdf.ValueTypeNames.FloatArray): return factory.create_float() elif usd_type in (\ Sdf.ValueTypeNames.Int2,\ Sdf.ValueTypeNames.Int2Array,\ Sdf.ValueTypeNames.Int3,\ Sdf.ValueTypeNames.Int3Array,\ Sdf.ValueTypeNames.Int4,\ Sdf.ValueTypeNames.Int4Array,\ Sdf.ValueTypeNames.IntArray): return factory.create_int() elif usd_type in (\ Sdf.ValueTypeNames.Double2,\ Sdf.ValueTypeNames.Double2Array,\ Sdf.ValueTypeNames.Double3,\ Sdf.ValueTypeNames.Double3Array,\ Sdf.ValueTypeNames.Double4,\ Sdf.ValueTypeNames.Double4Array,\ Sdf.ValueTypeNames.DoubleArray,\ Sdf.ValueTypeNames.Matrix2d,\ Sdf.ValueTypeNames.Matrix3d,\ Sdf.ValueTypeNames.Matrix4d): return factory.create_double() elif usd_type == Sdf.ValueTypeNames.BoolArray: return factory.create_bool() elif usd_type == Sdf.ValueTypeNames.StringArray: return factory.create_string() return None def convert(self, input, usd_type, type_factory, value_factory, expression_factory): value = input.Get() if value == None: return None if usd_type == Sdf.ValueTypeNames.Color3fArray: value = input.Get() array_size = len(value) vector_size = len(value[0]) assert(vector_size == 3) atomic_type = type_factory.create_color() if not atomic_type.is_valid_interface(): return None array_type = type_factory.create_immediate_sized_array(atomic_type, array_size) mdl_value_array = value_factory.create_array(array_type) mdl_value_array.set_size(array_size) for index in range(array_size): usd_value = value[index] atomic_value = value_factory.create_color(usd_value[0],usd_value[1],usd_value[2]) mdl_value_array.set_value(index, atomic_value) expression = expression_factory.create_constant(mdl_value_array) return expression elif usd_type == Sdf.ValueTypeNames.StringArray: value = input.Get() array_size = len(value) atomic_type = type_factory.create_string() if not atomic_type.is_valid_interface(): return None array_type = type_factory.create_immediate_sized_array(atomic_type, array_size) mdl_value_array = value_factory.create_array(array_type) mdl_value_array.set_size(array_size) for index in range(array_size): usd_value = value[index] atomic_value = value_factory.create_string() atomic_value.set_value(usd_value) mdl_value_array.set_value(index, atomic_value) expression = expression_factory.create_constant(mdl_value_array) return expression elif numpy.isscalar(value[0]): # Vector vector_size = len(value) type = self.create_type_or_value(usd_type, type_factory) if not type.is_valid_interface(): return None vector_type = type_factory.create_vector(type, vector_size) if not vector_type.is_valid_interface(): return None mdl_value_vector = value_factory.create_vector(vector_type) for index in range(vector_size): usd_value = value[index] atomic_value = self.create_type_or_value(usd_type, value_factory) atomic_value.set_value(usd_value) mdl_value_vector.set_value(index, atomic_value) expression = expression_factory.create_constant(mdl_value_vector) return expression else: # Array value = input.Get() array_size = len(value) vector_size = len(value[0]) type = self.create_type_or_value(usd_type, type_factory) if not type.is_valid_interface(): return None vector_type = type_factory.create_vector(type, vector_size) if not vector_type.is_valid_interface(): return None array_type = type_factory.create_immediate_sized_array(vector_type, array_size) mdl_value_array = value_factory.create_array(array_type) mdl_value_array.set_size(array_size) for index in range(array_size): mdl_value_vector = value_factory.create_vector(vector_type) usd_value = value[index] for index2 in range(vector_size): atomic_value = self.create_type_or_value(usd_type, value_factory) atomic_value.set_value(usd_value[index2]) mdl_value_vector.set_value(index2, atomic_value) mdl_value_array.set_value(index, mdl_value_vector) expression = expression_factory.create_constant(mdl_value_array) return expression #-------------------------------------------------------------------------------------------------- def convert_value(context, input, mdl_type): neuray = context.neuray transaction = context.transaction factory = neuray.get_api_component(pymdlsdk.IMdl_factory) expression_factory = factory.create_expression_factory(transaction) value_factory = factory.create_value_factory(transaction) type_factory = factory.create_type_factory(transaction) name = input.GetBaseName() type = input.GetTypeName() # Try to follow the connection # TODO: not sure this is properly implemented, need further tests expression = None if input.HasConnectedSource(): (source, sourceName, sourceType) = input.GetConnectedSource() if UsdShade.Shader(source): prim = source.GetPrim() inst_name = create_material_instance(context, prim.GetPath(), None) # TODO Test None expression_list if not inst_name == None: expression = expression_factory.create_call(inst_name) else: expression = convert_value(context, UsdShade.Input(input.GetValueProducingAttribute()[0]), mdl_type) if expression == None: # No connections mdlvalue = None if type == Sdf.ValueTypeNames.Int: if not input.GetRenderType() == None: # Handle Enum tf = factory.create_type_factory(transaction) if tf and tf.is_valid_interface(): et = tf.create_enum(input.GetRenderType()) if et and et.is_valid_interface(): mdlvalue = value_factory.create_enum(et) if mdlvalue == None: # Fallback mdlvalue = value_factory.create_int() elif type == Sdf.ValueTypeNames.Float: mdlvalue = value_factory.create_float() elif type == Sdf.ValueTypeNames.Bool: mdlvalue = value_factory.create_bool() elif type == Sdf.ValueTypeNames.Double: mdlvalue = value_factory.create_double() elif type == Sdf.ValueTypeNames.String: mdlvalue = value_factory.create_string() elif type == Sdf.ValueTypeNames.Color3f: value = input.Get() if value: mdlvalue = value_factory.create_color(value[0], value[1], value[2]) else: mdlvalue = value_factory.create_color(0, 0, 0) expression = expression_factory.create_constant(mdlvalue) return expression elif type == Sdf.ValueTypeNames.Asset: is_texture = mdl_type.get_kind() == pymdlsdk.IType.Kind.TK_TEXTURE if not is_texture and mdl_type.get_kind() == pymdlsdk.IType.Kind.TK_ALIAS: type_alias = mdl_type.get_interface(pymdlsdk.IType_alias) aliased_type = type_alias.get_aliased_type() is_texture = aliased_type.get_kind() == pymdlsdk.IType.Kind.TK_TEXTURE if is_texture: # Shape # TS_2D = 0, # TS_3D = 1, # TS_CUBE = 2, # TS_PTEX = 3, # TS_BSDF_DATA = 4, tt = aliased_type.get_interface(pymdlsdk.IType_texture) shape = tt.get_shape() texture_name = GetUniqueName.get(transaction, "texture") # TODO_PA: Has to specify argc and argv otherwise failure tex = transaction.create("Texture", 0, None) transaction.store(tex, texture_name) value = input.Get() if value: texture = transaction.edit_as(pymdlsdk.ITexture, texture_name) texture.set_image(value.path) tex_type = type_factory.create_texture(shape) mdlvalue = value_factory.create_texture(tex_type, texture_name) if mdlvalue: expression = expression_factory.create_constant(mdlvalue) return expression elif type in ( Sdf.ValueTypeNames.Float2,\ Sdf.ValueTypeNames.Float2Array,\ Sdf.ValueTypeNames.Float3,\ Sdf.ValueTypeNames.Float3Array,\ Sdf.ValueTypeNames.Float4,\ Sdf.ValueTypeNames.Float4Array,\ Sdf.ValueTypeNames.Int2,\ Sdf.ValueTypeNames.Int2Array,\ Sdf.ValueTypeNames.Int3,\ Sdf.ValueTypeNames.Int3Array,\ Sdf.ValueTypeNames.Int4,\ Sdf.ValueTypeNames.Int4Array,\ Sdf.ValueTypeNames.Double2,\ Sdf.ValueTypeNames.Double2Array,\ Sdf.ValueTypeNames.Double3,\ Sdf.ValueTypeNames.Double3Array,\ Sdf.ValueTypeNames.Double4,\ Sdf.ValueTypeNames.Double4Array,\ Sdf.ValueTypeNames.BoolArray,\ Sdf.ValueTypeNames.IntArray,\ Sdf.ValueTypeNames.FloatArray,\ Sdf.ValueTypeNames.DoubleArray,\ Sdf.ValueTypeNames.Color3fArray,\ Sdf.ValueTypeNames.StringArray,\ Sdf.ValueTypeNames.Matrix2d,\ Sdf.ValueTypeNames.Matrix3d,\ Sdf.ValueTypeNames.Matrix4d\ ): converter = ConvertVectorAndArray() return converter.convert(input, type, type_factory, value_factory, expression_factory) # TODO Convert structures # elif type == Sdf.ValueTypeNames.Token: # pass else: print("Error: Unsupported input (parm/type): {}/{}".format(name, type)) if mdlvalue: value = input.Get() rtn = 0 if not value == None: rtn = mdlvalue.set_value(value) if rtn and not rtn == 0: print("set_value() error ({}) for (parm/type/value): {}/{}/{}".format(rtn, name, type, value)) expression = expression_factory.create_constant(mdlvalue) return expression return expression #-------------------------------------------------------------------------------------------------- def set_default_value(context, parm_name, definition): defaults = definition.get_defaults() i = defaults.get_index(parm_name) if i != -1: return defaults.get_expression(i) return None #-------------------------------------------------------------------------------------------------- def convert_parameter(context, definition, input): name = input.GetBaseName() index = definition.get_parameter_index(name) if index >= 0: types = definition.get_parameter_types() if types: type = types.get_type(index) if type: expression = convert_value(context, input, type) if expression and expression.is_valid_interface(): return expression else: print("Error: Invalid expression for parameter: {}".format(name)) return None #-------------------------------------------------------------------------------------------------- def edit_instance(transaction, inst_name): return transaction.edit_as(pymdlsdk.IFunction_call, inst_name) #-------------------------------------------------------------------------------------------------- def dump_expression_list(expression_list): print("===== Dump expression list =====") for index in range(expression_list.get_size()): name = expression_list.get_name(index) expr = expression_list.get_expression(index) print("Expression name/kind/type kind: {} / {} / {}".format(name, expr.get_kind(), expr.get_type().get_kind())) print("===== End dump expression list =====") #-------------------------------------------------------------------------------------------------- def dump_parameter_types(fctdef, neuray, transaction): print("===== Dump parameter types =====") name = fctdef.get_mdl_simple_name() print("Function name: {}".format(name)) pt = fctdef.get_parameter_types() factory = neuray.get_api_component(pymdlsdk.IMdl_factory) type_factory = factory.create_type_factory(transaction) print(type_factory.dump(pt).get_c_str()) # for i in range(pt.get_size()): # t = pt.get_type(i) # k = t.get_kind() # if k == pymdlsdk.IType.Kind.TK_ALIAS: # a = t.get_interface(pymdlsdk.IType_alias) # k = a.get_aliased_type().get_kind() # pn = fctdef.get_parameter_name(i) # print("Parameter name/kind: {} / {}".format(pn, k)) print("===== End dump parameter types =====") #-------------------------------------------------------------------------------------------------- def convert_parameters(context, prim_path): definition = get_definition(context, prim_path) if not definition: return None stage = context.stage prim = get_shader_prim(stage, prim_path) # expression_list = definition.get_defaults() # expression_list = pymdlsdk.IExpression_list() neuray = context.neuray factory = neuray.get_api_component(pymdlsdk.IMdl_factory) transaction = context.transaction expression_factory = factory.create_expression_factory(transaction) expression_list = expression_factory.create_expression_list() if prim: shader = UsdShade.Shader(prim) if shader: inputs = shader.GetInputs() for input in inputs: name = input.GetBaseName() expression = convert_parameter(context, definition, input) if expression: rtn = expression_list.add_expression(name, expression) if rtn != 0: print("Error") # dump_expression_list(expression_list) # Handle parameters which are not set defaults = definition.get_defaults() parameter_types = definition.get_parameter_types() value_factory = factory.create_value_factory(transaction) for i in range(definition.get_parameter_count()): name = definition.get_parameter_name(i) if expression_list.get_index(name) == -1: type = parameter_types.get_type(i) value = value_factory.create(type) expr = expression_factory.create_constant(value) expression_list.add_expression(name, expr) return expression_list #-------------------------------------------------------------------------------------------------- def dump_material_instance(context, inst_name): transaction = context.transaction inst = edit_instance(transaction, inst_name) if not inst.is_valid_interface(): return print("============ MDL Dump =============") print(inst_name) print("") neuray = context.neuray factory = neuray.get_api_component(pymdlsdk.IMdl_factory) expression_factory = factory.create_expression_factory(transaction) count = inst.get_parameter_count() arguments = inst.get_arguments() for index in range(count): argument = arguments.get_expression(index) name = inst.get_parameter_name(index) argument_text = expression_factory.dump(argument, name, 1) print(argument_text.get_c_str()) print("============ MDL Dump =============") #-------------------------------------------------------------------------------------------------- # Return a shader prim corresponding to the input prim_path. # If prim_path is a shader, return the corresponding prim. # If prim_path is a material, return the first shader found in the list of children. def get_shader_prim(stage, prim_path): prim = stage.GetPrimAtPath(Sdf.Path(prim_path)) if UsdShade.Shader(prim): return prim if UsdShade.Material(prim): mat = UsdShade.Material(prim) if mat.GetOutput("mdl:surface") and mat.GetOutput("mdl:surface").HasConnectedSource(): (src, name, t) = mat.GetOutput("mdl:surface").GetConnectedSource() if UsdShade.Shader(src): return src.GetPrim() for prim in prim.GetChildren(): if UsdShade.Shader(prim): return prim if UsdShade.NodeGraph(prim): ng = UsdShade.NodeGraph(prim) if ng.GetOutput("out") and ng.GetOutput("out").HasConnectedSource(): (src, name, t) = ng.GetOutput("out").GetConnectedSource() if UsdShade.Shader(src): return src.GetPrim() for prim in prim.GetChildren(): if UsdShade.Shader(prim): return prim return None #-------------------------------------------------------------------------------------------------- def get_sub_identifier_from_prim(prim): sub_id = prim.GetAttribute("info:mdl:sourceAsset:subIdentifier").Get() if not sub_id: sub_id = prim.GetAttribute("info:sourceAsset:subIdentifier").Get() return sub_id #-------------------------------------------------------------------------------------------------- def get_definition(context, prim_path): stage = context.stage prim = get_shader_prim(stage, prim_path) if not prim: print("Error:\tCould not find any shader in prim '{}' from stage '{}'".format(prim_path, stage.GetRootLayer().GetDisplayName())) else: shader = UsdShade.Shader(prim) if shader: imp_source = shader.GetImplementationSourceAttr().Get() if imp_source == "sourceAsset": # Retrieve module name source_asset = shader.GetSourceAsset("mdl") neuray = context.neuray (success, module_db_name) = load_module(context, source_asset) if not success: print("Error: Failed to load module: {}".format(source_asset)) else: sub_id = get_sub_identifier_from_prim(prim) if sub_id: transaction = context.transaction module = pymdl.Module._fetchFromDb(transaction, module_db_name) if module: fct = find_function(module, sub_id) if fct: fctdef = transaction.access_as(pymdlsdk.IFunction_definition, fct.dbName) if fctdef.is_valid_interface(): return fctdef return None #-------------------------------------------------------------------------------------------------- def list_functions(module: pymdl.Module): for k in module.functions.keys(): for index in range(len(module.functions[k])): print(module.functions[k][index].mdlName.split("::")[-1]) #-------------------------------------------------------------------------------------------------- # return (module_name, simple_name, parameters) # module_name without trailing '::' # e.g. if sub_id = '::nvidia::foo::bar(float,color)' # module_name = '::nvidia::foo' # simple_name = 'bar' # parameters = 'float,color' def split_function_name(sub_id: str): module_name = "" simple_name = "" parameters = "" lf = sub_id.split('(') name_and_module = lf[0] lm = name_and_module.split('::') if len(lm) > 1: module_name = '::'.join(lm[0:-1]) simple_name = lm[-1] if len(lf) > 1: parameters = lf[1].split(')')[0] return (module_name, simple_name, parameters) #-------------------------------------------------------------------------------------------------- def find_function(module: pymdl.Module, sub_id: str): (module_name, simple_name, parameters) = split_function_name(sub_id) if simple_name in module.functions: if sub_id == simple_name: # Exact match, no overload, return the function return module.functions[simple_name][0] # Access the function definition, enumerate the overloads for index in range(len(module.functions[simple_name])): fct = module.functions[simple_name][index] (candidate_module_name, candidate_simple_name, candidate_parameters) = split_function_name(fct.mdlName) if parameters == candidate_parameters: return module.functions[simple_name][index] print("Error: Function not found in module (function/module): {} / {}".format(sub_id, module.filename)) # list_functions(module) return None #-------------------------------------------------------------------------------------------------- def create_material_instance(context, prim_path, expression_list): stage = context.stage prim = get_shader_prim(stage, prim_path) if prim: shader = UsdShade.Shader(prim) if shader: imp_source = shader.GetImplementationSourceAttr().Get() if imp_source == "sourceAsset": # Retrieve module name source_asset = shader.GetSourceAsset("mdl") neuray = context.neuray (success, module_db_name) = load_module(context, source_asset) if success: sub_id = get_sub_identifier_from_prim(prim) if sub_id: transaction = context.transaction module = pymdl.Module._fetchFromDb(transaction, module_db_name) if module: fct = find_function(module, sub_id) if fct: with transaction.access_as(pymdlsdk.IFunction_definition, fct.dbName) as fctdef: inst = None if fctdef.is_valid_interface(): if expression_list == None: expression_list = convert_parameters(context, prim_path) # dump_parameter_types(fctdef, context.neuray, context.transaction) (inst, ret) = fctdef.create_function_call_with_ret(expression_list) fname = "create_material_instance()" error = {0: "Success.", -1: "An argument for a non-existing parameter was provided in 'arguments'.", -2: "The type of an argument in 'arguments' does not have the correct type, see #get_parameter_types().", -3: "A parameter that has no default was not provided with an argument value.", -4: "The definition can not be instantiated because it is not exported.", -5: "A parameter type is uniform, but the corresponding argument has a varying return type.", -6: "An argument expression is not a constant nor a call.", -8: "One of the parameter types is uniform, but the corresponding argument or default is a \ call expression and the return type of the called function definition is effectively varying since the \ function definition itself is varying.", -9: "The function definition is invalid due to a module reload, see #is_valid() for diagnostics."} if inst: if inst.is_valid_interface(): (module_name, simple_name, parameters) = split_function_name(fct.dbName) inst_name = module_name + "::" + simple_name + "::converted" inst_name = GetUniqueName.get(transaction, inst_name) transaction.store(inst, inst_name) return inst_name else: print("Error: Invalid instance for function: {}".format(fct.mdlSimpleName)) print("{} error {}: {}".format(fname, ret, error[ret])) if ret == -2: dump_parameter_types(fctdef, context.neuray, context.transaction) return None #-------------------------------------------------------------------------------------------------- async def convert_usd_to_mdl(context, prim_path, output_filename): inst_name = None mdl_entity = None mdl_entity_snapshot = None if not context.ov_neuray == None: # We are in OV # Get the shader prim from Material shader_prim_path = get_shader_prim(context.stage, prim_path) if shader_prim_path == None: print(f"Error: can not access prim: '{prim_path}'") return None mdl_entity = context.ov_neuray.createMdlEntity(shader_prim_path.GetPath().pathString) mdl_entity_snapshot = None if not mdl_entity.getMdlModule() == None: mdl_entity_snapshot = context.ov_neuray.createMdlEntitySnapshot(mdl_entity) inst_name = mdl_entity_snapshot.dbName else: print(f"Error: can not access entity: '{prim_path}'") else: # Outside of OV, conversion is done here expression_list = convert_parameters(context, prim_path) inst_name = create_material_instance(context, prim_path, expression_list) if inst_name is not None: dump_material_instance(context, inst_name) if output_filename: # we use a temporary folder for resources from the server with tempfile.TemporaryDirectory() as temp_dir: success = await save_instance_to_module(context, inst_name, prim_path, temp_dir, output_filename) if not success: inst_name = None if not context.ov_neuray == None: # We are in OV if not mdl_entity_snapshot == None: context.ov_neuray.destroyMdlEntitySnapshot(mdl_entity_snapshot) if not mdl_entity == None: context.ov_neuray.destroyMdlEntity(mdl_entity) return inst_name #-------------------------------------------------------------------------------------------------- # Split the input string or list of strings using given the split char # Return a list of strings def split_list(list_of_strings, split_char): res = [] if type(list_of_strings) == list: for s in list_of_strings: res += s.split(split_char) else: res = list_of_strings.split(split_char) return res #-------------------------------------------------------------------------------------------------- # Remove all occurences of element from the list def remove_all_occurences_of_element_from_list(element, alist): try: while True: alist.remove(element) except: pass finally: return alist #-------------------------------------------------------------------------------------------------- # Split the input string or list of strings using all the input split chars def multi_split_list(list_of_strings, list_of_splits): res = list_of_strings for split in list_of_splits: res = split_list(res, split) return res #-------------------------------------------------------------------------------------------------- # Identify a line containing an MD import declaration # From the MDL 1.7 specs: # import : import qualified_import {, qualified_import} ; # | [export] using import_path # import ( * | simple_name {, simple_name} ) ; def is_import_line(token_list): if 'import' in token_list: if token_list[0] == 'import' or token_list[0] == 'export' or token_list[0] == 'using': return True return False #-------------------------------------------------------------------------------------------------- # Construct a set or strings found in an MDL module # Split the input strings using several separators (' ',';','(', ')') # if filter_import_lines is set to True, then only process lines beginning with 'import' def find_tokens(lines, filter_import_lines = False): all_ids = set() input_list = lines if not type(lines) == list: input_list = [lines] for l in input_list: ids = multi_split_list(l, [' ',';','(', ')']) remove_all_occurences_of_element_from_list('', ids) if filter_import_lines: if not is_import_line(ids): continue for id in ids: if not id.find('::') == -1: tokens = id.split('::') for t in tokens: if len(t) > 0: all_ids.add(t) return all_ids #-------------------------------------------------------------------------------------------------- # Find MDL identifier in this line of text if text is an import statement def find_import(line): ids = multi_split_list(line, [' ',';','(', ')']) remove_all_occurences_of_element_from_list('', ids) if is_import_line(ids): for id in ids: if not id.find('::') == -1: return id return '' #-------------------------------------------------------------------------------------------------- # Find MDL identifier in this line of text def find_identifiers(line): rtn_identifiers = set() ids = multi_split_list(line, [' ', ';', '(', ')', ',', '\n']) remove_all_occurences_of_element_from_list('', ids) for id in ids: if not id.find('::') == -1: rtn_identifiers.add(id) return rtn_identifiers #-------------------------------------------------------------------------------------------------- # Substitute source strings with target strings found in the input table in the input lines # Input lines is a string or list of strings def replace_tokens(lines, table): if type(lines) == list: for i in range(len(lines)): for k in table.keys(): lines[i] = lines[i].replace(k, table[k]) return lines else: for k in table.keys(): lines = lines.replace(k, table[k]) return lines #-------------------------------------------------------------------------------------------------- # Helper to perfom unmangling on MDL module files and MDL identifiers # Un-mangling is only done in the framework of OV if an un-mangling routine exists class Unmangle: unmangle_routine = None def __init__(self, context): if context.ov_neuray != None: if "_unmangleMdlModulePath" in dir(context.ov_neuray): self.unmangle_routine = context.ov_neuray._unmangleMdlModulePath # Un-mangle a single token # token should not contain any '::' def _unmangle_token(self, token): assert(token.find("::") == -1) # Un-mangle the input token # Add prefix otherwise unmangling has not effect unmangled_token = self.unmangle_routine("::" + token) # Remove any '.mdl' extension from unmangled token if len(unmangled_token) > 4 and unmangled_token[-4:] == '.mdl': unmangled_token = unmangled_token[:-4] unmangled = (unmangled_token != token) return (unmangled, unmangled_token) # Build an un-mangling mapping table from the input list of tokens def build_mapping_table(self, token_list): table = dict() for token in token_list: (unmangled_flag, unmangled_token) = self._unmangle_token(token) if unmangled_flag: table[token] = unmangled_token return table # Un-mangled an MDL identifier # Return a tuple (True if unmagling was done, unmangled value) def unmangle_mdl_identifier(self, source): if self.unmangle_routine == None: return (False, source) token_list = find_tokens(source) table = self.build_mapping_table(token_list) unmangled_str = replace_tokens(source, table) return (unmangled_str != source, unmangled_str) # Un-mangle an MDL file and create a new un-mangled output file def unmangle_mdl_file(self, infile, outfile): if self.unmangle_routine == None: return # Only consider 'import' statements filter_import_lines = True with open(infile, 'r') as f_in: lines = f_in.readlines() token_list = find_tokens(lines, filter_import_lines) mapping = self.build_mapping_table(token_list) lines = replace_tokens(lines, mapping) with open(outfile, 'w') as f_out: f_out.writelines(lines) #-------------------------------------------------------------------------------------------------- def parse_alias(pattern, line): match = pattern.match(line) if match == None: return(False, '', '') alias = match.group("alias") path_segment = match.group("value") # print(f"alias: '{alias}' path_segment: '{path_segment}'") return(True, alias, path_segment) #-------------------------------------------------------------------------------------------------- # This unmangling class uses MDL search path to trim down MDL identifiers # It uses also MDL aliases to perform substitutions in the MDL identifier class UnmangleAndFixMDLSearchPath(Unmangle): alias_pattern = None def __init__(self, context): # compile pattern only once as it is constant self.alias_pattern = re.compile(r"""\s*using\s* # whitespace, using, whitespace (?P<alias>.*?) # alias name \s*=\s* # whitespace, equal, whitespace \"(?P<value>.*?)\" # value in quotes, \s*;""", re.VERBOSE) # semicolon, whitespace # Build MDL search path list self.mdl_search_paths = list() with context.neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg: if cfg.is_valid_interface(): for i in range(cfg.get_mdl_paths_length()): sp = cfg.get_mdl_path(i) sp = os.path.normpath(sp.get_c_str()) self.mdl_search_paths.append(sp) super(UnmangleAndFixMDLSearchPath, self).__init__(context) # Determine if this line is defining an alias def __is_alias(self, line): (is_alias, alias, path_segment) = parse_alias(self.alias_pattern, line) if is_alias: return (True, path_segment, alias) return (False, '', '') # Determine if this identifier is mangled def __is_mangled_identifier(self, id): token_list = id.split("::") remove_all_occurences_of_element_from_list('', token_list) for token in token_list: (unmangled_flag, unmangled_token) = self._unmangle_token(token) if unmangled_flag: return unmangled_flag return False # Determine if this string contains a mangled identifier def __get_mangled_identifiers(self, line): identifiers = find_identifiers(line) rtn_identifiers = set() for id in identifiers: if len(id) > 0: if self.__is_mangled_identifier(id): rtn_identifiers.add(id) return rtn_identifiers # Build mapping table for a given mangled identifier # Using the stored MDL search paths and the MDL aliases def __build_table_from_mangled_id(self, id, aliases, makeRelativeIfFailure: bool = False): key = '' value = '' # unmangle using _unmangleMdlModulePath if not id.find('::') == 0: unmangled_id = self.unmangle_routine("::" + id) else: unmangled_id = self.unmangle_routine(id) unmangled_id = re.sub('^file:/', '', unmangled_id) # Replace aliases for alias in aliases.keys(): unmangled_id = unmangled_id.replace(aliases[alias], alias) unmangled_id = os.path.normpath(unmangled_id) # Remove MDL seach path search_path_removed = False mapping_table = dict() for sp in self.mdl_search_paths: temp_id = unmangled_id temp_sp = sp if platform.system() == 'Windows': temp_id = unmangled_id.lower() temp_sp = sp.lower() # Remove the search path only when the path is found at the head of id if temp_id.startswith(temp_sp): unmangled_id = unmangled_id[len(sp):] search_path_removed = True break # Conversion is done only if we did find search path prefix in the identifier if search_path_removed: replaced = unmangled_id replaced = replaced.replace('\\', '::') replaced = replaced.replace('.mdl::', '::') what_to_replace = id mapping_table[what_to_replace] = replaced return (True, mapping_table) else: if makeRelativeIfFailure: # Turn absolute path to relative unmangled_id = os.path.basename(unmangled_id) replaced = unmangled_id replaced = replaced.replace('.mdl::', '::') what_to_replace = id mapping_table[what_to_replace] = replaced return (True, mapping_table) return (False, mapping_table) # Un-mangle an MDL file and create a new un-mangled output file def unmangle_mdl_file(self, infile, outfile): if self.unmangle_routine == None: return # Read file mapping_table = dict() with open(infile, 'r') as f_in: input_lines = f_in.readlines() if not type(input_lines) == list: # handle single line input_lines = [input_lines] # aliases mapping table aliases = dict() for line in input_lines: (alias, key, value) = self.__is_alias(line) if alias: aliases[key] = value continue ids = self.__get_mangled_identifiers(line) for id in ids: (success, new_mapping_table) = self.__build_table_from_mangled_id(id, aliases) if success: # Mege new mapping in mapping_table.update(new_mapping_table) # Replace in file and write out result with open(infile, 'r') as f_in: lines = f_in.readlines() lines = replace_tokens(lines, mapping_table) with open(outfile, 'w') as f_out: f_out.writelines(lines) # Un-mangle an MDL file and create a new un-mangled output file # Return (is identifier mangled, demangling and removing search path succeeded, un-mangled module name) def unmangle_mdl_module(self, module): if self.unmangle_routine == None: return (False, True, module) rtn = module isMangled = self.__is_mangled_identifier(module) (success, mapping_table) = self.__build_table_from_mangled_id(module, dict(), makeRelativeIfFailure = True) if success: rtn = mapping_table[module] if rtn.find('::') == 0: rtn = rtn[2:] rtn = rtn.replace("::", "/") return (isMangled, success, rtn) #-------------------------------------------------------------------------------------------------- def is_reserved_word(name : str): # there will be an API function for this soon reserved_words = ['annotation', 'auto', 'bool', 'bool2', 'bool3', 'bool4', 'break', 'bsdf', 'bsdf_measurement', 'case', 'cast', 'color', 'const', 'continue', 'default', 'do', 'double', 'double2', 'double2x2', 'double2x3', 'double3', 'double3x2', 'double3x3', 'double3x4', 'double4', 'double4x3', 'double4x4', 'double4x2', 'double2x4', 'edf', 'else', 'enum', 'export', 'false', 'float', 'float2', 'float2x2', 'float2x3', 'float3', 'float3x2', 'float3x3', 'float3x4', 'float4', 'float4x3', 'float4x4', 'float4x2', 'float2x4', 'for', 'hair_bsdf', 'if', 'import', 'in', 'int', 'int2', 'int3', 'int4', 'intensity_mode', 'intensity_power', 'intensity_radiant_exitance', 'let', 'light_profile', 'material', 'material_emission', 'material_geometry', 'material_surface', 'material_volume', 'mdl', 'module', 'package', 'return', 'string', 'struct', 'switch', 'texture_2d', 'texture_3d', 'texture_cube', 'texture_ptex', 'true', 'typedef', 'uniform', 'using', 'varying', 'vdf', 'while', 'catch', 'char', 'class', 'const_cast', 'delete', 'dynamic_cast', 'explicit', 'extern', 'external', 'foreach', 'friend', 'goto', 'graph', 'half', 'half2', 'half2x2', 'half2x3', 'half3', 'half3x2', 'half3x3', 'half3x4', 'half4', 'half4x3', 'half4x4', 'half4x2', 'half2x4', 'inline', 'inout', 'lambda', 'long', 'mutable', 'namespace', 'native', 'new', 'operator', 'out', 'phenomenon', 'private', 'protected', 'public', 'reinterpret_cast', 'sampler', 'shader', 'short', 'signed', 'sizeof', 'static', 'static_cast', 'technique', 'template', 'this', 'throw', 'try', 'typeid', 'typename', 'union', 'unsigned', 'virtual', 'void', 'volatile', 'wchar_t'] return name in reserved_words #-------------------------------------------------------------------------------------------------- # the db name of a texture is constructed here: # rendering\include\rtx\neuraylib\NeurayLibUtils.h # computeSceneIdentifierTexture def parse_ov_resource_name(texture_db_name : str): # drop the db prefix texture_db_name = texture_db_name[5:] undescore = texture_db_name.rfind('_') texture_db_name = texture_db_name[:undescore] undescore = texture_db_name.rfind('_') return texture_db_name[:undescore] async def prepare_resources_for_export(transaction : pymdlsdk.ITransaction, inst_name, temp_dir): functionCall = pymdl.FunctionCall._fetchFromDb(transaction, inst_name) for name, param in functionCall.parameters.items(): # name if param.type.kind == pymdlsdk.IType.Kind.TK_TEXTURE and param.value[0] != None: # print(f"* Name: {name}") # print(f" Type Kind: {param.type.kind}") texture_path = parse_ov_resource_name(param.value[0]) # print(f" texture_path: {texture_path}") # print(f" db_name: {param.value[0]}") # print(f" gamma: {param.value[1]}") # special handling for resources on the server if texture_path.startswith("omniverse:") or \ texture_path.startswith("file:") or \ texture_path.startswith("ftp:") or \ texture_path.startswith("http:") or \ texture_path.startswith("https:"): basename = os.path.basename(texture_path) filename, fileext = os.path.splitext(basename) id = 0 dst_path = os.path.join(temp_dir, basename) while (os.path.exists(dst_path)): dst_path = os.path.join(temp_dir, f"{filename}_{id}{fileext}") id = id + 1 result = await copy_async(texture_path, dst_path) if not result: print(f"Cannot copy from {texture_path} to {dst_path}, error code: {result}.") continue else: print(f"Downloaded resource from {texture_path} to {dst_path}. Will be deleted after export.") # use the resource in the temp folder texture_path = dst_path # create a new image new_image_db_name = "mdlexp::" + texture_path with transaction.create("Image", 0, None) as new_interface: with new_interface.get_interface(pymdlsdk.IImage) as new_image: new_image.reset_file(texture_path) transaction.store(new_image, new_image_db_name) transaction.remove(new_image_db_name) # drop after transaction is closed # assign the image to the texture # todo make sure the transaction is aborted, we don't want this change visible to other components with transaction.edit_as(pymdlsdk.ITexture, param.value[0]) as itexture: itexture.set_image(new_image_db_name) itexture.set_gamma(param.value[1]) # TODO check if srgb and linear work with floating precission here if isinstance(param, pymdl.ArgumentCall): # print(f"* Name: {name}") # print(f" Type Kind: {param.type.kind}") # print(f" dbName: {param.value}") await prepare_resources_for_export(transaction, param.value, temp_dir) # ExportHelper: Helps to save files to Nucleus server. # If we want to export a file to Nucleus, this helper: # 1- creates a temp folder, # 2- substitutes the original Nucleus folder with the temp folder, # 3- files are saved/exported to the temp folder, # 4- when finalize() is called, the content of the temp folder is saved to Nucleus server # and temp folder is deleted class ExportHelper: def __init__(self, out_filename): self.original_filename = out_filename self.out_filename = out_filename self.temp_dir = None # If out_filename is on Nucleus, then change it to temp filename if out_filename.startswith("omniverse:") or \ out_filename.startswith("file:") or \ out_filename.startswith("ftp:"): # create a temp folder self.temp_dir = tempfile.TemporaryDirectory() # substitutes the original Nucleus folder with the temp folder self.out_filename = os.path.join(self.temp_dir.name, os.path.basename(out_filename)) async def finalize(self, copy_files: bool = True): # If out_filename is different from the original one, copy all files # from the temp folder to the Nucleus server if self.temp_dir != None: if copy_files: from_dir = os.path.dirname(self.out_filename) to_dir = os.path.dirname(self.original_filename) for ld in os.listdir(from_dir): f = os.path.basename(ld) result = await copy_async(os.path.join(from_dir, f), to_dir + '/' + f) if not result: print(f"Cannot copy from {f} to {to_dir}, error code: {result}.") else: print(f"Copied resource {f} to {to_dir}.") # Delete temp folder self.temp_dir.cleanup() async def save_instance_to_module(context, inst_name, usd_prim, temp_dir, out_filename): print("============ MDL Save Instance to Module =============") neuray = context.neuray transaction = context.transaction stage = context.stage # access shader prim prim = get_shader_prim(stage, usd_prim) prim_name = usd_prim.pathString.split('/')[-1] if out_filename == None or os.path.isdir(out_filename) or os.path.splitext(out_filename)[1] != '.mdl': print(f"Error: output filename is invalid, expected an .mdl file: '{out_filename}'") return False # Handle Nucleus: OM-46539 Graph to MDL fails to copy Nucleus textures to local filesystem when exporting export_helper = ExportHelper(out_filename) out_filename = export_helper.out_filename # Sanity checks with transaction.access_as(pymdlsdk.IFunction_call, inst_name) as inst: if inst == None or not inst.is_valid_interface(): print("Error: Invalid instance name (IFunction_call): {}".format(inst_name)) return False with transaction.access_as(pymdlsdk.IFunction_definition, inst.get_function_definition()) as fd: if fd == None or not fd.is_valid_interface(): print("Error: Invalid IFunction_definition: {}".format(inst.get_function_definition())) return False module = pymdl.Module._fetchFromDb(transaction, fd.get_module()) if module == None: print("Error: Invalid Module: {}".format(fd.get_module())) return False # since resourcse are handled by the renderer we need to pass them to neuray before exporting await prepare_resources_for_export(transaction, inst_name, temp_dir) factory: pymdlsdk.IMdl_factory = neuray.get_api_component(pymdlsdk.IMdl_factory) execution_context = factory.create_execution_context() # Create the module builder. module_name = "mdl::new_module_28f8c871b7034e55a0541be81655ffb1" module_builder = factory.create_module_builder( transaction, module_name, pymdlsdk.MDL_VERSION_1_6, # In order to use aliases pymdlsdk.MDL_VERSION_LATEST, execution_context) if not module_builder.is_valid_interface(): print("Error: Failed to create module builder") return False module_builder.clear_module(execution_context) # Create a variant success = False with transaction.access_as(pymdlsdk.IFunction_call, inst_name) as inst, \ factory.create_expression_factory(transaction) as ef, \ ef.create_annotation_block() as empty_anno_block: if inst.is_valid_interface(): if is_reserved_word(prim_name): variant_name = "Main" else: variant_name = prim_name result = module_builder.add_variant( variant_name, inst.get_function_definition(), inst.get_arguments(), empty_anno_block, empty_anno_block, True, execution_context) if result != 0: print("Error: Failed to add variant to module builder:\n\t'{}'\n\t'{}'\n\t'{}'".format(prim.GetName(), inst.get_function_definition(), inst.get_arguments())) for i in range(execution_context.get_messages_count()): print(execution_context.get_message(i).get_string()) if result == 0: with neuray.get_api_component(pymdlsdk.IMdl_impexp_api) as imp_exp: rtn = -1 execution_context.set_option("bundle_resources", True) rtn = imp_exp.export_module(transaction, module_name, out_filename, execution_context) if rtn >= 0: unmangle_helper = UnmangleAndFixMDLSearchPath(context) unmangle_helper.unmangle_mdl_file(out_filename, out_filename) print(f"Success: Material '{prim_name}' exported to module '{out_filename}'") # Copy files to Nucleus if needed await export_helper.finalize() success = True else: print(f"Failure: Could not export Material '{prim_name}' to module '{out_filename}'") await export_helper.finalize(copy_files = False) module_builder.clear_module(execution_context) return success
117,950
Python
43.695339
232
0.568249
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/test_usd_converter.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.mdl.usd_converter import omni.usd import shutil import pathlib import os import carb import carb.settings # Having a test class derived from omni.kit.test.AsyncTestCase declared on the root of module # will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCaseFailOnLogError): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._test_data = str(pathlib.Path(__file__).parent.joinpath("data")) self._test_data_usd = str(pathlib.Path(self._test_data).joinpath("usd")) self._test_data_mdl = str(pathlib.Path(self._test_data).joinpath("mdl")) # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_mdl_to_usd(self): # Disable standard path to ensure reproducible results locally and in TC NO_STD_PATH = "/app/mdl/nostdpath" settings = carb.settings.get_settings() settings.set_bool(NO_STD_PATH, True) filter_import = False tokens = omni.mdl.usd_converter.find_tokens('mdl::ZA0OmniGlass_2Emdl::OmniGlass::converted_27', filter_import) result = (tokens == {'ZA0OmniGlass_2Emdl', 'converted_27', 'mdl', 'OmniGlass'}) self.assertEqual(result, True) filter_import = True tokens = omni.mdl.usd_converter.find_tokens('import ::state::normal;\n', filter_import) result = (tokens == {'state', 'normal'}) self.assertEqual(result, True) filter_import = False tokens = omni.mdl.usd_converter.find_tokens(' anno::author("NVIDIA CORPORATION"),\n', filter_import) result = (tokens == {'anno', 'author'}) self.assertEqual(result, True) filter_import = True tokens = omni.mdl.usd_converter.find_tokens(' anno::author("NVIDIA CORPORATION"),\n', filter_import) result = (len(tokens) == 0) self.assertEqual(result, True) with omni.mdl.usd_converter.TemporaryDirectory() as temp_dir: test_search_path = self._test_data_mdl fn = "core_definitions.usda" ADD_MDL_PATH = "/app/mdl/additionalUserPaths" settings = carb.settings.get_settings() mdl_custom_paths: List[str] = settings.get(ADD_MDL_PATH) or [] mdl_custom_paths.append(test_search_path) mdl_custom_paths.append(temp_dir) mdl_custom_paths = list(set(mdl_custom_paths)) settings.set_string_array(ADD_MDL_PATH, mdl_custom_paths) result = omni.mdl.usd_converter.mdl_to_usd( moduleName="nvidia/core_definitions.mdl", targetFolder=temp_dir, targetFilename=fn, output=omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY) self.assertEqual(result, True) # fn = "tutorials.usda" # # WORKAROUND: Copy test file to temp folder, NeurayLib does not handle folder containing '*.mdl.*' in their name # source_file = str(pathlib.Path(self._test_data_mdl).joinpath('nvidia/sdk_examples/tutorials.mdl')) # shutil.copy2(source_file, temp_dir) # module = str(pathlib.Path(temp_dir).joinpath("tutorials.mdl")) # if os.path.exists(module): # result = omni.mdl.usd_converter.mdl_to_usd( # moduleName=module, # targetFolder=temp_dir, # targetFilename=fn, # searchPath=test_search_path) # self.assertEqual(result, True) # fn = "test_types.usda" # WORKAROUND: Copy test file to temp folder, NeurayLib does not handle folder containing '*.mdl.*' in their name # source_file = str(pathlib.Path(self._test_data_mdl).joinpath('test/test_types.mdl')) # shutil.copy2(source_file, temp_dir) # module = str(pathlib.Path(temp_dir).joinpath("test_types.mdl")) # if os.path.exists(module): # result = omni.mdl.usd_converter.mdl_to_usd( # moduleName=module, # targetFolder=temp_dir, # targetFilename=fn, # searchPath=test_search_path) # self.assertEqual(result, True) tutorial_scene = str(pathlib.Path(self._test_data_usd).joinpath("tutorials.usda")) if os.path.exists(tutorial_scene): result = await omni.mdl.usd_converter.usd_prim_to_mdl( tutorial_scene, "/example_material", test_search_path, forceNotOV=True) self.assertEqual(result, True) result = await omni.mdl.usd_converter.usd_prim_to_mdl( tutorial_scene, "/example_modulemdl_material_examples", test_search_path, forceNotOV=True) self.assertEqual(result, True) result = await omni.mdl.usd_converter.usd_prim_to_mdl( tutorial_scene, "/wave_gradient", test_search_path, forceNotOV=True) self.assertEqual(result, True) omni.mdl.usd_converter.test_mdl_prim_to_usd('/root') simple_scene = str(pathlib.Path(self._test_data_usd).joinpath("scene.usda")) if os.path.exists(simple_scene): test_prim = '/World/Looks/Material' stage = omni.mdl.usd_converter.mdl_usd.Usd.Stage.Open(simple_scene) prim = stage.GetPrimAtPath(test_prim) omni.mdl.usd_converter.mdl_prim_to_usd(stage, prim) omni.mdl.usd_converter.mdl_usd.get_examples_search_path() mdl_tmpfile = str(pathlib.Path(temp_dir).joinpath("tmpout.mdl")) result = await omni.mdl.usd_converter.export_to_mdl(mdl_tmpfile, prim, forceNotOV=True) self.assertEqual(result, True) # Example: 'mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase' # Return: 'OmniSurface/OmniSurfaceBase.mdl' omni.mdl.usd_converter.mdl_usd.prototype_to_source_asset('mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase') omni.mdl.usd_converter.mdl_usd.parse_ov_resource_name('mdl::resolvedPath_texture_raw')
6,881
Python
44.576159
126
0.600203
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/__init__.py
from .test_usd_converter import *
34
Python
16.499992
33
0.764706
omniverse-code/kit/exts/omni.mdl.usd_converter/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.mdl.usd_converter`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`_. ## [1.0.1] - 2021-09-20 ### Changed - Added interface for USD to MDL conversion ## [1.0.0] - 2021-05-12 ### Added - Initial extensions 2.0
309
Markdown
19.666665
82
0.695793
omniverse-code/kit/exts/omni.mdl.usd_converter/docs/README.md
# Python Extension for MDL <--> USD conversions [omni.mdl.usd_converter] This is an extension for MDL to USD and for USD to MDL conversions. ## Interfaces ### mdl_to_usd(moduleName: str, searchPath: str = None, targetFolder: str = MDL_AUTOGEN_PATH, targetFilename: str = None, output: mdl_usd.OutputType = mdl_usd.OutputType.SHADER, nestedShaders: bool = False) - moduleName: Module to convert (example: `nvidia/core_definitions.mdl`) - searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set) - targetFolder: Destination folder for USD stage (default = `${data}/shadergraphs/mdl_usd`) - targetFilename: Destination stage filename, extension `.usd` or `.usda` can be omitted (default is module name, example: `core_definitions.usda`) - output: What to output: a shader: omni.mdl.usd_converter.mdl_usd.OutputType.SHADER a material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL material and geometry: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY - nestedShaders: Do we want nested shaders or flat (default = False) ### usd_prim_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None, forceNotOV: bool = False) - usdStage: Input stage containing the prim to convert - usdPrim: Prim path to convert (default = not set, use stage default prim) - searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set) - forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False) ### export_to_mdl(path: str, prim: mdl_usd.Usd.Prim, forceNotOV: bool = False) - path: Output filename to save the new module to (need to end with .mdl, example: "c:/temp/new_module.mdl") - prim: The Usd.Prim to convert - forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False) ## Examples ### MDL -> USD conversion ``` omni.mdl.usd_converter.mdl_to_usd("nvidia/core_definitions.mdl") ``` Convert core_definitions module to USD. Save the result of the conversion in the folder `${data}/shadergraphs/mdl_usd`. ``` omni.mdl.usd_converter.mdl_to_usd( moduleName = "nvidia/core_definitions.mdl", targetFolder = "C:/ProgramData/NVIDIA Corporation/mdl") ``` Convert core_definitions module to USD. Save the result of the conversion in the folder `C:/ProgramData/NVIDIA Corporation/mdl`. ``` omni.mdl.usd_converter.mdl_to_usd( moduleName = "nvidia/core_definitions.mdl", targetFolder = "C:/ProgramData/NVIDIA Corporation/mdl", targetFilename = "stage.usda") ``` Convert core_definitions module to USD. Save the result of the conversion in the folder `C:/ProgramData/NVIDIA Corporation/mdl` under the name `stage.usda`. ### USD -> MDL conversion ``` import asyncio asyncio.ensure_future(omni.mdl.usd_converter.usd_prim_to_mdl( "C:/temp/tutorials.usda", "/example_material", "C:/ProgramData/NVIDIA Corporation/mdl", forceNotOV = True)) ``` Convert the USD Prim `/example_material` found in the stage `C:/temp/tutorials.usda`. Assuming `/example_material` is a valid prim in the stage `C:/temp/tutorials.usda`, and that MDL material module `tutorials.mdl` is under `C:/ProgramData/NVIDIA Corporation/mdl/nvidia/sdk_examples`, convert the prim to MDL in memory. Here is the shader prim: ``` def Shader "example_material" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_material" float inputs:roughness = 0 color3f inputs:tint = (1, 1, 1) token outputs:out ( renderType = "material" ) } ```
3,657
Markdown
39.644444
233
0.744053
omniverse-code/kit/exts/omni.mdl.usd_converter/docs/index.rst
omni.mdl.usd_converter ########################### .. toctree:: :maxdepth: 1 CHANGELOG
94
reStructuredText
12.571427
27
0.468085
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/__init__.py
from .file import *
20
Python
9.499995
19
0.7
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/file_actions.py
import carb import omni.usd import omni.kit.window.file import omni.kit.actions.core def post_notification(message: str, info: bool = False, duration: int = 3): try: 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) except ModuleNotFoundError: carb.log_warn(message) def quit(fast: bool = False): if fast: carb.settings.get_settings().set("/app/fastShutdown", True) omni.kit.app.get_app().post_quit() def open_stage_with_new_edit_layer(): stage = omni.usd.get_context().get_stage() if not stage: post_notification(f"Cannot Re-open with New Edit Layer. No valid stage") return omni.kit.window.file.open_with_new_edit_layer(stage.GetRootLayer().identifier) def register_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "File Actions" omni.kit.actions.core.get_action_registry().register_action( extension_id, "quit", lambda: quit(fast=False), display_name="File->Exit", description="Exit", tag=actions_tag, ) omni.kit.actions.core.get_action_registry().register_action( extension_id, "quit_fast", lambda: quit(fast=True), display_name="File->Exit Fast", description="Exit Fast", tag=actions_tag, ) omni.kit.actions.core.get_action_registry().register_action( extension_id, "open_stage_with_new_edit_layer", open_stage_with_new_edit_layer, display_name="File->Open Current Stage With New Edit Layer", description="Open Stage With New Edit Layer", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
2,035
Python
28.507246
82
0.653071
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/file.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 urllib.parse import carb.input import omni.client import omni.ext import omni.kit.menu.utils import omni.kit.ui import omni.usd from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types, FILE_EVENT_QUEUE_UPDATED from omni.kit.menu.utils import MenuItemDescription from .file_actions import register_actions, deregister_actions from omni.ui import color as cl from pathlib import Path _extension_instance = None _extension_path = None INTERACTIVE_TEXT = cl.shade(cl("#1A91C5")) SHARE_ICON_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)).joinpath("data/icons/share.svg") class FileMenuExtension(omni.ext.IExt): def __init__(self): super().__init__() omni.kit.menu.utils.set_default_menu_proirity("File", -10) def on_startup(self, ext_id): global _extension_instance _extension_instance = self global _extension_path _extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id) self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name) settings = carb.settings.get_settings() self._max_recent_files = settings.get("exts/omni.kit.menu.file/maxRecentFiles") or 10 self._file_menu_list = None self._recent_menu_list = None self._build_file_menu() event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._event_sub = event_stream.create_subscription_to_pop_by_type(FILE_EVENT_QUEUE_UPDATED, lambda _: self._build_recent_menu()) events = omni.usd.get_context().get_stage_event_stream() self._stage_event_subscription = events.create_subscription_to_pop(self._on_stage_event, name="omni.kit.menu.file stage watcher") def on_shutdown(self): global _extension_instance deregister_actions(self._ext_name) _extension_instance = None self._stage_sub = None omni.kit.menu.utils.remove_menu_items(self._recent_menu_list, "File") omni.kit.menu.utils.remove_menu_items(self._file_menu_list, "File") self._recent_menu_list = None self._file_menu_list = None self._event_sub = None def _on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): self._build_file_menu() def _build_file_menu(self): # setup menu self._file_menu_list = [ MenuItemDescription( name="New", glyph="file.svg", onclick_action=("omni.kit.window.file", "new"), hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.N), ), MenuItemDescription( name="Open", glyph="folder_open.svg", onclick_action=("omni.kit.window.file", "open"), hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.O), ), MenuItemDescription(), MenuItemDescription( name="Re-open with New Edit Layer", glyph="external_link.svg", # enable_fn=lambda: not FileMenuExtension.is_new_stage(), onclick_action=("omni.kit.menu.file", "open_stage_with_new_edit_layer") ), MenuItemDescription(), MenuItemDescription( name="Share", glyph=str(SHARE_ICON_PATH), enable_fn=FileMenuExtension.can_share, onclick_action=("omni.kit.window.file", "share") ), MenuItemDescription(), MenuItemDescription( name="Save", glyph="save.svg", # enable_fn=FileMenuExtension.can_close, onclick_action=("omni.kit.window.file", "save"), hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.S), ), MenuItemDescription( name="Save With Options", glyph="save.svg", # enable_fn=FileMenuExtension.can_close, onclick_action=("omni.kit.window.file", "save_with_options"), hotkey=( carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL | carb.input.KEYBOARD_MODIFIER_FLAG_ALT, carb.input.KeyboardInput.S, ), ), MenuItemDescription( name="Save As...", glyph="none.svg", # enable_fn=FileMenuExtension.can_close, onclick_action=("omni.kit.window.file", "save_as"), hotkey=( carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL | carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT, carb.input.KeyboardInput.S, ), ), MenuItemDescription( name="Save Flattened As...", glyph="none.svg", # enable_fn=FileMenuExtension.can_close, onclick_action=("omni.kit.window.file", "save_as_flattened"), ), MenuItemDescription(), MenuItemDescription( name="Add Reference", glyph="none.svg", onclick_action=("omni.kit.window.file", "add_reference"), ), MenuItemDescription( name="Add Payload", glyph="none.svg", onclick_action=("omni.kit.window.file", "add_payload") ), MenuItemDescription(), MenuItemDescription(name="Exit", glyph="none.svg", onclick_action=("omni.kit.menu.file", "quit")), ] if not carb.settings.get_settings().get("/app/fastShutdown"): self._file_menu_list.append(MenuItemDescription(name="Exit Fast (Experimental)", glyph="none.svg", onclick_action=("omni.kit.menu.file", "quit_fast"))) self._build_recent_menu() omni.kit.menu.utils.add_menu_items(self._file_menu_list, "File", -10) def _build_recent_menu(self): if self._recent_menu_list: omni.kit.menu.utils.remove_menu_items(self._recent_menu_list, "File", rebuild_menus=False) recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD) sub_menu = [] # add reopen stage = omni.usd.get_context().get_stage() is_anonymous = stage.GetRootLayer().anonymous if stage else False filename_url = "" if not is_anonymous: filename_url = stage.GetRootLayer().identifier if stage else "" if filename_url: sub_menu.append( MenuItemDescription( name=f"Current stage: {filename_url}", onclick_action=("omni.kit.window.file", "reopen"), user={"user_style": {"color": INTERACTIVE_TEXT}} ) ) elif not recent_files: sub_menu.append(MenuItemDescription(name="None", enabled=False)) if recent_files: for recent_file in recent_files: # NOTE: not compatible with hotkeys as passing URL to open_stage sub_menu.append( MenuItemDescription( name=urllib.parse.unquote(recent_file), onclick_action=("omni.kit.window.file", "open_stage", recent_file), ) ) self._recent_menu_list = [ MenuItemDescription(name="Open Recent", glyph="none.svg", appear_after="Open", sub_menu=sub_menu) ] omni.kit.menu.utils.add_menu_items(self._recent_menu_list, "File") def is_new_stage(): return omni.usd.get_context().is_new_stage() def can_open(): stage_state = omni.usd.get_context().get_stage_state() return stage_state == omni.usd.StageState.OPENED or stage_state == omni.usd.StageState.CLOSED def can_save(): return ( omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED and not FileMenuExtension.is_new_stage() and omni.usd.get_context().is_writable() ) def can_close(): return omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED def can_close_and_not_is_new_stage(): return FileMenuExtension.can_close() and not FileMenuExtension.is_new_stage() def can_share(): return ( omni.usd.get_context() is not None and omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED and omni.usd.get_context().get_stage_url().startswith("omniverse://") ) def get_extension_path(sub_directory): global _extension_path path = _extension_path if sub_directory: path = os.path.normpath(os.path.join(path, sub_directory)) return path def get_instance(): global _extension_instance return _extension_instance
9,504
Python
39.619658
163
0.592277
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_recent_menu.py
import carb import omni.kit.test import omni.kit.helper.file_utils as file_utils from omni.kit import ui_test from .. import get_instance from omni.kit.window.file_importer.test_helper import FileImporterTestHelper class TestMenuFileRecents(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await omni.usd.get_context().new_stage_async() file_utils.reset_file_event_queue() # After running each test async def tearDown(self): await omni.usd.get_context().new_stage_async() file_utils.reset_file_event_queue() async def _mock_open_stage_async(self, url: str): # Doesn't actually open a stage but pushes an opened event like that action would. This # should cause the file event queue to update. message_bus = omni.kit.app.get_app().get_message_bus_event_stream() message_bus.push(file_utils.FILE_OPENED_EVENT, payload=file_utils.FileEventModel(url=url).dict()) await ui_test.human_delay(4) async def test_file_recent_menu(self): test_files = [ "omniverse://ov-test/first.usda", "c:/users/me/second.usda", "omniverse://ov-test/third.usda", ] under_test = get_instance() get_recent_list = lambda: under_test._recent_menu_list[0].sub_menu # load first.usda file... rebuild_menu == 1 await self._mock_open_stage_async(test_files[0]) recent_list = get_recent_list() self.assertEqual(len(recent_list), 1) self.assertEqual(recent_list[0].name, test_files[0]) # load second.usda file... rebuild_menu == 2 await self._mock_open_stage_async(test_files[1]) recent_list = get_recent_list() self.assertEqual(len(recent_list), 2) self.assertEqual(recent_list[0].name, test_files[1]) # load second.usda file again... rebuild_menu still == 2 await self._mock_open_stage_async(test_files[1]) recent_list = get_recent_list() self.assertEqual(len(recent_list), 2) self.assertEqual(recent_list[0].name, test_files[1]) # load third.usda ... rebuild_menu == 3 await self._mock_open_stage_async(test_files[2]) recent_list = get_recent_list() self.assertEqual(len(recent_list), 3) self.assertEqual(recent_list[0].name, test_files[2]) # confirm list order is as expected expected = test_files[::-1] self.assertEqual([i.name for i in recent_list], expected) async def test_file_recent_menu_current_stage(tester, _): under_test = get_instance() get_recent_list = lambda: under_test._recent_menu_list[0].sub_menu # verify recent == "None" recent_list = get_recent_list() tester.assertEqual(len(recent_list), 1) tester.assertTrue(recent_list[0].name.startswith("None")) await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open").click() await ui_test.human_delay(5) async with FileImporterTestHelper() as file_import_helper: dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests") await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda") await tester.wait_for_stage_event() await ui_test.human_delay(5) # verify name of stage stage = omni.usd.get_context().get_stage() tester.assertTrue(stage.GetRootLayer().identifier.replace("\\", "/").endswith("data/tests/4Lights.usda")) # verify recent == "Current stage:" and "4Lights.usda" recent_list = get_recent_list() tester.assertEqual(len(recent_list), 2) tester.assertTrue(recent_list[0].name.startswith("Current stage:")) tester.assertTrue(recent_list[0].name.endswith("data/tests/4Lights.usda")) tester.assertFalse(recent_list[1].name.startswith("Current stage:")) tester.assertTrue(recent_list[1].name.endswith("data/tests/4Lights.usda")) await omni.usd.get_context().new_stage_async() await ui_test.human_delay(5) # verify recent == "4Lights.usda" recent_list = get_recent_list() tester.assertEqual(len(recent_list), 1) tester.assertFalse(recent_list[0].name.startswith("Current stage:")) tester.assertTrue(recent_list[0].name.endswith("data/tests/4Lights.usda"))
4,420
Python
40.317757
109
0.666968
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/__init__.py
from .file_tests import * from .test_recent_menu import *
58
Python
18.66666
31
0.741379
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_templates.py
import asyncio import carb import omni.usd import omni.ui as ui from omni.kit import ui_test from omni.kit.menu.utils import MenuItemDescription, MenuLayout async def file_test_func_file_new_from_stage_template_empty(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("New From Stage Template").click() # select empty and wait for stage open await menu_widget.find_menu("Empty").click() await tester.wait_for_stage_event() # verify Empty stage stage = omni.usd.get_context().get_stage() tester.assertFalse(stage.GetRootLayer().identifier == layer_name) prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertTrue(prim_list == ['/World']) async def file_test_func_file_new_from_stage_template_sunlight(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("New From Stage Template").click() # select Sunlight and wait for stage open await menu_widget.find_menu("Sunlight").click() await tester.wait_for_stage_event() # verify Sunlight stage stage = omni.usd.get_context().get_stage() tester.assertFalse(stage.GetRootLayer().identifier == layer_name) prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertTrue(prim_list == ['/World', '/Environment', '/Environment/defaultLight']) async def file_test_func_file_new_from_stage_template_default_stage(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("New From Stage Template").click() # select Default Stage and wait for stage open await menu_widget.find_menu("Default Stage").click() await tester.wait_for_stage_event() # verify Default Stage stage = omni.usd.get_context().get_stage() tester.assertFalse(stage.GetRootLayer().identifier == layer_name) prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertEqual(set(prim_list), set([ '/World', '/Environment', '/Environment/Sky', '/Environment/DistantLight', '/Environment/Looks', '/Environment/Looks/Grid', '/Environment/Looks/Grid/Shader', '/Environment/ground', '/Environment/groundCollider']))
3,018
Python
42.128571
108
0.710073
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_media.py
import os import shutil import tempfile import asyncio import carb import omni.usd import omni.ui as ui from omni.kit import ui_test from omni.kit.menu.utils import MenuItemDescription, MenuLayout from omni.kit.window.file_importer.test_helper import FileImporterTestHelper from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper async def file_test_func_file_new(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("New").click() await tester.wait_for_stage_event() # verify its a new layer tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier == layer_name) async def file_test_func_file_open(tester, menu_item: MenuItemDescription): await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open").click() await ui_test.human_delay(5) async with FileImporterTestHelper() as file_import_helper: dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests") await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda") await tester.wait_for_stage_event() # verify name of stage stage = omni.usd.get_context().get_stage() tester.assertTrue(stage.GetRootLayer().identifier.replace("\\", "/").endswith("data/tests/4Lights.usda")) async def file_test_func_file_reopen(tester, menu_item: MenuItemDescription): await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open Recent").click() await menu_widget.find_menu(tester._light_path, ignore_case=True).click() await tester.wait_for_stage_event() # verify its a unmodified stage tester.assertFalse(omni.kit.undo.can_undo()) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # verify its a modified stage tester.assertTrue(omni.kit.undo.can_undo()) await tester.reset_stage_event(omni.usd.StageEventType.OPENED) await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open Recent").click() await menu_widget.find_menu("Current stage:", contains_path=True).click() await tester.wait_for_stage_event() # verify its a unmodified stage tester.assertFalse(omni.kit.undo.can_undo()) async def file_test_func_file_re_open_with_new_edit_layer(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await file_test_func_file_open(tester, {}) await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Re-open with New Edit Layer").click() await ui_test.human_delay(50) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights_layer.usda") await tester.wait_for_stage_event() # verify its not saved to tmpdir layer = omni.usd.get_context().get_stage().GetRootLayer() expected_name = f"{tmpdir}/4Lights_layer.usd".replace("\\", "/") tester.assertTrue(layer.anonymous) tester.assertTrue(len(layer.subLayerPaths) == 2) tester.assertTrue(layer.subLayerPaths[0] == expected_name) tester.assertTrue(layer.subLayerPaths[1].endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda")) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_save(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save").click() await ui_test.human_delay(50) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") expected_size = os.path.getsize(expected_name) tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # save again, it should not show dialog.... await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save").click() await ui_test.human_delay() # handle dialog.... save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'") await save_widget.click() await ui_test.human_delay() await tester.wait_for_stage_event() # verify file was saved tester.assertFalse(os.path.getsize(expected_name) == expected_size) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_save_with_options(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save With Options").click() await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") expected_size = os.path.getsize(expected_name) tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # save again, it should not show dialog.... await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save").click() await ui_test.human_delay() # handle dialog.... save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'") await save_widget.click() await ui_test.human_delay() await tester.wait_for_stage_event() # verify file was saved tester.assertFalse(os.path.getsize(expected_name) == expected_size) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_save_as(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await file_test_func_file_open(tester, {}) await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save As...").click() await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_save_flattened_as(tester, menu_item: MenuItemDescription): # save flattened doesn't send any stage events as it exports not saves tmpdir = tempfile.mkdtemp() await file_test_func_file_open(tester, {}) stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier.replace("\\", "/") if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save Flattened As...").click() await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda") await ui_test.human_delay(20) # verify its exported to tmpdir & hasn't changed stage path expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == layer_name) tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_open_recent_exts_omni_kit_menu_file_data_tests_4lights_usda(tester, menu_item: MenuItemDescription): await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open Recent").click() await menu_widget.find_menu(tester._light_path, ignore_case=True).click() await tester.wait_for_stage_event() # verify its 4lights tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/").endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda")) async def file_test_func_file_exit(tester, menu_item: MenuItemDescription): # not sure how to test this without kit exiting... pass async def file_test_func_file_exit_fast__experimental(tester, menu_item: MenuItemDescription): # not sure how to test this without kit exiting... pass async def file_test_hotkey_func_file_new(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" # emulate hotkey await tester.reset_stage_event(omni.usd.StageEventType.OPENED) await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await tester.wait_for_stage_event() # verify its a new layer tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier == layer_name) async def file_test_hotkey_func_file_open(tester, menu_item: MenuItemDescription): # emulate hotkey await tester.reset_stage_event(omni.usd.StageEventType.OPENED) await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(5) async with FileImporterTestHelper() as file_import_helper: dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests") await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda") await tester.wait_for_stage_event() # verify its 4lights tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/").endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda")) async def file_test_hotkey_func_file_save(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await tester.reset_stage_event(omni.usd.StageEventType.SAVED) # emulate hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) expected_size = os.path.getsize(expected_name) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await ui_test.human_delay() # save again, it should not show dialog.... await tester.reset_stage_event(omni.usd.StageEventType.SAVED) await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.S, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) # handle dialog.... save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'") if save_widget: await save_widget.click() await ui_test.human_delay() await tester.wait_for_stage_event() # verify file was saved tester.assertFalse(os.path.getsize(expected_name) == expected_size) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_hotkey_func_file_save_with_options(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await tester.reset_stage_event(omni.usd.StageEventType.SAVED) # emulate hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") expected_size = os.path.getsize(expected_name) tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await ui_test.human_delay() # save again, it should not show dialog.... await tester.reset_stage_event(omni.usd.StageEventType.SAVED) # emulate hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) # handle dialog.... save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'") await save_widget.click() await ui_test.human_delay() await tester.wait_for_stage_event() # verify file was saved tester.assertFalse(os.path.getsize(expected_name) == expected_size) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_hotkey_func_file_save_as(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await file_test_func_file_open(tester, {}) await tester.reset_stage_event(omni.usd.StageEventType.SAVED) # emulate hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_share(tester, menu_item: MenuItemDescription): # File->Share will only work on omniverse:// files. Currently there is no way to mock this scenario. menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Share").click() pass
15,830
Python
40.012953
162
0.704991
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_payload.py
import asyncio import carb import omni.usd import omni.ui as ui from omni.kit import ui_test from omni.kit.menu.utils import MenuItemDescription, MenuLayout async def file_test_func_file_add_reference(tester, menu_item: MenuItemDescription): from carb.input import KeyboardInput menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Add Reference").click() await ui_test.human_delay() dir_widget = ui_test.find("Select File//Frame/**/StringField[*].identifier=='filepicker_directory_path'") await ui_test.human_delay() await dir_widget.input(carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")) await ui_test.human_delay() await tester.find_content_file("Select File", "sphere.usda").click(double=True) await ui_test.human_delay(20) # verify reference was added... stage = omni.usd.get_context().get_stage() prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertTrue(len(prim_list) > 0) async def file_test_func_file_add_payload(tester, menu_item: MenuItemDescription): from carb.input import KeyboardInput menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Add Payload").click() await ui_test.human_delay() dir_widget = ui_test.find("Select File//Frame/**/StringField[*].identifier=='filepicker_directory_path'") await ui_test.human_delay() await dir_widget.input(carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")) await ui_test.human_delay() await tester.find_content_file("Select File", "sphere.usda").click(double=True) await ui_test.human_delay(20) # verify payload was added... stage = omni.usd.get_context().get_stage() prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertTrue(len(prim_list) > 0)
1,999
Python
36.735848
119
0.710355
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/file_tests.py
import sys import re import asyncio import carb import omni.kit.test import omni.kit.helper.file_utils as file_utils from .test_func_media import * from .test_func_payload import * from .test_func_templates import * from .test_recent_menu import test_file_recent_menu_current_stage class TestMenuFile(omni.kit.test.AsyncTestCase): async def setUp(self): self._light_path = carb.tokens.get_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests/4Lights.usda") # load stage so menu shows reopen await omni.usd.get_context().open_stage_async(self._light_path) async def tearDown(self): pass async def test_file_menus(self): import omni.kit.material.library # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() await ui_test.human_delay() menus = omni.kit.menu.utils.get_merged_menus() prefix = "file_test" to_test = [] this_module = sys.modules[__name__] for key in menus.keys(): if key.startswith("File"): for item in menus[key]['items']: if item.name != "" and item.has_action(): key_name = re.sub('\W|^(?=\d)','_', key.lower()) func_name = re.sub('\W|^(?=\d)','_', item.name.replace("${kit}/", "").lower()) while key_name and key_name[-1] == "_": key_name = key_name[:-1] while func_name and func_name[-1] == "_": func_name = func_name[:-1] test_fn = f"{prefix}_func_{key_name}_{func_name}" if test_fn.startswith("file_test_func_file_open_recent_reopen_current_stage"): test_fn = "file_test_func_file_reopen" elif test_fn.startswith("file_test_func_file_open_recent"): continue try: to_call = getattr(this_module, test_fn) to_test.append((to_call, test_fn, item)) except AttributeError: carb.log_error(f"test function \"{test_fn}\" not found") if item.original_menu_item and item.original_menu_item.hotkey: test_fn = f"{prefix}_hotkey_func_{key_name}_{func_name}" try: to_call = getattr(this_module, test_fn) to_test.append((to_call, test_fn, item.original_menu_item)) except AttributeError: carb.log_error(f"test function \"{test_fn}\" not found") self._future_test = None self._required_stage_event = -1 self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.menu.file") # add in any additional tests test_fn = "test_file_recent_menu_current_stage" to_call = getattr(this_module, test_fn) to_test.append((to_call, test_fn, None)) for to_call, test_fn, menu_item in to_test: file_utils.reset_file_event_queue() carb.settings.get_settings().set("/persistent/app/omniverse/lastOpenDirectory", "") carb.settings.get_settings().set("/persistent/app/file_exporter/directory", "") carb.settings.get_settings().set("/persistent/app/file_exporter/filename", "") carb.settings.get_settings().set("/persistent/app/file_exporter/file_extension", "") await self.wait_stage_loading() await omni.usd.get_context().new_stage_async() await ui_test.human_delay() print(f"Running test {test_fn}") await to_call(self, menu_item) self._stage_event_sub = None def find_content_file(self, window_name, filename): for widget in ui_test.find_all(f"{window_name}//Frame/**/TreeView[*]"): for file_widget in widget.find_all(f"**/Label[*]"): if file_widget.widget.text==filename: return file_widget return None def _on_stage_event(self, event): if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done(): self._future_test.set_result(event.type) async def reset_stage_event(self, stage_event): self._required_stage_event = stage_event self._future_test = asyncio.Future() async def wait_for_stage_event(self): async def wait_for_event(): await self._future_test try: await asyncio.wait_for(wait_for_event(), timeout=30.0) except asyncio.TimeoutError: carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}") self._future_test = None self._required_stage_event = -1 async def wait_stage_loading(self): while True: _, files_loaded, total_files = omni.usd.get_context().get_stage_loading_status() if files_loaded or total_files: await ui_test.human_delay() continue break await ui_test.human_delay()
5,421
Python
42.725806
155
0.561336
omniverse-code/kit/exts/omni.kit.menu.file/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.1.4] - 2023-01-18 ### Changes - Cancel update task after stage closing. ## [1.1.3] - 2022-11-01 ### Changes - Restored failing test & fixed ## [1.1.2] - 2022-11-01 ### Changes - Remove failing test ## [1.1.1] - 2022-07-19 ### Changes - Disabled contextual greying of menu items ## [1.1.0] - 2022-06-08 ### Changes - Updated menu to use actions ## [1.0.9] - 2022-06-15 ### Changes - Updated unittests. ## [1.0.8] - 2022-05-19 ### Changes - Optimized recents menu rebuilding ## [1.0.7] - 2022-02-23 ### Changes - Removed "Open With Payloads Disabled" from file menu. ## [1.0.6] - 2021-11-25 ### Changes - Only rebuild recent list on stage save/load/open/close events ## [1.0.5] - 2021-08-23 ### Changes - Set menus default order ## [1.0.4] - 2021-07-13 ### Changes - Added "Open With Payloads Disabled" - Added "Add Payload" ## [1.0.3] - 2021-06-21 ### Changes - Moved recents from USDContext ## [1.0.2] - 2021-05-05 ### Changes - Added "Save With Options" ## [1.0.1] - 2020-12-03 ### Changes - Added "Add Reference" ## [1.0.0] - 2020-08-17 ### Changes - Created
1,176
Markdown
17.107692
80
0.633503
omniverse-code/kit/exts/omni.kit.menu.file/docs/index.rst
omni.kit.menu.file ########################### File Menu .. toctree:: :maxdepth: 1 CHANGELOG
107
reStructuredText
6.2
27
0.448598
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/config/extension.toml
[package] version = "1.0.1" authors = ["NVIDIA"] title = "USD Material MDL Export" description="The ability to export USD Material to MDL" readme = "docs/README.md" repository = "" category = "USD" feature = true keywords = ["usd", "mdl", "export", "stage"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" # icon = "data/icon.png" [dependencies] "omni.appwindow" = {} "omni.kit.commands" = {} "omni.kit.context_menu" = {} "omni.kit.pip_archive" = {} "omni.usd" = {} "omni.mdl.usd_converter" = {} "omni.kit.window.filepicker" = {} "omni.kit.widget.filebrowser" = {} [[python.module]] name = "omni.kit.stage.mdl_converter" [[test]] args = [] dependencies = [] stdoutFailPatterns.include = [] stdoutFailPatterns.exclude = []
744
TOML
20.911764
55
0.669355
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/stage_mdl_converter_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__ = ["StageMdlConverterExtension"] from pxr import Sdf import omni.ext import omni.usd import omni.kit.context_menu from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.window.filepicker import FilePickerDialog from omni.kit.window.popup_dialog.message_dialog import MessageDialog import os import omni.ui as ui import asyncio import carb class AskForOverrideDialog(MessageDialog): WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self._style = self._style.copy() # self._style["Background"]["background_color"] = ui.color("#00000000") # self._style["Background"]["border_color"] = ui.color("#00000000") class WarningDialog(MessageDialog): WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class StageMdlConverterExtension(omni.ext.IExt): def on_startup(self, ext_id): app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() self._stage_menu = ext_manager.subscribe_to_extension_enable( on_enable_fn=lambda _: self._register_stage_menu(), on_disable_fn=lambda _: self._unregister_stage_menu(), ext_name="omni.kit.widget.stage", hook_name="omni.kit.stage.mdl_converter", ) self._pick_export_path_dialog = None self._override_dialog = None self._warning_dialog = None self._selected_prim = None self._current_dir = None self._current_export_path = None def on_shutdown(self): self._unregister_stage_menu() self._stage_menu = None self._stage_context_menu_export = None @staticmethod def __on_filter_mdl_files(item: FileBrowserItem) -> bool: """Used by pick folder dialog to hide all the files""" if item and not item.is_folder: _, ext = os.path.splitext(item.path) return (ext in [".mdl"]) return True def __run_export(self): """Do the actual export after we have a filename to export to""" carb.log_info(f"Picked output filename: {self._current_export_path}") asyncio.ensure_future(omni.mdl.usd_converter.usd_to_mdl(self._current_export_path, self._selected_prim)) def __on_ok_override(self, popup): """Called when the the user confirmed to override""" carb.log_info(f"Confirmed to override selected filename: {self._current_export_path}") popup.hide() self.__run_export() def __on_cancel_override(self, popup): """Called when the the user rejected to override""" carb.log_info(f"Rejected to override selected filename: {self._current_export_path}") popup.hide() self._pick_export_path_dialog.refresh_current_directory() self._pick_export_path_dialog.show(path=self._current_export_path) def __on_ok_warning(self, popup): """Called when the the user closes warning dialog""" popup.hide() def __on_apply_filename(self, filename: str, dir: str): """Called when the user press "Export" in the pick filename dialog""" # don't accept as long as no filename is selected if not filename or not dir: return # add the file extension if missing if len(filename) < 5 or filename[-4:] != '.mdl': filename = filename + '.mdl' self._current_dir = dir # add a trailing slash for the client library if(dir[-1] != os.sep): dir = dir + os.sep self._current_export_path = omni.client.combine_urls(dir, filename) self._pick_export_path_dialog.hide() # ask for override or run export directly if os.path.exists(self._current_export_path): carb.log_info(f"WARNING: selected filename already exists: {self._current_export_path}") if self._override_dialog != None: self._override_dialog.destroy() self._override_dialog = AskForOverrideDialog( title = "Confirm override...", message = "The selected file already exists. Do you want to replace it?", ok_label = "Yes", cancel_label = "No", ok_handler = self.__on_ok_override, cancel_handler = self.__on_cancel_override ) # self._override_dialog.build_ui() self._override_dialog.show() else: self.__run_export() def _register_stage_menu(self): """Called when "omni.kit.widget.stage" is loaded""" def on_export(objects: dict): """Called from the context menu""" # keep the selected prim prims = objects.get("prim_list", None) if not prims or len(prims) > 1: return if len(prims) == 1: theprim = prims[0] stage = theprim.GetStage() (status, message) = omni.mdl.usd_converter.is_shader_resolved(stage, theprim) if not status: carb.log_warn(message) if self._warning_dialog != None: self._warning_dialog.destroy() self._warning_dialog = WarningDialog( title = "Convert Material to MDL", message = "WARNING: " + message, disable_cancel_button=True, ok_handler = self.__on_ok_warning, ) self._warning_dialog.show() return if not omni.mdl.usd_converter.is_material_bound_to_prim(stage, theprim): # Material not bound, display warning dialog and do not proceed carb.log_warn(f"Material is not bound to any prim, can not convert") if self._warning_dialog != None: self._warning_dialog.destroy() self._warning_dialog = WarningDialog( title = "Convert Material to MDL", message = "WARNING: Material is not bound to any prim, can not convert", disable_cancel_button=True, ok_handler = self.__on_ok_warning, ) self._warning_dialog.show() return self._selected_prim = prims[0] """Open Pick Folder dialog to add compounds""" if self._pick_export_path_dialog is None: self._pick_export_path_dialog = FilePickerDialog( "Convert Material to MDL and Export As...", allow_multi_selection=False, apply_button_label="Export", click_apply_handler=self.__on_apply_filename, item_filter_options=["MDL Files (*.mdl)"], item_filter_fn=self.__on_filter_mdl_files, # OM-61553: Use the selected material prim name as the default filename current_filename=self._selected_prim.GetName(), current_directory=self._current_dir ) if self._pick_export_path_dialog is not None: self._pick_export_path_dialog.refresh_current_directory() self._pick_export_path_dialog.set_filename(self._selected_prim.GetName()) self._pick_export_path_dialog.show(path=self._current_export_path) # Add context menu to omni.kit.widget.stage context_menu = omni.kit.context_menu.get_instance() if context_menu: menu = { "name": "Export to MDL", "glyph": "menu_save.svg", "show_fn": [context_menu.is_material, context_menu.is_one_prim_selected], "onclick_fn": on_export, "appear_after": "Save Selected", } self._stage_context_menu_export = omni.kit.context_menu.add_menu(menu, "MENU", "omni.kit.widget.stage") def _unregister_stage_menu(self): """Called when "omni.kit.widget.stage" is unloaded""" if self._pick_export_path_dialog: self._pick_export_path_dialog.destroy() self._pick_export_path_dialog = None if self._override_dialog: self._override_dialog.destroy() self._override_dialog = None if self._warning_dialog: self._warning_dialog.destroy() self._warning_dialog = None self._stage_context_menu_export = None
9,267
Python
40.375
115
0.584116
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/tests/test_mdl_converter.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.stage.mdl_converter import * from pxr import Sdf from pxr import Usd from pxr import UsdGeom import omni.kit.test class Test(omni.kit.test.AsyncTestCase): async def test_mdl_converter(self): """Testing omni.kit.stage.mdl_converter""" self.assertEqual(True, True)
726
Python
37.263156
76
0.77686
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/docs/CHANGELOG.md
# CHANGELOG The ability to export USD Material to MDL. ## [1.0.1] - 2022-05-31 - Changed "Export Selected" to "Save Selected" ## [1.0.0] - 2022-02-10 ### Added
165
Markdown
14.090908
47
0.636364
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/docs/README.md
# USD Material MDL Export. This extension adds a context menu item "Export to MDL" to the stage window. It shows when right-clicking a (single) selected material node. When the new menu item is chosen, the user is prompted for a destination MDL filename. The selected USD material is then converted to an MDL material and saved to the selected destination in a new MDL module. ## Issues and limitation - The USD material needs to be bound to geometry in order to be fully available to the renderer and ready for export. - Resources that are exported with the material are not overridden if files with the name exists already. Instead, new filenames are generated for those resources. This also applies when exporting a USD material to the same MDL file multiple times. ## Screenshot
787
Markdown
70.636357
349
0.792884
omniverse-code/kit/exts/omni.kit.capture/config/extension.toml
[package] category = "Rendering" changelog = "docs/CHANGELOG.md" description = "An extension to capture Kit viewport into images and videos." icon = "data/icon.svg" preview_image = "data/preview.png" readme = "docs/README.md" title = "Kit Image and Video Capture" version = "0.5.1" [dependencies] "omni.usd" = {} "omni.timeline" = {} "omni.ui" = {} "omni.videoencoding" = {} "omni.kit.viewport.utility" = {} "omni.kit.renderer.capture" = { optional=true } [[python.module]] name = "omni.kit.capture" [[test]] dependencies = [ "omni.kit.renderer.capture", "omni.kit.window.viewport", ] waiver = "extension is being deprecated" unreliable = true
656
TOML
20.899999
76
0.6875
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/capture_progress.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from enum import Enum, IntEnum import datetime import subprocess import carb import omni.ui as ui import omni.kit.app class CaptureStatus(IntEnum): NONE = 0 CAPTURING = 1 PAUSED = 2 FINISHING = 3 TO_START_ENCODING = 4 ENCODING = 5 CANCELLED = 6 class CaptureProgress: def __init__(self): self._init_internal() def _init_internal(self, time_length=0, time_rate=24): self._time_length = time_length self._time_rate = time_rate self._total_frames = int(self._time_length / self._time_rate) # at least to capture 1 frame if self._total_frames < 1: self._total_frames = 1 self._capture_status = CaptureStatus.NONE self._elapsed_time = 0.0 self._estimated_time_remaining = 0.0 self._current_frame_time = 0.0 self._average_time_per_frame = 0.0 self._encoding_time = 0.0 self._current_frame = 0 self._first_frame_num = 0 self._got_first_frame = False self._progress = 0.0 self._current_subframe = -1 self._total_subframes = 1 self._subframe_time = 0.0 self._total_frame_time = 0.0 self._average_time_per_subframe = 0.0 self._total_preroll_frames = 0 self._prerolled_frames = 0 self._path_trace_iteration_num = 0 self._path_trace_subframe_num = 0 @property def capture_status(self): return self._capture_status @capture_status.setter def capture_status(self, value): self._capture_status = value @property def elapsed_time(self): return self._get_time_string(self._elapsed_time) @property def estimated_time_remaining(self): return self._get_time_string(self._estimated_time_remaining) @property def current_frame_time(self): return self._get_time_string(self._current_frame_time) @property def average_frame_time(self): return self._get_time_string(self._average_time_per_frame) @property def encoding_time(self): return self._get_time_string(self._encoding_time) @property def progress(self): return self._progress @property def current_subframe(self): return self._current_subframe @property def total_subframes(self): return self._total_subframes @property def subframe_time(self): return self._get_time_string(self._subframe_time) @property def average_time_per_subframe(self): return self._get_time_string(self._average_time_per_subframe) @property def total_preroll_frames(self): return self._total_preroll_frames @total_preroll_frames.setter def total_preroll_frames(self, value): self._total_preroll_frames = value @property def prerolled_frames(self): return self._prerolled_frames @prerolled_frames.setter def prerolled_frames(self, value): self._prerolled_frames = value @property def path_trace_iteration_num(self): return self._path_trace_iteration_num @path_trace_iteration_num.setter def path_trace_iteration_num(self, value): self._path_trace_iteration_num = value @property def path_trace_subframe_num(self): return self._path_trace_subframe_num @path_trace_subframe_num.setter def path_trace_subframe_num(self, value): self._path_trace_subframe_num = value def start_capturing(self, time_length, time_rate, preroll_frames=0): self._init_internal(time_length, time_rate) self._total_preroll_frames = preroll_frames self._capture_status = CaptureStatus.CAPTURING def finish_capturing(self): self._init_internal() def is_prerolling(self): return ( (self._capture_status == CaptureStatus.CAPTURING or self._capture_status == CaptureStatus.PAUSED) and self._total_preroll_frames > 0 and self._total_preroll_frames > self._prerolled_frames ) def add_encoding_time(self, time): if self._estimated_time_remaining > 0.0: self._elapsed_time += self._estimated_time_remaining self._estimated_time_remaining = 0.0 self._encoding_time += time def add_frame_time(self, frame, time, pt_subframe_num=0, pt_iteration_num=0): if not self._got_first_frame: self._got_first_frame = True self._first_frame_num = frame self._current_frame = frame self._path_trace_subframe_num = pt_subframe_num self._path_trace_iteration_num = pt_iteration_num self._elapsed_time += time if self._current_frame != frame: frames_captured = self._current_frame - self._first_frame_num + 1 self._average_time_per_frame = self._elapsed_time / frames_captured self._current_frame = frame self._current_frame_time = time else: self._current_frame_time += time if frame == self._first_frame_num: self._estimated_time_remaining = 0.0 self._progress = 0.0 else: total_frame_time = self._average_time_per_frame * self._total_frames # if users pause for long times, it's possible that elapsed time will be greater than estimated total time # if this happens, estimate it again if self._elapsed_time >= total_frame_time: total_frame_time += time + self._average_time_per_frame self._estimated_time_remaining = total_frame_time - self._elapsed_time self._progress = self._elapsed_time / total_frame_time def add_single_frame_capture_time(self, subframe, total_subframes, time): self._total_subframes = total_subframes self._elapsed_time += time if self._current_subframe != subframe: self._subframe_time = time if self._current_subframe == -1: self._average_time_per_subframe = self._elapsed_time else: self._average_time_per_subframe = self._elapsed_time / subframe self._total_frame_time = self._average_time_per_subframe * total_subframes else: self._subframe_time += time self._current_subframe = subframe if self._current_subframe == 0: self._estimated_time_remaining = 0.0 self._progress = 0.0 else: if self._elapsed_time >= self._total_frame_time: self._total_frame_time += time + self._average_time_per_subframe self._estimated_time_remaining = self._total_frame_time - self._elapsed_time self._progress = self._elapsed_time / self._total_frame_time def _get_time_string(self, time_seconds): hours = int(time_seconds / 3600) minutes = int((time_seconds - hours*3600) / 60) seconds = time_seconds - hours*3600 - minutes*60 time_string = "" if hours > 0: time_string += '{:d}h '.format(hours) if minutes > 0: time_string += '{:d}m '.format(minutes) else: if hours > 0: time_string += "0m " time_string += '{:.2f}s'.format(seconds) return time_string PROGRESS_WINDOW_WIDTH = 360 PROGRESS_WINDOW_HEIGHT = 260 PROGRESS_BAR_WIDTH = 216 PROGRESS_BAR_HEIGHT = 20 PROGRESS_BAR_HALF_HEIGHT = PROGRESS_BAR_HEIGHT / 2 TRIANGLE_WIDTH = 6 TRIANGLE_HEIGHT = 10 TRIANGLE_OFFSET_Y = 10 PROGRESS_WIN_DARK_STYLE = { "Triangle::progress_marker": {"background_color": 0xFFD1981D}, "Rectangle::progress_bar_background": { "border_width": 0.5, "border_radius": PROGRESS_BAR_HALF_HEIGHT, "background_color": 0xFF888888, }, "Rectangle::progress_bar_full": { "border_width": 0.5, "border_radius": PROGRESS_BAR_HALF_HEIGHT, "background_color": 0xFFD1981D, }, "Rectangle::progress_bar": { "background_color": 0xFFD1981D, "border_radius": PROGRESS_BAR_HALF_HEIGHT, "corner_flag": ui.CornerFlag.LEFT, "alignment": ui.Alignment.LEFT, }, } PAUSE_BUTTON_STYLE = { "NvidiaLight": { "Button.Label::pause": {"color": 0xFF333333}, "Button.Label::pause:disabled": {"color": 0xFF666666}, }, "NvidiaDark": { "Button.Label::pause": {"color": 0xFFCCCCCC}, "Button.Label::pause:disabled": {"color": 0xFF666666}, }, } class CaptureProgressWindow: def __init__(self): self._app = omni.kit.app.get_app_interface() self._update_sub = None self._window_caption = "Capture Progress" self._window = None self._progress = None self._progress_bar_len = PROGRESS_BAR_HALF_HEIGHT self._progress_step = 0.5 self._is_single_frame_mode = False self._show_pt_subframes = False self._show_pt_iterations = False self._support_pausing = True def show( self, progress, single_frame_mode: bool = False, show_pt_subframes: bool = False, show_pt_iterations: bool = False, support_pausing: bool = True, ) -> None: self._progress = progress self._is_single_frame_mode = single_frame_mode self._show_pt_subframes = show_pt_subframes self._show_pt_iterations = show_pt_iterations self._support_pausing = support_pausing self._build_ui() self._update_sub = self._app.get_update_event_stream().create_subscription_to_pop( self._on_update, name="omni.kit.capure progress" ) def close(self): self._window = None self._update_sub = None def _build_progress_bar(self): self._progress_bar_area.clear() self._progress_bar_area.set_style(PROGRESS_WIN_DARK_STYLE) with self._progress_bar_area: with ui.Placer(offset_x=self._progress_bar_len - TRIANGLE_WIDTH / 2, offset_y=TRIANGLE_OFFSET_Y): ui.Triangle( name="progress_marker", width=TRIANGLE_WIDTH, height=TRIANGLE_HEIGHT, alignment=ui.Alignment.CENTER_BOTTOM, ) with ui.ZStack(): ui.Rectangle(name="progress_bar_background", width=PROGRESS_BAR_WIDTH, height=PROGRESS_BAR_HEIGHT) ui.Rectangle(name="progress_bar", width=self._progress_bar_len, height=PROGRESS_BAR_HEIGHT) def _build_ui_timer(self, text, init_value): with ui.HStack(): with ui.HStack(width=ui.Percent(50)): ui.Spacer() ui.Label(text, width=0) with ui.HStack(width=ui.Percent(50)): ui.Spacer(width=15) timer_label = ui.Label(init_value) ui.Spacer() return timer_label def _build_multi_frames_capture_timers(self): self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time) self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining) self._ui_current_frame_time = self._build_ui_timer("Current frame time", self._progress.current_frame_time) if self._show_pt_subframes: subframes_str = f"{self._progress.path_trace_subframe_num}" self._ui_pt_subframes = self._build_ui_timer("Subframes", subframes_str) if self._show_pt_iterations: iter_str = f"{self._progress.path_trace_iteration_num}" self._ui_pt_iterations = self._build_ui_timer("Iterations", iter_str) self._ui_ave_frame_time = self._build_ui_timer("Average time per frame", self._progress.average_frame_time) self._ui_encoding_time = self._build_ui_timer("Encoding", self._progress.encoding_time) def _build_single_frame_capture_timers(self): self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time) self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining) subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count = self._build_ui_timer("Subframe/Total frames", subframe_count) self._ui_current_frame_time = self._build_ui_timer("Current subframe time", self._progress.subframe_time) self._ui_ave_frame_time = self._build_ui_timer("Average time per subframe", self._progress.average_frame_time) def _build_preroll_notification(self): with ui.HStack(): ui.Spacer(width=ui.Percent(20)) self._preroll_frames_notification = ui.Label("Running preroll frames, please wait...") ui.Spacer(width=ui.Percent(10)) def _build_ui(self): if self._window is None: style_settings = carb.settings.get_settings().get("/persistent/app/window/uiStyle") if not style_settings: style_settings = "NvidiaDark" self._window = ui.Window( self._window_caption, width=PROGRESS_WINDOW_WIDTH, height=PROGRESS_WINDOW_HEIGHT, style=PROGRESS_WIN_DARK_STYLE, ) with self._window.frame: with ui.VStack(): with ui.HStack(): ui.Spacer(width=ui.Percent(20)) self._progress_bar_area = ui.VStack() self._build_progress_bar() ui.Spacer(width=ui.Percent(20)) ui.Spacer(height=5) if self._is_single_frame_mode: self._build_single_frame_capture_timers() else: self._build_multi_frames_capture_timers() self._build_preroll_notification() with ui.HStack(): with ui.HStack(width=ui.Percent(50)): ui.Spacer() self._ui_pause_button = ui.Button( "Pause", height=0, clicked_fn=self._on_pause_clicked, enabled=self._support_pausing, style=PAUSE_BUTTON_STYLE[style_settings], name="pause", ) with ui.HStack(width=ui.Percent(50)): ui.Spacer(width=15) ui.Button("Cancel", height=0, clicked_fn=self._on_cancel_clicked) ui.Spacer() ui.Spacer() self._window.visible = True self._update_timers() def _on_pause_clicked(self): if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause": self._progress.capture_status = CaptureStatus.PAUSED self._ui_pause_button.text = "Resume" elif self._progress.capture_status == CaptureStatus.PAUSED: self._progress.capture_status = CaptureStatus.CAPTURING self._ui_pause_button.text = "Pause" def _on_cancel_clicked(self): if ( self._progress.capture_status == CaptureStatus.CAPTURING or self._progress.capture_status == CaptureStatus.PAUSED ): self._progress.capture_status = CaptureStatus.CANCELLED def _update_timers(self): if self._is_single_frame_mode: self._ui_elapsed_time.text = self._progress.elapsed_time self._ui_remaining_time.text = self._progress.estimated_time_remaining subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count.text = subframe_count self._ui_current_frame_time.text = self._progress.subframe_time self._ui_ave_frame_time.text = self._progress.average_time_per_subframe else: self._ui_elapsed_time.text = self._progress.elapsed_time self._ui_remaining_time.text = self._progress.estimated_time_remaining self._ui_current_frame_time.text = self._progress.current_frame_time if self._show_pt_subframes: subframes_str = f"{self._progress.path_trace_subframe_num}" self._ui_pt_subframes.text = subframes_str if self._show_pt_iterations: iter_str = f"{self._progress.path_trace_iteration_num}" self._ui_pt_iterations.text = iter_str self._ui_ave_frame_time.text = self._progress.average_frame_time self._ui_encoding_time.text = self._progress.encoding_time def _update_preroll_frames(self): if self._progress.is_prerolling(): msg = 'Running preroll frames {}/{}, please wait...'.format( self._progress.prerolled_frames, self._progress.total_preroll_frames ) self._preroll_frames_notification.text = msg else: self._preroll_frames_notification.visible = False def _on_update(self, event): self._update_preroll_frames() self._update_timers() self._progress_bar_len = ( PROGRESS_BAR_WIDTH - PROGRESS_BAR_HEIGHT ) * self._progress.progress + PROGRESS_BAR_HALF_HEIGHT self._build_progress_bar()
17,963
Python
38.052174
123
0.597228