file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/tests/__init__.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 .test_window import TestWindow
463
Python
50.55555
76
0.812095
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/tests/test_window.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__ = ["TestWindow"] from omni.example.ui_gradient_window import PropertyWindowExample from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import omni.kit.app import omni.kit.test EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests") class TestWindow(OmniUiTest): async def test_general(self): """Testing general look of section""" window = PropertyWindowExample("Test") await omni.kit.app.get_app().next_update_async() await self.docked_test_window( window=window, width=450, height=600, ) # Wait for images for _ in range(20): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
1,363
Python
34.894736
115
0.710198
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-22 ### Changed - Added README.md - Clean up the style a bit and change some of the widgets function name ## [1.0.0] - 2022-06-09 ### Added - Initial window
191
Markdown
16.454544
71
0.65445
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/README.md
# Gradient Window (omni.example.ui_gradient_window) ![](../data/preview.png) # Overview In this example, we create a window which heavily uses graident style in various widgets. The window is build using `omni.ui`. It contains the best practices of how to build customized widgets and leverage to reuse them without duplicating the code. ## [Tutorial](../tutorial/tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md) # Customized Widgets A customized widget can be a class or a function. It's not required to derive from anything. We build customized widget so that we can use them just like default `omni.ui` widgets which allows us to reuse the code and saves us from reinventing the wheel again and again. ## Gradient Image Gradient images are used a lot in this example. It is used in the customized slider and field background. Therefore, we encapsulate it into a function `build_gradient_image` which is a customized `ui.ImageWithProvider` under the hood. The `ImageWithProvider` has a source data which is generated by `ui.ByteImageProvider`. We define how to generate the byte data into a function called `generate_byte_data`. We use one pixel height data to generate the image data. For users' conveniences, we provide the function signature as an array of hex colors, so we provided a function to achieve `hex_to_color` conversion. ``` def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = (hex >> 16) & 255 alpha = (hex >> 24) & 255 rgba_values = [red, green, blue, alpha] return rgba_values def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) _byte_provider = ui.ByteImageProvider() _byte_provider.set_bytes_data(data, [len(colors), 1]) return _byte_provider def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name) return byte_provider ``` With this, the user will be able to generate gradient image easily which also allows flexibly set the height and style. Here are a couple of examples used in the example: ``` colors = cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")] byte_provider = build_gradient_image(colors, 8, "gradient_slider") cls_button_gradient = [cl("#232323"), cl("#656565")] button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient") ``` ![](../data/gradient_img.png) ## Value Changed Widget In this example, almost every attribute has got a widget which indicates whether the value has been changed or not. By default, the widget is a small gray rectangle, while the value has been changed it becomes a bigger blue rectangle. We wrapped this up into a function called `__build_value_changed_widget` and returns both rectangles so that the caller can switch the visiblity of them. It is not only an indicator of value change, it is also a button. While you click on it when the value has changed, it has the callback to restore the default value for the attribute. Since different attribute has different data model, the restore callbacks are added into different widgets instead of the value change widget itself. ## Gradient Float Slider Almost all the numeric attribute in this example is using gradient float slider which is defined by `_build_gradient_float_slider`. This customized float slider are consisted of three parts: the label, the float slider, and the value-changed-widget. The label is just a usual `ui.Label`. The slider is a normal `ui.FloatSlider` with a gradient image, composed by `ui.ZStack`. We also added the `add_value_changed_fn` callback for slider model change to trigger the value-changed-widget change visiblity and `rect_changed.set_mouse_pressed_fn` to add the callback to restore the default value of the silder. ``` rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider)) ``` ![](../data/gradient_float_slider.png) ## Customized CheckBox The customized Checkbox is defined by `_build_checkbox`. It is also consisted of three parts: the label, the check box, and the value-changed-widget. The label is just a usual `ui.Label`. For the check box, since we have completely two different images for the checked and unchecked status. Therefore, we use `ui.Image` as the base for the customized CheckBox. The `name` of the image is used to switch between the corresponding styles which changes the `image_url` for the image. The callbacks of value-changed-widget are added similarly as gradient float slider. ![](../data/checked.png) ![](../data/unchecked.png) ## Customized ComboBox The customized ComboBox is defined by `_build_combobox`. It is also consisted of three parts: the label, the ComnoBox, and the value-changed-widget. The label is just a usual `ui.Label`. The ComboBox is a normal `ui.ComboBox` with a gradient image, composed by `ui.ZStack`. The callbacks of value-changed-widget are added similarly as gradient float slider. ![](../data/combobox.png) ![](../data/combobox2.png) ## Customized CollsableFrame The customized CollsableFrame is wrapped in `CustomCollsableFrame` class. It is a normal `ui.CollapsableFrame` with a customized header. It is the main widget groups other widgets as a collapsable frame. ![](../data/collapse_frame.png) ## Customized ColorWidget The customized ColorWidget is wrapped in `ColorWidget` class. ![](../data/color_widget.png) The RGB values `self.__multifield` is represented by a normal `ui.MultiFloatDragField`, composed with three gradient images of red, green and blue using `ui.ZStack`, as well as the lable and circle dots in between the three values. The colorpicker is just a normal `ui.ColorWidget`, which shares the same model of `self.__multifield`, so that these two widgets are connected. We also added the `add_item_changed_fn` callback for the shared model. When the model item changes, it will trigger the value-changed-widget to switch the visiblity and `rect_changed.set_mouse_pressed_fn` to add the callback to restore the default value for the shared model. # Style We kept all the styles of all the widgets in `style.py`. One advantage is that specific style or colors could be reused without duplication. The other advantage is that users don't need to go through the lengthy widgets code to change the styles. All the styles are recommended to be arranged and named in a self-explanatory way. # Window It's handy to derive a custom window from the class `ui.Window`. The UI can be defined right in __init__, so it's created immediately or it can be defined in a `set_build_fn` callback and it will be created when the window is visible. The later one is used in this example. ``` class PropertyWindowExample(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) ``` Inside the `self._build_fn`, we use the customized widgets to match the design layout for the window. # Extension When the extension starts up, we register a new menu item that controls the window and shows the window. A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit. ``` ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) ``` When the extension shuts down, we remove the menu item and deregister the window callback.
8,457
Markdown
52.194968
614
0.753104
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/index.rst
omni.example.ui_gradient_window ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
161
reStructuredText
13.727271
40
0.534161
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/tutorial/tutorial.md
# How to Understand and Navigate Omniverse Code from Other Developers This tutorial teaches how to access, navigate and understand source code from extensions written by other developers. This is done by opening an extension, navigating to its code and learning how its user interface is put together. It also teaches how custom widgets are organized. With this information developers can find user interface elements in other developers' extensions and re-use or extend them. The extension itself is a UI mockup for a [julia quaternion modeling tool](http://paulbourke.net/fractals/quatjulia/). ## Learning Objectives - Access Source of Omniverse Extensions - Understand UI Code Structure - Re-use Widget Code from Other Developers ## Prerequisites - [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_window/tutorial/tutorial.md) - [UI Gradient Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_gradient_window/tutorial/tutorial.md) - Omniverse Code version 2022.1.1 or higher - Working understanding of GitHub - Visual Studio Code ## Step 1: Clone the Repository Clone the `main` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window): ```shell git clone https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git ``` This repository contains the code you use in this tutorial. ## Step 2: Add the Extension to Omniverse Code In order to use and test your Extension, you need to add it to Omniverse Code. ### Step 2.1: Navigate to the Extensions List In Omniverse Code, navigate to the *Extensions* panel: ![Click the Extensions panel](Images/extensions_panel.png) Here, you see a list of Omniverse Extensions that you can activate and use in Code. > **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**: > > ![Show the Extensions panel](Images/window_extensions.png) ### Step 2.2: Navigate to the *Extension Search Paths* Click the **gear** icon to open *Extension Search Paths*: ![Click the gear icon](Images/extension_search_paths.png) In this panel, you can add your custom Extension to the Extensions list. ### Step 2.3: Create a New Search Path Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field: ![New search path](Images/new_search_path_ui-window.png) When you submit your new search path, you should be able to find your extension in the *Extensions* list. Search for "omni.example.ui_" to filter down the list. Activate the "OMNI.UI JULIA QUATERNION MO..." Extension: ![Reticle extensions list](Images/window_extensions_list_ui-julia.png) Now that your Extension is added and enabled, you can make changes to the code and see them in your Application. You will see the user interface pictured below: <p align="center"> <img src="Images/JuliaUI.png" width=25%> <p> ## Step 3: View the User Interface and Source Code ### Step 3.1: Review the User Interface Take a moment to think like a connoisseur of excellent user interface elements. What aspects of this user interface are worth collecting? Notice the styling on the collapsable frames, the backgrounds on the sliders. Edit some of the values and notice that the arrow on the right is now highlighted in blue. Click on that arrow and notice that the slider returns to a default value. Focus on the best aspects because you can collect those and leave the lesser features behind. ### Step 3.2: Access the Source Code Now, go back to the extensions window and navigate to the `Julia` extension. Along the top of its details window lies a row of icons as pictured below: <p align="center"> <img src="Images/VisualStudioIcon.png" width=75%> <p> Click on the Visual Studio icon to open the Extension's source in Visual Studio. This is a great way to access extension source code and learn how they were written. ## Step 4: Find `extension.py` This section explains how to start navigation of an extension's source code. ### Step 4.1: Access the Extension Source Code Open the Visual Studio window and expand the `exts` folder. The image below will now be visible: <p align="center"> <img src="Images/FolderStructure.png" width=35%> <p> Click on `omni\example\ui_julia_modeler` to expand it and see the files in that folder as shown below: <p align="center"> <img src="Images/DevFiles.png" width=35%> <p> ### Step 4.2: Open `extension.py` The file named `extension.py` is a great place to start. It contains a class that derives from `omni.ext.IExt`. ### Step 4.3: Find the `on_startup` Function Look for the `on_startup`. This function runs when the extension first starts and is where the UI should be built. It has been included below: ```Python def on_startup(self): # The ability to show the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None)) # Add the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( JuliaModelerExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(JuliaModelerExtension.WINDOW_NAME) ``` This function does a few steps that are common for a window-based extension. Not all extensions will be written in exactly this way, but these are best practices and are good things to look for. 1. It registers a `show` function with the application. 2. It adds the extension to the `Window` application menu. 3. It requests that the window be shown using the `show` function registered before. ### Step 4.4: Find the Function that Builds the Window What function has been registered to show the `Julia` extension window? It is `self.show_window()`. Scroll down until you find it in `extension.py`. It has been included below for convenience: ```Python def show_window(self, menu, value): if value: self._window = JuliaModelerWindow( JuliaModelerExtension.WINDOW_NAME, width=WIN_WIDTH, height=WIN_HEIGHT) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False ``` In this function `value` is a boolean that is `True` if the window should be shown and `False` if the window should be hidden. Take a look at the code block that will run if `value` is `True` and you will see that `self._window` is set equal to a class constructor. ### Step 4.5: Navigate to the Window Class To find out where this class originates, hold the `ctrl` button and click on `JuliaModelerWindow` in the third line of the function. This will navigate to that symbol's definition. In this case it opens the `window.py` file and takes the cursor to definition of the `JuliaModelerWindow` class. The next section explores this class and how the window is built. ## Step 5: Explore `JuliaModelerWindow` This sections explores the `JuliaModelerWindow` class, continuing the exploration of this extension, navigating the code that builds the UI from the top level towards specific elements. ### Step 5.1: Read `show_window()` The `show_window()` function in the previous section called the constructor from the `JuliaModelerWindow` class. The constructor in Python is the `__init__()` function and is copied below: ```Python def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = ATTR_LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = julia_modeler_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) ``` The first statement simply sets a label width. The next statement calls `super().__init__()`. This initializes all base classes of `JuliaModelerWindow`. This has to do with inheritance, a topic that will be briefly covered later in this tutorial. The third statement sets the window style, which is useful information, but is the topic of another tutorial. These styles are contained in `style.py` for the curious. Finally, the function registers the `self._build_fn` callback as the frame's build function. This is the function of interest. ### Step 5.2: Navigate to `_build_fn()` Hold ctrl and click on `self._build_fn` which has been reproduced below: ```Python def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(name="window_bg", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): self._build_title() self._build_calculations() self._build_parameters() self._build_light_1() self._build_scene() ``` This function builds an outer scrolling frame, a vertical stack, and then builds a few sections to add to that stack. Each of these methods has useful information worth taking a look at, but this tutorial will focus on `_build_parameters()`. ### Step 5.3: Navigate to `_build_parameters()` Navigate to `_build_parameters` using ctrl+click. As usual, it is duplicated below: ```Python def _build_parameters(self): """Build the widgets of the "Parameters" group""" with ui.CollapsableFrame("Parameters".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=-2, max=2, display_range=True, label="Iterations", default_val=0.75) CustomSliderWidget(min=0, max=2, display_range=True, label="i", default_val=0.65) CustomSliderWidget(min=0, max=2, display_range=True, label="j", default_val=0.25) CustomSliderWidget(min=0, max=2, display_range=True, label="k", default_val=0.55) CustomSliderWidget(min=0, max=3.14, display_range=True, label="Theta", default_val=1.25) ``` Here is a collapsable frame, a vertical stack, and then instead of the horizontal stacks with combinations of labels and controls seen in the `UI_Window` tutorial, there is a list of custom controls. In fact, scrolling up and down the class to look at the other build functions reveals quite a few custom controls. These custom controls are what gives the user interface a variety of controls, maintains a consistent look and feel, and gives them all the same functionality to restore a default value. Taking a closer at constructor for each `CustomSliderWidget` above reveals that each sets a default value for its respective widget. ### Step 5.4: Identify Custom Widgets In the folder structure are a few files that look like they contain custom widgets, namely: - `custom_base_widget.py` - `custom_bool_widget.py` - `custom_color_widget.py` - `custom_combobox_widget.py` - `custom_multifield_widget.py` - `custom_path_widget.py` - `custom_radio_widget.py` - `custom_slider_widget.py` ### Step 5.5: Recognize Hierarchical Class Structure `custom_base_widget.py` contains `CustomBaseWidget` which many of the other widgets `inherit` from. For example, open one of the widget modules such as `custom_slider_widget.py` and take a look at its class declaration: ```Python class CustomSliderWidget(CustomBaseWidget): ``` There, in parentheses is `CustomBaseWidget`, confirming that this is a hierarchical class structure with the specific widgets inheriting from `CustomBaseWidget`. For those unfamiliar with inheritance, a quick explanation in the next section is in order. ## Step 6: Inheritance In Python (and other programming languages) it is possible to group classes together if they have some things in common but are different in other ways and this is called inheritance. With inheritance, a base class is made containing everything in common, and sub-classes are made that contain the specific elements of each object. 2D Shapes are a classic example. <p align="center"> <img src="Images/Shape.svg" width=35%> <p> In this case all shapes have a background color, you can get their area, and you can get their perimeter. Circles, however have a radius where rectangles have a length and a width. When you use inheritance, the common code can be in a single location in the base class where the sub-classes contain the specific code. The next step is to look at `CustomBaseWidget` to see what all of the custom widgets have in common. Either navigate to `custom_base_widget.py` or ctrl+click on `CustomBaseWidget` in any of the sub-classes. Inheritance is one element of object-oriented programming (OOP). To learn more about OOP, check out [this video](https://www.youtube.com/watch?v=pTB0EiLXUC8). To learn more about inheritance syntax in Python, check out [this article](https://www.w3schools.com/Python/Python_inheritance.asp). ## Step 7: Explore `custom_base_widget.py` This section explores the code in `custom_base_widget.py` ### Step 7.1: Identify Code Patterns The developer who wrote this extension has a consistent style, so you should see a lot in common between this class and `JuliaModelerWindow` class. It starts with `__init__()` and `destroy()` functions and further down has a few `_build` functions: `_build_head()`, `_build_body()`, `_build_tail()`, and `_build_fn()`. The `_build_fn()` function is called from the constructor and in turn calls each of the other build functions. ### Step 7.2: Characterize Custom Widget Layout From this it can be determined that each of the custom widgets has a head, body and tail and if we look at the controls in the UI this makes sense as illustrated below: <p align="center"> <img src="Images/HeadBodyTail.png" width=35%> <p> This image shows a vertical stack containing 5 widgets. Each widget is a collection of smaller controls. The first highlighted column contains the head of each widget, the second contains their content and the third holds each tail. This tutorial will now look at how the head, content, and tail are created in turn. ### Step 7.3: Inspect `_build_head()` `_build_head()` is as follows: ```Python def _build_head(self): """Build the left-most piece of the widget line (label in this case)""" ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) ``` It has a single label that displays the text passed into the widget's constructor. This makes sense when looking at the UI, each control has a label and they are all aligned. ### Step 7.4: Inspect `_build_body()` `_build_body()` is as follows: ```Python def _build_body(self): """Build the custom part of the widget. Most custom widgets will override this method, as it is where the meat of the custom widget is. """ ui.Spacer() ``` In the comments it says that most widgets will override this method. This has to do with the inheritance mentioned before. Just like with `GetArea()` in the shape class, each shape has an area, but that area is calculated differently. In this situation, the function is placed in the base class but each sub-class implements that function in its own way. In this case `_build_body()` is essentially empty, and if you look at each custom widget sub-class, they each have their own `_build_body()` function that runs in place of the one in `CustomBaseWidget`. ### Step 7.5: Inspect `_build_tail()` Finally, the `_build_tail()` function contains the following code: ```Python def _build_tail(self): """Build the right-most piece of the widget line. In this case, we have a Revert Arrow button at the end of each widget line. """ with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # call back for revert_img click, to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) ``` This function draws the reverse arrow that lets a user revert a control to a default value and is the same for every custom control. In this way the author of this extension has ensured that all of the custom widgets are well aligned, have a consistent look and feel and don't have the same code repeated in each class. They each implemented their own body, but other than that are the same. The next section will show how the widget body is implmeneted in the `CustomSliderWidget` class. ## Step 8: Explore `custom_slider_widget.py` To view the `CustomSliderWidget` class open `custom_slider_widget.py` and take a look at the `build_body()` function which contains the following code: ```Python def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() ``` This function is significantly longer than others in this tutorial and could be overwhelming at first glance. This is the perfect situation to take advantage of code folding. If you hover over the blank column between the line numbers and the code window inside visual studio, downward carrats will appear next to code blocks. Click on the carrats next to the two vertical stacks to collapse those blocks of code and make the function easier to navigate. <p align="center"> <img src="Images/FoldedCode.png" width=75%> <p> Now it's clear that this function creates an outer horizontal stack which contains two vertical stacks. If you dig deeper you will find that the first vertical stack contains a float slider with an image background. In order to learn how to create an image background like this, check out the [UI Gradient Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_gradient_window/tutorial/tutorial.md). The second vertical stack contains a number field which displays the number set by the float slider. If you take a look at the other custom widgets, you will see that each of them has its own `_build_body` function. Exploring these is a great way to get ideas on how to create your own user interface. ## Step 9: Reusing UI code By exploring extensions in this manner, developers can get a head start creating their own user interfaces. This can range from copying and pasting controls from other extensions, to creating new sub-classes on top of existing base classes, to simply reading and understanding the code written by others to learn from it. Hopefully this tutorial has given you a few tips and tricks as you navigate code written by others. ## Conclusion This tutorial has explained how to navigate the file and logical structure of a typical Omniverse extension. In addition it has explained how custom widgets work, even when they are part of a hieararchical inheritance structure.
22,207
Markdown
50.7669
634
0.701806
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/config/extension.toml
[package] title = "omni.ui Julia Quaternion Modeler Example" description = "A window example with custom UI elements" version = "1.0.1" category = "Example" authors = ["Alan Cheney"] repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows" keywords = ["example", "window", "ui", "julia_modeler"] changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.menu.utils" = {} "omni.kit.window.popup_dialog" = {} [[python.module]] name = "omni.example.ui_julia_modeler" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
771
TOML
23.903225
84
0.680934
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_radio_collection.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__ = ["CustomRadioCollection"] from typing import List, Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH SPACING = 5 class CustomRadioCollection: """A custom collection of radio buttons. The group_name is on the first line, and each label and radio button are on subsequent lines. This one does not inherit from CustomBaseWidget because it doesn't have the same Head label, and doesn't have a Revert button at the end. """ def __init__(self, group_name: str, labels: List[str], model: ui.AbstractItemModel = None, default_value: bool = True, **kwargs): self.__group_name = group_name self.__labels = labels self.__default_val = default_value self.__images = [] self.__selection_model = ui.SimpleIntModel(default_value) self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__images = [] self.__selection_model = None self.__frame = None @property def model(self) -> Optional[ui.AbstractValueModel]: """The widget's model""" if self.__selection_model: return self.__selection_model @model.setter def model(self, value: int): """The widget's model""" self.__selection_model.set(value) def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__frame, attr) def _on_value_changed(self, index: int = 0): """Set states of all radio buttons so only one is On.""" self.__selection_model.set_value(index) for i, img in enumerate(self.__images): img.checked = i == index img.name = "radio_on" if img.checked else "radio_off" def _build_fn(self): """Main meat of the widget. Draw the group_name label, label and radio button for each row, and set up callbacks to keep them updated. """ with ui.VStack(spacing=SPACING): ui.Spacer(height=2) ui.Label(self.__group_name.upper(), name="radio_group_name", width=ATTR_LABEL_WIDTH) for i, label in enumerate(self.__labels): with ui.HStack(): ui.Label(label, name="attribute_name", width=ATTR_LABEL_WIDTH) with ui.HStack(): with ui.VStack(): ui.Spacer(height=2) self.__images.append( ui.Image( name=("radio_on" if self.__default_val == i else "radio_off"), fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) ) ui.Spacer() ui.Spacer(height=2) # Set up a mouse click callback for each radio button image for i in range(len(self.__labels)): self.__images[i].set_mouse_pressed_fn( lambda x, y, b, m, i=i: self._on_value_changed(i))
3,781
Python
35.718446
98
0.556467
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/style.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__ = ["julia_modeler_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) ATTR_LABEL_WIDTH = 150 BLOCK_HEIGHT = 22 TAIL_WIDTH = 35 WIN_WIDTH = 400 WIN_HEIGHT = 930 # Pre-defined constants. It's possible to change them at runtime. cl.window_bg_color = cl(0.2, 0.2, 0.2, 1.0) cl.window_title_text = cl(.9, .9, .9, .9) cl.collapsible_header_text = cl(.8, .8, .8, .8) cl.collapsible_header_text_hover = cl(.95, .95, .95, 1.0) cl.main_attr_label_text = cl(.65, .65, .65, 1.0) cl.main_attr_label_text_hover = cl(.9, .9, .9, 1.0) cl.multifield_label_text = cl(.65, .65, .65, 1.0) cl.combobox_label_text = cl(.65, .65, .65, 1.0) cl.field_bg = cl(0.18, 0.18, 0.18, 1.0) cl.field_border = cl(1.0, 1.0, 1.0, 0.2) cl.btn_border = cl(1.0, 1.0, 1.0, 0.4) cl.slider_fill = cl(1.0, 1.0, 1.0, 0.3) cl.revert_arrow_enabled = cl(.25, .5, .75, 1.0) cl.revert_arrow_disabled = cl(.35, .35, .35, 1.0) cl.transparent = cl(0, 0, 0, 0) fl.main_label_attr_hspacing = 10 fl.attr_label_v_spacing = 3 fl.collapsable_group_spacing = 2 fl.outer_frame_padding = 15 fl.tail_icon_width = 15 fl.border_radius = 3 fl.border_width = 1 fl.window_title_font_size = 18 fl.field_text_font_size = 14 fl.main_label_font_size = 14 fl.multi_attr_label_font_size = 14 fl.radio_group_font_size = 14 fl.collapsable_header_font_size = 13 fl.range_text_size = 10 url.closed_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/closed.svg" url.open_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/opened.svg" url.revert_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/revert_arrow.svg" url.checkbox_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_on.svg" url.checkbox_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_off.svg" url.radio_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_on.svg" url.radio_btn_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_off.svg" url.diag_bg_lines_texture = f"{EXTENSION_FOLDER_PATH}/icons/diagonal_texture_screenshot.png" # The main style dict julia_modeler_style = { "Button::tool_button": { "background_color": cl.field_bg, "margin_height": 0, "margin_width": 6, "border_color": cl.btn_border, "border_width": fl.border_width, "font_size": fl.field_text_font_size, }, "CollapsableFrame::group": { "margin_height": fl.collapsable_group_spacing, "background_color": cl.transparent, }, # TODO: For some reason this ColorWidget style doesn't respond much, if at all (ie, border_radius, corner_flag) "ColorWidget": { "border_radius": fl.border_radius, "border_color": cl(0.0, 0.0, 0.0, 0.0), }, "Field": { "background_color": cl.field_bg, "border_radius": fl.border_radius, "border_color": cl.field_border, "border_width": fl.border_width, }, "Field::attr_field": { "corner_flag": ui.CornerFlag.RIGHT, "font_size": 2, # fl.field_text_font_size, # Hack to allow for a smaller field border until field padding works }, "Field::attribute_color": { "font_size": fl.field_text_font_size, }, "Field::multi_attr_field": { "padding": 4, # TODO: Hacky until we get padding fix "font_size": fl.field_text_font_size, }, "Field::path_field": { "corner_flag": ui.CornerFlag.RIGHT, "font_size": fl.field_text_font_size, }, "HeaderLine": {"color": cl(.5, .5, .5, .5)}, "Image::collapsable_opened": { "color": cl.collapsible_header_text, "image_url": url.open_arrow_icon, }, "Image::collapsable_opened:hovered": { "color": cl.collapsible_header_text_hover, "image_url": url.open_arrow_icon, }, "Image::collapsable_closed": { "color": cl.collapsible_header_text, "image_url": url.closed_arrow_icon, }, "Image::collapsable_closed:hovered": { "color": cl.collapsible_header_text_hover, "image_url": url.closed_arrow_icon, }, "Image::radio_on": {"image_url": url.radio_btn_on_icon}, "Image::radio_off": {"image_url": url.radio_btn_off_icon}, "Image::revert_arrow": { "image_url": url.revert_arrow_icon, "color": cl.revert_arrow_enabled, }, "Image::revert_arrow:disabled": {"color": cl.revert_arrow_disabled}, "Image::checked": {"image_url": url.checkbox_on_icon}, "Image::unchecked": {"image_url": url.checkbox_off_icon}, "Image::slider_bg_texture": { "image_url": url.diag_bg_lines_texture, "border_radius": fl.border_radius, "corner_flag": ui.CornerFlag.LEFT, }, "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_TOP, "margin_height": fl.attr_label_v_spacing, "margin_width": fl.main_label_attr_hspacing, "color": cl.main_attr_label_text, "font_size": fl.main_label_font_size, }, "Label::attribute_name:hovered": {"color": cl.main_attr_label_text_hover}, "Label::collapsable_name": {"font_size": fl.collapsable_header_font_size}, "Label::multi_attr_label": { "color": cl.multifield_label_text, "font_size": fl.multi_attr_label_font_size, }, "Label::radio_group_name": { "font_size": fl.radio_group_font_size, "alignment": ui.Alignment.CENTER, "color": cl.main_attr_label_text, }, "Label::range_text": { "font_size": fl.range_text_size, }, "Label::window_title": { "font_size": fl.window_title_font_size, "color": cl.window_title_text, }, "ScrollingFrame::window_bg": { "background_color": cl.window_bg_color, "padding": fl.outer_frame_padding, "border_radius": 20 # Not obvious in a window, but more visible with only a frame }, "Slider::attr_slider": { "draw_mode": ui.SliderDrawMode.FILLED, "padding": 0, "color": cl.transparent, # Meant to be transparent, but completely transparent shows opaque black instead. "background_color": cl(0.28, 0.28, 0.28, 0.01), "secondary_color": cl.slider_fill, "border_radius": fl.border_radius, "corner_flag": ui.CornerFlag.LEFT, # TODO: Not actually working yet OM-53727 }, # Combobox workarounds "Rectangle::combobox": { # TODO: remove when ComboBox can have a border "background_color": cl.field_bg, "border_radius": fl.border_radius, "border_color": cl.btn_border, "border_width": fl.border_width, }, "ComboBox::dropdown_menu": { "color": cl.combobox_label_text, # label color "padding_height": 1.25, "margin": 2, "background_color": cl.field_bg, "border_radius": fl.border_radius, "font_size": fl.field_text_font_size, "secondary_color": cl.transparent, # button background color }, "Rectangle::combobox_icon_cover": {"background_color": cl.field_bg} }
7,532
Python
36.854271
121
0.633696
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/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__ = ["JuliaModelerExtension"] import asyncio from functools import partial import omni.ext import omni.kit.ui import omni.ui as ui from .style import WIN_WIDTH, WIN_HEIGHT from .window import JuliaModelerWindow class JuliaModelerExtension(omni.ext.IExt): """The entry point for Julia Modeler Example Window.""" WINDOW_NAME = "Julia Quaternion Modeler" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None)) # Add the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( JuliaModelerExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(JuliaModelerExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(JuliaModelerExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user presses "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating a new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = JuliaModelerWindow( JuliaModelerExtension.WINDOW_NAME, width=WIN_WIDTH, height=WIN_HEIGHT) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
2,948
Python
35.407407
107
0.662144
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import JuliaModelerExtension
478
Python
46.899995
76
0.8159
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_bool_widget.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__ = ["CustomBoolWidget"] import omni.ui as ui from .custom_base_widget import CustomBaseWidget class CustomBoolWidget(CustomBaseWidget): """A custom checkbox or switch widget""" def __init__(self, model: ui.AbstractItemModel = None, default_value: bool = True, **kwargs): self.__default_val = default_value self.__bool_image = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__bool_image = None def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.__bool_image.checked = self.__default_val self.__bool_image.name = ( "checked" if self.__bool_image.checked else "unchecked" ) self.revert_img.enabled = False def _on_value_changed(self): """Swap checkbox images and set revert_img to correct state.""" self.__bool_image.checked = not self.__bool_image.checked self.__bool_image.name = ( "checked" if self.__bool_image.checked else "unchecked" ) self.revert_img.enabled = self.__default_val != self.__bool_image.checked def _build_body(self): """Main meat of the widget. Draw the appropriate checkbox image, and set up callback. """ with ui.HStack(): with ui.VStack(): # Just shift the image down slightly (2 px) so it's aligned the way # all the other rows are. ui.Spacer(height=2) self.__bool_image = ui.Image( name="checked" if self.__default_val else "unchecked", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) # Let this spacer take up the rest of the Body space. ui.Spacer() self.__bool_image.set_mouse_pressed_fn( lambda x, y, b, m: self._on_value_changed())
2,626
Python
37.072463
87
0.604722
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_multifield_widget.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__ = ["CustomMultifieldWidget"] from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget class CustomMultifieldWidget(CustomBaseWidget): """A custom multifield widget with a variable number of fields, and customizable sublabels. """ def __init__(self, model: ui.AbstractItemModel = None, sublabels: Optional[List[str]] = None, default_vals: Optional[List[float]] = None, **kwargs): self.__field_labels = sublabels or ["X", "Y", "Z"] self.__default_vals = default_vals or [0.0] * len(self.__field_labels) self.__multifields = [] # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__multifields = [] @property def model(self, index: int = 0) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__multifields: return self.__multifields[index].model @model.setter def model(self, value: ui.AbstractItemModel, index: int = 0): """The widget's model""" self.__multifields[index].model = value def _restore_default(self): """Restore the default values.""" if self.revert_img.enabled: for i in range(len(self.__multifields)): model = self.__multifields[i].model model.as_float = self.__default_vals[i] self.revert_img.enabled = False def _on_value_changed(self, val_model: ui.SimpleFloatModel, index: int): """Set revert_img to correct state.""" val = val_model.as_float self.revert_img.enabled = self.__default_vals[index] != val def _build_body(self): """Main meat of the widget. Draw the multiple Fields with their respective labels, and set up callbacks to keep them updated. """ with ui.HStack(): for i, (label, val) in enumerate(zip(self.__field_labels, self.__default_vals)): with ui.HStack(spacing=3): ui.Label(label, name="multi_attr_label", width=0) model = ui.SimpleFloatModel(val) # TODO: Hopefully fix height after Field padding bug is merged! self.__multifields.append( ui.FloatField(model=model, name="multi_attr_field")) if i < len(self.__default_vals) - 1: # Only put space between fields and not after the last one ui.Spacer(width=15) for i, f in enumerate(self.__multifields): f.model.add_value_changed_fn(lambda v: self._on_value_changed(v, i))
3,255
Python
39.19753
92
0.614132
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_color_widget.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__ = ["CustomColorWidget"] from ctypes import Union import re from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget from .style import BLOCK_HEIGHT COLOR_PICKER_WIDTH = ui.Percent(35) FIELD_WIDTH = ui.Percent(65) COLOR_WIDGET_NAME = "color_block" SPACING = 4 class CustomColorWidget(CustomBaseWidget): """The compound widget for color input. The color picker widget model converts its 3 RGB values into a comma-separated string, to display in the StringField. And vice-versa. """ def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = [a for a in args if a is not None] self.__strfield: Optional[ui.StringField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__color_sub = None self.__strfield_sub = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__strfield = None self.__colorpicker = None self.__color_sub = None self.__strfield_sub = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__colorpicker: return self.__colorpicker.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__colorpicker.model = value @staticmethod def simplify_str(val): s = str(round(val, 3)) s_clean = re.sub(r'0*$', '', s) # clean trailing 0's s_clean = re.sub(r'[.]$', '', s_clean) # clean trailing . s_clean = re.sub(r'^0', '', s_clean) # clean leading 0 return s_clean def set_color_stringfield(self, item_model: ui.AbstractItemModel, children: List[ui.AbstractItem]): """Take the colorpicker model that has 3 child RGB values, convert them to a comma-separated string, and set the StringField value to that string. Args: item_model: Colorpicker model children: child Items of the colorpicker """ field_str = ", ".join([self.simplify_str(item_model.get_item_value_model(c).as_float) for c in children]) self.__strfield.model.set_value(field_str) if self.revert_img: self._on_value_changed() def set_color_widget(self, str_model: ui.SimpleStringModel, children: List[ui.AbstractItem]): """Parse the new StringField value and set the ui.ColorWidget component items to the new values. Args: str_model: SimpleStringModel for the StringField children: Child Items of the ui.ColorWidget's model """ joined_str = str_model.get_value_as_string() for model, comp_str in zip(children, joined_str.split(",")): comp_str_clean = comp_str.strip() try: self.__colorpicker.model.get_item_value_model(model).as_float = float(comp_str_clean) except ValueError: # Usually happens in the middle of typing pass def _on_value_changed(self, *args): """Set revert_img to correct state.""" default_str = ", ".join([self.simplify_str(val) for val in self.__defaults]) cur_str = self.__strfield.model.as_string self.revert_img.enabled = default_str != cur_str def _restore_default(self): """Restore the default values.""" if self.revert_img.enabled: field_str = ", ".join([self.simplify_str(val) for val in self.__defaults]) self.__strfield.model.set_value(field_str) self.revert_img.enabled = False def _build_body(self): """Main meat of the widget. Draw the colorpicker, stringfield, and set up callbacks to keep them updated. """ with ui.HStack(spacing=SPACING): # The construction of the widget depends on what the user provided, # defaults or a model if self.existing_model: # the user provided a model self.__colorpicker = ui.ColorWidget( self.existing_model, width=COLOR_PICKER_WIDTH, height=BLOCK_HEIGHT, name=COLOR_WIDGET_NAME ) color_model = self.existing_model else: # the user provided a list of default values self.__colorpicker = ui.ColorWidget( *self.__defaults, width=COLOR_PICKER_WIDTH, height=BLOCK_HEIGHT, name=COLOR_WIDGET_NAME ) color_model = self.__colorpicker.model self.__strfield = ui.StringField(width=FIELD_WIDTH, name="attribute_color") self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn( lambda m, _, children=color_model.get_item_children(): self.set_color_stringfield(m, children)) self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn( lambda m, children=color_model.get_item_children(): self.set_color_widget(m, children)) # show data at the start self.set_color_stringfield(self.__colorpicker.model, children=color_model.get_item_children())
6,076
Python
39.245033
101
0.59842
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_combobox_widget.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__ = ["CustomComboboxWidget"] from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget from .style import BLOCK_HEIGHT class CustomComboboxWidget(CustomBaseWidget): """A customized combobox widget""" def __init__(self, model: ui.AbstractItemModel = None, options: List[str] = None, default_value=0, **kwargs): self.__default_val = default_value self.__options = options or ["1", "2", "3"] self.__combobox_widget = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__options = None self.__combobox_widget = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__combobox_widget: return self.__combobox_widget.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__combobox_widget.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" model = self.__combobox_widget.model index = model.get_item_value_model().get_value_as_int() self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.__combobox_widget.model.get_item_value_model().set_value( self.__default_val) self.revert_img.enabled = False def _build_body(self): """Main meat of the widget. Draw the Rectangle, Combobox, and set up callbacks to keep them updated. """ with ui.HStack(): with ui.ZStack(): # TODO: Simplify when borders on ComboBoxes work in Kit! # and remove style rule for "combobox" Rect # Use the outline from the Rectangle for the Combobox ui.Rectangle(name="combobox", height=BLOCK_HEIGHT) option_list = list(self.__options) self.__combobox_widget = ui.ComboBox( 0, *option_list, name="dropdown_menu", # Abnormal height because this "transparent" combobox # has to fit inside the Rectangle behind it height=10 ) # Swap for different dropdown arrow image over current one with ui.HStack(): ui.Spacer() # Keep it on the right side with ui.VStack(width=0): # Need width=0 to keep right-aligned ui.Spacer(height=5) with ui.ZStack(): ui.Rectangle(width=15, height=15, name="combobox_icon_cover") ui.Image(name="collapsable_closed", width=12, height=12) ui.Spacer(width=2) # Right margin ui.Spacer(width=ui.Percent(30)) self.__combobox_widget.model.add_item_changed_fn(self._on_value_changed)
3,724
Python
37.010204
89
0.585124
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_path_button.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__ = ["CustomPathButtonWidget"] from typing import Callable, Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH, BLOCK_HEIGHT class CustomPathButtonWidget: """A compound widget for holding a path in a StringField, and a button that can perform an action. TODO: Get text ellision working in the path field, to start with "..." """ def __init__(self, label: str, path: str, btn_label: str, btn_callback: Callable): self.__attr_label = label self.__pathfield: ui.StringField = None self.__path = path self.__btn_label = btn_label self.__btn = None self.__callback = btn_callback self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__pathfield = None self.__btn = None self.__callback = None self.__frame = None @property def model(self) -> Optional[ui.AbstractItem]: """The widget's model""" if self.__pathfield: return self.__pathfield.model @model.setter def model(self, value: ui.AbstractItem): """The widget's model""" self.__pathfield.model = value def get_path(self): return self.model.as_string def _build_fn(self): """Draw all of the widget parts and set up callbacks.""" with ui.HStack(): ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) self.__pathfield = ui.StringField( name="path_field", height=BLOCK_HEIGHT, width=ui.Fraction(2), ) # TODO: Add clippingType=ELLIPSIS_LEFT for long paths self.__pathfield.model.set_value(self.__path) self.__btn = ui.Button( self.__btn_label, name="tool_button", height=BLOCK_HEIGHT, width=ui.Fraction(1), clicked_fn=lambda path=self.get_path(): self.__callback(path), )
2,599
Python
30.707317
78
0.576376
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_slider_widget.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__ = ["CustomSliderWidget"] from typing import Optional import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl from .custom_base_widget import CustomBaseWidget NUM_FIELD_WIDTH = 50 SLIDER_WIDTH = ui.Percent(100) FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18 SPACING = 4 TEXTURE_NAME = "slider_bg_texture" class CustomSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=1.0, default_val=0.0, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed)
6,797
Python
40.451219
105
0.529351
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_base_widget.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__ = ["CustomBaseWidget"] from typing import Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH class CustomBaseWidget: """The base widget for custom widgets that follow the pattern of Head (Label), Body Widgets, Tail Widget""" def __init__(self, *args, model=None, **kwargs): self.existing_model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.revert_img = None self.__attr_label: Optional[str] = kwargs.pop("label", "") self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.existing_model = None self.revert_img = None self.__attr_label = None self.__frame = None def __getattr__(self, attr): """Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__frame, attr) def _build_head(self): """Build the left-most piece of the widget line (label in this case)""" ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) def _build_body(self): """Build the custom part of the widget. Most custom widgets will override this method, as it is where the meat of the custom widget is. """ ui.Spacer() def _build_tail(self): """Build the right-most piece of the widget line. In this case, we have a Revert Arrow button at the end of each widget line. """ with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # call back for revert_img click, to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) def _build_fn(self): """Puts the 3 pieces together.""" with ui.HStack(): self._build_head() self._build_body() self._build_tail()
2,781
Python
32.518072
87
0.591514
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/window.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__ = ["JuliaModelerWindow"] import omni.ui as ui from omni.kit.window.popup_dialog import MessageDialog from .custom_bool_widget import CustomBoolWidget from .custom_color_widget import CustomColorWidget from .custom_combobox_widget import CustomComboboxWidget from .custom_multifield_widget import CustomMultifieldWidget from .custom_path_button import CustomPathButtonWidget from .custom_radio_collection import CustomRadioCollection from .custom_slider_widget import CustomSliderWidget from .style import julia_modeler_style, ATTR_LABEL_WIDTH SPACING = 5 class JuliaModelerWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = ATTR_LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = julia_modeler_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) def destroy(self): # Destroys all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def on_export_btn_click(self, path): """Sample callback that is used when the Export button is pressed.""" dialog = MessageDialog( title="Button Pressed Dialog", message=f"Export Button was clicked with path inside: {path}", disable_cancel_button=True, ok_handler=lambda dialog: dialog.hide() ) dialog.show() def _build_title(self): with ui.VStack(): ui.Spacer(height=10) ui.Label("JULIA QUATERNION MODELER - 1.0", name="window_title") ui.Spacer(height=10) def _build_collapsable_header(self, collapsed, title): """Build a custom title of CollapsableFrame""" with ui.VStack(): ui.Spacer(height=8) with ui.HStack(): ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, width=10, height=10) ui.Spacer(height=8) ui.Line(style_type_name_override="HeaderLine") def _build_calculations(self): """Build the widgets of the "Calculations" group""" with ui.CollapsableFrame("Calculations".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=0, max=20, num_type="int", label="Precision", default_val=6) CustomSliderWidget(min=0, max=20, num_type="int", label="Iterations", default_val=10) def _build_parameters(self): """Build the widgets of the "Parameters" group""" with ui.CollapsableFrame("Parameters".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=-2, max=2, display_range=True, label="Iterations", default_val=0.75) CustomSliderWidget(min=0, max=2, display_range=True, label="i", default_val=0.65) CustomSliderWidget(min=0, max=2, display_range=True, label="j", default_val=0.25) CustomSliderWidget(min=0, max=2, display_range=True, label="k", default_val=0.55) CustomSliderWidget(min=0, max=3.14, display_range=True, label="Theta", default_val=1.25) def _build_light_1(self): """Build the widgets of the "Light 1" group""" with ui.CollapsableFrame("Light 1".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomMultifieldWidget( label="Orientation", default_vals=[0.0, 0.0, 0.0] ) CustomSliderWidget(min=0, max=1.75, label="Intensity", default_val=1.75) CustomColorWidget(1.0, 0.875, 0.5, label="Color") CustomBoolWidget(label="Shadow", default_value=True) CustomSliderWidget(min=0, max=2, label="Shadow Softness", default_val=.1) def _build_scene(self): """Build the widgets of the "Scene" group""" with ui.CollapsableFrame("Scene".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=0, max=160, display_range=True, num_type="int", label="Field of View", default_val=60) CustomMultifieldWidget( label="Orientation", default_vals=[0.0, 0.0, 0.0] ) CustomSliderWidget(min=0, max=2, label="Camera Distance", default_val=.1) CustomBoolWidget(label="Antialias", default_value=False) CustomBoolWidget(label="Ambient Occlusion", default_value=True) CustomMultifieldWidget( label="Ambient Distance", sublabels=["Min", "Max"], default_vals=[0.0, 200.0] ) CustomComboboxWidget(label="Ambient Falloff", options=["Linear", "Quadratic", "Cubic"]) CustomColorWidget(.6, 0.62, 0.9, label="Background Color") CustomRadioCollection("Render Method", labels=["Path Traced", "Volumetric"], default_value=1) CustomPathButtonWidget( label="Export Path", path=".../export/mesh1.usd", btn_label="Export", btn_callback=self.on_export_btn_click, ) ui.Spacer(height=10) def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(name="window_bg", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): self._build_title() self._build_calculations() self._build_parameters() self._build_light_1() self._build_scene()
7,703
Python
37.909091
100
0.564975
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-23 ### Added - Readme ## [1.0.0] - 2022-06-22 ### Added - Initial window
108
Markdown
9.899999
23
0.555556
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/README.md
# Julia Modeler (omni.example.ui_julia_modeler) ![](../data/preview.png) ## Overview In this example, we create a window which uses custom widgets that follow a similar pattern. The window is built using `omni.ui`. It contains the best practices of how to build customized widgets and reuse them without duplicating the code. The structure is very similar to that of `omni.example.ui_window`, so we won't duplicate all of that same documentation here. ## [Tutorial](../tutorial/tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md) ## Usage This is just a UI demo. You can interact with the various controls, but they have not additional effect in the Application. ## Explanations ### Custom Widgets Because this design had a pattern for most of its attribute rows, like: `<head><body><tail>` where "head" is always the same kind of attribute label, the "body" is the customized part of the widget, and then the "tail" is either a revert arrow button, or empty space, we decided it would be useful to make a base class for all of the similar custom widgets, to reduce code duplication, and to make sure that the 3 parts always line up in the UI. ![](../data/similar_widget_structure.png) By structuring the base class with 3 main methods for building the 3 sections, child classes can focus on just building the "body" section, by implementing `_build_body()`. These are the 3 main methods in the base class, and the `_build_fn()` method that puts them all together: ```python def _build_head(self): # The main attribute label ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) def _build_body(self): # Most custom widgets will override this method, # as it is where the meat of the custom widget is ui.Spacer() def _build_tail(self): # In this case, we have a Revert Arrow button # at the end of each widget line with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # add call back to revert_img click to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) def _build_fn(self): # Put all the parts together with ui.HStack(): self._build_head() self._build_body() self._build_tail() ``` and this is an example of implementing `_build_body()` in a child class: ```python def _build_body(self): with ui.HStack(): with ui.VStack(): ui.Spacer(height=2) self.__bool_image = ui.Image( name="checked" if self.__default_val else "unchecked", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) ui.Spacer() self.__bool_image.set_mouse_pressed_fn( lambda x, y, b, m: self._on_value_changed()) ``` #### Value Changed "Revert" Widget In this example, almost every attribute row has a widget which indicates whether the value has been changed or not. By default, the revert arrow button is disabled and gray, and when the value has been changed it turns light blue and is enabled. Most of the functionality for this widget lives in the CustomBaseWidget class. The base class also calls a _restore_value method that needs to be implemented in the child class. Each child class can handle attribute values differently, so the logic of how to revert back needs to live at that level. The child class also takes care of enabling the revert button when the value has changed, turning it blue. ![](../data/revert_enabled.png) ![](../data/revert_disabled.png) #### Custom Int/Float Slider ![](../data/custom_float_slider.png) At a high level, this custom widget is just the combination of a `ui.FloatSlider` or `ui.IntSlider` and a `ui.FloatField` or `ui.IntField`. But there are a few more aspects that make this widget interesting: - The background of the slider has a diagonal lines texture. To accomplish that, a tiled image of that texture is placed behind the rest of the widget using a ZStack. A Slider is placed over top, almost completely transparent. The background color is transparent and the text is transparent. The foreground color, called the `secondary_color` is light gray with some transparency to let the texture show through. - Immediately below the slider is some optional tiny text that denotes the range of the slider. If both min and max are positive or both are negative, only the endpoints are shown. If the min is negative, and the max is positive, however, the 0 point is also added in between, based on where it would be. That tiny text is displayed by using `display_range=True` when creating a `CustomSliderWidget`. - There was a bug with sliders and fields around how the padding worked. It is fixed and will be available in the next version of Kit, but until then, there was a workaround to make things look right: a ui.Rectangle with the desired border is placed behind a ui.FloatField. The Field has a transparent background so all that shows up from it is the text. That way the Slider and Field can line up nicely and the text in the Field can be the same size as with other widgets in the UI. #### Customized ColorWidget The customized ColorWidget wraps a `ui.ColorWidget` widget and a `ui.StringField` widget in a child class of CustomBaseWidget. ![](../data/custom_color_widget.png) The colorpicker widget is a normal `ui.ColorWidget`, but the text part is really just a `ui.StringField` with comma-separated values, rather than a `ui.MultiFloatDragField` with separate R, G, and B values. So it wasn't as easy to just use the same model for both. Instead, to make them connect in both directions, we set up a callback for each widget, so that each would update the other one on any changes: ```python self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn( lambda m, _, children=color_model.get_item_children(): self.set_color_stringfield(m, children)) self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn( lambda m, children=color_model.get_item_children(): self.set_color_widget(m, children)) ``` #### Custom Path & Button Widget The Custom Path & Button widget doesn't follow quite the same pattern as most of the others, because it doesn't have a Revert button at the end, and the Field and Button take different proportions of the space. ![](../data/custom_path_button.png) In the widget's `_build_fn()` method, we draw the entire row all in one place. There's the typical label on the left, a StringField in the middle, and a Button at the end: ```python with ui.HStack(): ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) self.__pathfield = ui.StringField( name="path_field", height=BLOCK_HEIGHT, width=ui.Fraction(2), ) self.__pathfield.model.set_value(self.__path) self.__btn = ui.Button( self.__btn_label, name="tool_button", height=BLOCK_HEIGHT, width=ui.Fraction(1), clicked_fn=lambda path=self.get_path(): self.__callback(path), ) ``` All of those strings for labels and paths are customizable when creating the Widget. In window.py, this is how we instantiate the Export-style version: _(Note: In a real situation we would use the entire path, but we added the "..." ellipsis to show an ideal way to clip the text in the future.)_ ```python CustomPathButtonWidget( label="Export Path", path=".../export/mesh1.usd", btn_label="Export", btn_callback=self.on_export_btn_click, ) ``` And we show a sample callback hooked up to the button -- `self.on_export_btn_click`, which for this example, just pops up a MessageDialog telling the user what the path was that is in the Field: ```python def on_export_btn_click(self, path): """Sample callback that is used when the Export button is pressed.""" dialog = MessageDialog( title="Button Pressed Dialog", message=f"Export Button was clicked with path inside: {path}", disable_cancel_button=True, ok_handler=lambda dialog: dialog.hide() ) dialog.show() ``` ### Style Although the style can be applied to any widget, we recommend keeping the style dictionary in one location, such as `styles.py`. One comment on the organization of the styles. You may notice named constants that seem redundant, that could be consolidated, such as multiple font type sizes that are all `14`. ```python fl.window_title_font_size = 18 fl.field_text_font_size = 14 fl.main_label_font_size = 14 fl.multi_attr_label_font_size = 14 fl.radio_group_font_size = 14 fl.collapsable_header_font_size = 13 fl.range_text_size = 10 ``` While you definitely _could_ combine all of those into a single constant, it can be useful to break them out by type of label/text, so that if you later decide that you want just the Main Labels to be `15` instead of `14`, you can adjust just the one constant, without having to break out all of the other types of text that were using the same font size by coincidence. This same organization applies equally well to color assignments also. ### Window It's handy to derive a custom window from the class `ui.Window`. The UI can be defined right in `__init__`, so it's created immediately or it can be defined in a `set_build_fn` callback and it will be created when the window is visible. The later one is used in this example. ```python class PropertyWindowExample(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = julia_modeler_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) ``` Inside the `self._build_fn`, we use the customized widgets to match the design layout for the window. ### Extension When the extension starts up, we register a new menu item that controls the window and shows the window. A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit. ```python ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None)) ``` When the extension shuts down, we remove the menu item and deregister the window callback.
11,458
Markdown
49.480176
486
0.686245
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/index.rst
omni.example.ui_julia_modeler ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
159
reStructuredText
13.545453
40
0.528302
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/tutorial/tutorial.md
# UI Window Tutorial In this tutorial, you learn how to create an Omniverse Extension that has a window and user interface (UI) elements inside that window. ## Learning Objectives * Create a window. * Add it to the **Window** menu. * Add various control widgets into different collapsable group with proper layout and alignment. ## Step 1: Clone the Repository Clone the `ui-window-tutorial-start` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/ui-window-tutorial-start): ```shell git clone -b ui-window-tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git ``` This repository contains the starting code you use in this tutorial. ## Step 2: Add the Extension to Omniverse Code In order to use and test your Extension, you need to add it to Omniverse Code. ### Step 2.1: Navigate to the Extensions List In Omniverse Code, navigate to the *Extensions* panel: ![Click the Extensions panel](Images/extensions_panel.png) Here, you see a list of Omniverse Extensions that you can activate and use in Code. > **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**: > > ![Show the Extensions panel](Images/window_extensions.png) ### Step 2.2: Navigate to the *Extension Search Paths* Click the **gear** icon to open *Extension Search Paths*: ![Click the gear icon](Images/extension_search_paths.png) In this panel, you can add your custom Extension to the Extensions list. ### Step 2.3: Create a New Search Path Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field: ![New search path](Images/new_search_path_ui-window.png) When you submit your new search path, you should be able to find your extension in the *Extensions* list. Search for "omni.example.ui_" to filter down the list. Activate the "OMNI.UI WINDOW EXAMPLE" Extension: ![Reticle extensions list](Images/window_extensions_list_ui-window.png) Now that your Extension is added and enabled, you can make changes to the code and see them in your Application. ## Step 3: Create A Window In this section, you create an empty window that you can hide and show and is integrated into the **Application** menu. This window incorporates a few best practices so that it's well-connected with Omniverse and feels like a natural part of the application it's being used from. You do all of this in the `extension.py` file. ### Step 3.1: Support Hide/Show Windows can be hidden and shown from outside the window code that you write. If you would like Omniverse to be able to show a window after it has been hidden, you must register a callback function to run when the window visibility changes. To do this, open the `extension.py` file, go to the `on_startup()` definition, and edit the function to match the following code: ```python def on_startup(self): # The ability to show the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Add a Menu Item for the window # Show the window through the 'set_show_window_fn' you wired up above # It will call `self.show_window` ``` The added line registers the `self.show_window` callback to be run whenever the visibility of your extension is changed. The `pass` line of code is deleted because it is no longer necessary. It was only included because all code had been removed from that function. ### Step 3.2: Add a Menu Item It is helpful to add extensions to the application menu so that if a user closes a window they can reopen it. This is done by adding the following code to `on_startup()`: ```python def on_startup(self): # The ability to show the window if the system requires it. # You use it in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Add a Menu Item for the window editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window through the 'set_show_window_fn' you wired up above # It will call `self.show_window` ``` The first added line grabs a reference to the application menu. The second new line adds a new menu item where `MENU_PATH` determines where the menu item will appear in the menu system, and `self.show_window` designates the function to run when the user toggles the window visibility by clicking on the menu item. ### Step 3.3: Show the Window To finish with `on_startup()`, add the following: ```python def on_startup(self): # The ability to show the window if the system requires it. # You use it in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Add a Menu Item for the window editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window through the 'set_show_window_fn' you wired up above # It will call `self.show_window` ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME) ``` This calls `show_window()` through the registration you set up earlier. ### Step 3.4: Call the Window Constructor Finally, in the `extension.py` file, scroll down to the `show_window` method which is currently the code below: ```python def show_window(self, menu, value): #value is true if the window should be shown if value: #call our custom window constructor #Handles the change in visibility of the window gracefuly self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False ``` Add the following line to this function: ```python def show_window(self, menu, value): #value is true if the window should be shown if value: #call our custom window constructor self._window = ExampleWindow(ExampleWindowExtension.WINDOW_NAME, width=300, height=365) #Handles the change in visibility of the window gracefuly self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False ``` This calls the constructor of the custom window class in `window.py` and assigns it to the extension `self._window`. ## Step 4: Custom Window The custom window class can be found in `window.py`. It is possible to simply build all of your user interface in `extension.py`, but this is only a good practice for very simple extensions. More complex extensions should be broken into managable pieces. It is a good practice to put your user interface into its own file. Note that `window.py` contains a class that inherits from `ui.Window`. Change the `__init__()` function to include the line added below: ```python def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) ``` This line registers the `self._build_fn` callback to run when the window is visible, which is where you will build the user interface for this tutorial. ### Step 4.1: Create a Scrolling Frame Now scroll down to `_build_fn` at the bottom of `window.py` and edit it to match the following: ```python def _build_fn(self): # The method that is called to build all the UI once the window is visible. with ui.ScrollingFrame(): pass ``` The `with` statement begins a context block and you are creating a `ScrollingFrame`. What this means is that everything intended below the `with` will be a child of the `ScrollingFrame`. A [ScrollingFrame](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.ScrollingFrame) is an area within your user interface with a scroll bar. By creating one first, if the user makes the window small, a scrollbar will appear, allowing the user to still access all content in the user interface. ### Step 4.2: Create a Vertical Stack Next edit the `_build_fn()` definition by replacing the `pass` line with the following context block and put a `pass` keyword inside the new context block as shown below: ```python def _build_fn(self): # The method that is called to build all the UI once the window is visible. with ui.ScrollingFrame(): with ui.VStack(height=0): pass ``` Here you added a `VStack`, which stacks its children vertically. The first item is at the top and each subsequent item is placed below the previous item as demonstrated in the schematic below: <p align="center"> <img src="Images/VerticalStack.png" width=25%> <p> This will be used to organize the controls into rows. ### Step 4.3: Break the Construction into Chunks While it would be possible to create the entire user interface in this tutorial directly in `_build_fn()`, as a user interface gets large it can be unwieldly to have it entirely within one function. In order to demonstrate best practices, this tutorial builds each item in the vertical stack above in its own function. Go ahead and edit your code to match the block below: ```python def _build_fn(self): # The method that is called to build all the UI once the window is visible. with ui.ScrollingFrame(): with ui.VStack(height=0): self._build_calculations() self._build_parameters() self._build_light_1() ``` Each of these functions: `_build_calculations()`, `_build_parameters()`, and `_build_light_1()` builds an item in the vertical stack. Each of those items is a group of well-organized controls made with a consistent look and layout. If you save `window.py` it will `hot reload`, but will not look any different from before. That is because both `ScrollingFrame` and `VStack` are layout controls. This means that they are meant to organize content within them, not be displayed themselves. A `ScrollingFrame` can show a scroll bar, but only if it has content to be scrolled. ## Step 5: Build Calculations The first group you will create is the `Calculations group`. In this section `CollapsableFrame`, `HStack`, `Label`, and `IntSlider` will be introduced. Scroll up to the `_build_calculations` which looks like the following block of code: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group # A VStack is a vertical stack and aligns widgets vertically one after the other # An HStack is a horizontal stack and aligns widgets horizontally one after the other # A label displays text # An IntSlider lets a user choose an integer by sliding a bar back and forth # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider pass ``` In the remaining sub-sections you will fill this in and create your first group of controls. ### Step 5.1: Create a Collapsable Frame Edit `_build_calculations()` to match the following: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other # An HStack is a horizontal stack and aligns widgets horizontally one after the other # A label displays text # An IntSlider lets a user choose an integer by sliding a bar back and forth # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider pass ``` A `CollapsableFrame` is a control that you can expand and contract by clicking on its header, which will show or hide its content. The first argument passed into its constructor is the title string. The second argument is its name and the final argument is a reference to the function that builds its header. You can write this function to give the header whatever look you want. At this point if you save `window.py` and then test in Omniverse Code you will see a change in your extension's window. The `CollapsableFrame` will be visible and should look like this: <p align="center"> <img src="Images/CollapsableFrame.png" width=25%> <p> Next we will add content inside this `CollapsableFrame`. ### Step 5.2: Create a Horizontal Stack The next three steps demonstrate a very common user interface pattern, which is to have titled controls that are well aligned. A common mistake is to create a user interface that looks like this: <p align="center"> <img src="Images/BadUI.png" width=25%> <p> The controls have description labels, but they have inconsistent positions and alignments. The following is a better design: <p align="center"> <img src="Images/GoodUI.png" width=25%> <p> Notice that the description labels are all to the left of their respective controls, the labels are aligned, and the controls have a consistent width. This will be demonstrated twice within a `VStack` in this section. Add a `VStack` and then to create this common description-control layout, add an `HStack` to the user interface as demonstrated in the following code block: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text # An IntSlider allows a user choose an integer by sliding a bar back and forth pass # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider pass ``` An `HStack` is very similar to a `VStack` except that it stacks its content horizontally rather than vertically. Note that a `pass` you added to the `VStack` simply so that the code will run until you add more controls to this context. ### Step 5.3: Create a Label Next add a `Label` to the `HStack`: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text ui.Label("Precision", name="attribute_name", width=self.label_width) # An IntSlider allows a user choose an integer by sliding a bar back and forth # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider ``` If you save the file and go to `Code` you will see that the `Label` appears in the user interface. Take special note of the `width` attribute passed into the constructor. By making all of the labels the same width inside their respective `HStack` controls, the labels and the controls they describe will be aligned. Note also that all contexts now have code, so we have removed the `pass` statements. ### Step 5.4: Create an IntSlider Next add an `IntSlider` as shown below: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text ui.Label("Precision", name="attribute_name", width=self.label_width) # An IntSlider allows a user choose an integer by sliding a bar back and forth ui.IntSlider(name="attribute_int") # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider ``` An `IntSlider` is a slider bar that a user can click and drag to control an integer value. If you save your file and go to Omniverse Code, your user interface should now look like this: <p align="center"> <img src="Images/IntSlider.png" width=25%> <p> Go ahead and add a second label/control pair by adding the following code: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text ui.Label("Precision", name="attribute_name", width=self.label_width) # An IntSlider allows a user choose an integer by sliding a bar back and forth ui.IntSlider(name="attribute_int") # Pairing a label with a control is a common UI comb with ui.HStack(): # The label makes the purpose of the control clear ui.Label("Iterations", name="attribute_name", width=self.label_width) # You can set the min and max value on an IntSlider ui.IntSlider(name="attribute_int", min=0, max=5) ``` You have added another `HStack`. This one has a `Label` set to the same width as the first `Label`. This gives the group consistent alignment. `min` and `max` values have also been set on the second `IntSlider` as a demonstration. Save `window.py` and test the extension in Omniverse Code. Expand and collapse the `CollapsableFrame`, resize the window, and change the integer values. It is a good practice to move and resize your extension windows as you code to make sure that the layout looks good no matter how the user resizes it. ## Step 6: Build Parameters In this section you will introduce the `FloatSlider` and demonstrate how to keep the UI consistent across multiple groups. You will be working in the `_build_parameters()` definition which starts as shown below: ```python def _build_parameters(self): # Build the widgets of the "Parameters" group # A Float Slider is similar to an Int Slider # controls a 'float' which is a number with a decimal point (A Real number) # You can set the min and max of a float slider as well # Setting the labels all to the same width gives the UI a nice alignment # A few more examples of float sliders pass ``` Hopefullly this is starting to feel a bit more familiar. You have an empty function that has a `pass` command at the end as a placeholder until you add code to all of its contexts. ### Step 6.1: Create a FloatSlider A `FloatSlider` is very similar to an `IntSlider`. The difference is that it controls a `float` number rather than an `integer`. Match the code below to add one to your extension: ```python def _build_parameters(self): # Build the widgets of the "Parameters" group with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Value", name="attribute_name", width=self.label_width) # A Float Slider is similar to an Int Slider # controls a 'float' which is a number with a decimal point (A Real number) ui.FloatSlider(name="attribute_float") # You can set the min and max of a float slider as well # Setting the labels all to the same width gives the UI a nice alignment # A few more examples of float sliders ``` Here you added a second `CollapsableFrame` with a `VStack` inside of it. This will allow you to add as many label/control pairs as you want to this group. Note that the `Label` has the same width as the label above. Save `window.py` and you should see the following in Omniverse Code: <p align="center"> <img src="Images/SecondGroup.png" width=25%> <p> Note that the description labels and controls in the first and second group are aligned with each other. ### Step 6.2: Make a Consistent UI By using these description control pairs inside of collapsable groups, you can add many controls to a window while maintaining a clean, easy to navigate experience. The following code adds a few more `FloatSlider` controls to the user interface: ```python def _build_parameters(self): # Build the widgets of the "Parameters" group with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Value", name="attribute_name", width=self.label_width) # A Float Slider is similar to an Int Slider # controls a 'float' which is a number with a decimal point (A Real number) ui.FloatSlider(name="attribute_float") with ui.HStack(): ui.Label("i", name="attribute_name", width=self.label_width) # You can set the min and max of a float slider as well ui.FloatSlider(name="attribute_float", min=-1, max=1) # Setting the labels all to the same width gives the UI a nice alignment with ui.HStack(): ui.Label("j", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) # A few more examples of float sliders with ui.HStack(): ui.Label("k", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("Theta", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") ``` Save `window.py` and take a look in Omniverse Code. Your window should look like this: <p align="center"> <img src="Images/SecondGroupComplete.png" width=25%> <p> Note that a few of the sliders have `min` and `max` values and they they are all well-aligned. ## Step 7: Build Light In your final group you will add a few other control types to help give you a feel for what can be done in an extension UI. This will also be well-arranged, even though they are different control types to give the overall extension a consistent look and feel, even though it has a variety of control types. You will be working in `_build_light_1()`, which starts as shown below: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group # A multi float drag field lets you control a group of floats # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel #Feel free to copy this color widget and use it in your own UIs # The custom compound widget #An example of a checkbox pass ``` First you will add a `MultiFloatDragField` to it, then a custom color picker widget and finally a `Checkbox`. ### Step 7.1: Create a MultiFloatDragField Edit `_build_light_1` to match the following: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) # A multi float drag field allows you control a group of floats (Real numbers) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") #Feel free to copy this color widget and use it in your own UIs # The custom compound widget #An example of a checkbox ``` This adds a third `CollapsableFrame` with a `VStack` to hold its controls. Then it adds a label/control pair with a `MultiFloatDragField`. A `MultiFloatDragField` lets a user edit as many values as you put into its constructor, and is commonly used to edit 3-component vectors such as position and rotation. You also added a second label and control pair with a `FloatSlider` similar to the one you added in [section 5.1](#51-create-a-floatslider). ### Step 7.2: Add a Custom Widget Developers can create custom widgets and user interface elements. The color picker added in this section is just such an example. Add it to your extension with the following code: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) # A multi float drag field lets you control a group of floats (Real numbers) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") #Feel free to copy this color widget and use it in your own UIs with ui.HStack(): ui.Label("Color", name="attribute_name", width=self.label_width) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) #An example of a checkbox ``` This widget lets users click and then select a color. Feel free to use this widget in your own applications and feel free to write and share your own widgets. Over time you will have a wide variety of useful widgets and controls for everyone to use in their extensions. ### Step 7.3: Add a Checkbox Finally, edit `_build_light_1()` to match the following: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) # A multi float drag field lets you control a group of floats (Real numbers) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") #Feel free to copy this color widget and use it in your own UIs with ui.HStack(): ui.Label("Color", name="attribute_name", width=self.label_width) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) #An example of a checkbox with ui.HStack(): ui.Label("Shadow", name="attribute_name", width=self.label_width) ui.CheckBox(name="attribute_bool") ``` This adds a label/control pair with a `CheckBox`. A `CheckBox` control allows a user to set a boolean value. Save your `window.py` file and open Omniverse Code. Your user interface should look like this if you collapse the `Parameters` section: <p align="center"> <img src="Images/Complete.png" width=25%> <p> There are three collapsable groups, each with a variety of controls with a variety of settings and yet they are all well-aligned with a consistent look and feel. ## Conclusion In this tutorial you created an extension user interface using coding best practices to integrate it into an Omniverse application. It contains a variety of controls that edit integers, float, colors and more. These controls are well organized so that a user can easily find their way around the window. We look forward to seeing the excellent extensions you come up with and how you can help Omniverse users accomplish things that were hard or even impossible to do before you wrote an extension to help them.
30,589
Markdown
47.478605
565
0.696296
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/config/extension.toml
[package] title = "omni.ui Window Example" description = "The full end to end example of the window" version = "1.0.1" category = "Example" authors = ["Victor Yudin"] repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows" keywords = ["example", "window", "ui"] changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.example.ui_window" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
695
TOML
22.199999
84
0.671942
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/style.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__ = ["example_window_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. cl.example_window_attribute_bg = cl("#1f2124") cl.example_window_attribute_fg = cl("#0f1115") cl.example_window_hovered = cl("#FFFFFF") cl.example_window_text = cl("#CCCCCC") fl.example_window_attr_hspacing = 10 fl.example_window_attr_spacing = 1 fl.example_window_group_spacing = 2 url.example_window_icon_closed = f"{EXTENSION_FOLDER_PATH}/data/closed.svg" url.example_window_icon_opened = f"{EXTENSION_FOLDER_PATH}/data/opened.svg" # The main style dict example_window_style = { "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_CENTER, "margin_height": fl.example_window_attr_spacing, "margin_width": fl.example_window_attr_hspacing, }, "Label::attribute_name:hovered": {"color": cl.example_window_hovered}, "Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER}, "Slider::attribute_int:hovered": {"color": cl.example_window_hovered}, "Slider": { "background_color": cl.example_window_attribute_bg, "draw_mode": ui.SliderDrawMode.HANDLE, }, "Slider::attribute_float": { "draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": cl.example_window_attribute_fg, }, "Slider::attribute_float:hovered": {"color": cl.example_window_hovered}, "Slider::attribute_vector:hovered": {"color": cl.example_window_hovered}, "Slider::attribute_color:hovered": {"color": cl.example_window_hovered}, "CollapsableFrame::group": {"margin_height": fl.example_window_group_spacing}, "Image::collapsable_opened": {"color": cl.example_window_text, "image_url": url.example_window_icon_opened}, "Image::collapsable_closed": {"color": cl.example_window_text, "image_url": url.example_window_icon_closed}, }
2,530
Python
42.63793
112
0.717787
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/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__ = ["ExampleWindowExtension"] from .window import ExampleWindow from functools import partial import asyncio import omni.ext import omni.kit.ui import omni.ui as ui class ExampleWindowExtension(omni.ext.IExt): """The entry point for Example Window""" WINDOW_NAME = "Example Window" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Put the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(ExampleWindowExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user pressed "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = ExampleWindow(ExampleWindowExtension.WINDOW_NAME, width=300, height=365) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
2,849
Python
36.012987
108
0.662338
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ExampleWindowExtension", "ExampleWindow"] from .extension import ExampleWindowExtension from .window import ExampleWindow
568
Python
42.769227
76
0.806338
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/color_widget.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__ = ["ColorWidget"] from ctypes import Union from typing import List, Optional import omni.ui as ui COLOR_PICKER_WIDTH = 20 SPACING = 4 class ColorWidget: """The compound widget for color input""" def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = args self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.__multifield: Optional[ui.MultiFloatDragField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__model = None self.__multifield = None self.__colorpicker = None self.__frame = None def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__root_frame, attr) @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__multifield: return self.__multifield.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__multifield.model = value self.__colorpicker.model = value def _build_fn(self): with ui.HStack(spacing=SPACING): # The construction of multi field depends on what the user provided, # defaults or a model if self.__model: # the user provided a model self.__multifield = ui.MultiFloatDragField( min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color" ) model = self.__model else: # the user provided a list of default values self.__multifield = ui.MultiFloatDragField( *self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color" ) model = self.__multifield.model self.__colorpicker = ui.ColorWidget(model, width=COLOR_PICKER_WIDTH)
2,600
Python
33.223684
95
0.611538
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/window.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__ = ["ExampleWindow"] import omni.ui as ui from .style import example_window_style from .color_widget import ColorWidget LABEL_WIDTH = 120 SPACING = 4 class ExampleWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def _build_collapsable_header(self, collapsed, title): """Build a custom title of CollapsableFrame""" with ui.HStack(): ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, width=20, height=20) def _build_calculations(self): """Build the widgets of the "Calculations" group""" with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Precision", name="attribute_name", width=self.label_width) ui.IntSlider(name="attribute_int") with ui.HStack(): ui.Label("Iterations", name="attribute_name", width=self.label_width) ui.IntSlider(name="attribute_int", min=0, max=5) def _build_parameters(self): """Build the widgets of the "Parameters" group""" with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Value", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") with ui.HStack(): ui.Label("i", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("j", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("k", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("Theta", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") def _build_light_1(self): """Build the widgets of the "Light 1" group""" with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") with ui.HStack(): ui.Label("Color", name="attribute_name", width=self.label_width) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) with ui.HStack(): ui.Label("Shadow", name="attribute_name", width=self.label_width) ui.CheckBox(name="attribute_bool") def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(): with ui.VStack(height=0): self._build_calculations() self._build_parameters() self._build_light_1()
5,056
Python
39.13492
111
0.584256
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/tests/__init__.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 .test_window import TestWindow
463
Python
50.55555
76
0.812095
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/tests/test_window.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__ = ["TestWindow"] from omni.example.ui_window import ExampleWindow from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import omni.kit.app import omni.kit.test EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests") class TestWindow(OmniUiTest): async def test_general(self): """Testing general look of section""" window = ExampleWindow("Test") await omni.kit.app.get_app().next_update_async() await self.docked_test_window( window=window, width=300, height=385, ) # Wait for images for _ in range(20): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
1,338
Python
34.236841
115
0.705531
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-22 ### Added - Readme ## [1.0.0] - 2022-06-05 ### Added - Initial window
108
Markdown
9.899999
23
0.555556
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/docs/README.md
# Generic Window (omni.example.ui_window) ![](../data/preview.png) ## Overview This extension provides an end-to-end example and general recommendations on creating a simple window using `omni.ui`. It contains the best practices of building an extension, a menu item, a window itself, a custom widget, and a generic style. ## [Tutorial](../tutorial/tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md) ## Usage This is just a UI demo. You can interact with the various controls, but they have not additional effect in the Application. ## Explanations ### Extension When the extension starts up, we register a new menu item that controls the window and shows the window. A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit. ``` # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) ``` When the extension shuts down, we remove the menu item and deregister the window callback. ### Window It's handy to derive a custom window from the class `ui.Window`. The UI can be defined right in __init__, so it's created immediately. Or it can be defined in a callback and it will be created when the window is visible. ``` class ExampleWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) ``` ### Custom Widget A custom widget can be a class or a function. It's not required to derive anything. It's only necessary to create sub-widgets. ``` class ColorWidget: """The compound widget for color input""" def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = args self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.__multifield: Optional[ui.MultiFloatDragField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__frame = ui.Frame() with self.__frame: self._build_fn() ``` ### Style Although the style can be applied to any widget, we recommend keeping the style dictionary in one location. There is an exception to this recommendation. It's recommended to use styles directly on the widgets to hide a part of the widget. For example, it's OK to set {"color": cl.transparent} on a slider to hide the text. Or "background_color": cl.transparent to disable background on a field.
3,040
Markdown
35.202381
155
0.715789
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/docs/index.rst
omni.example.ui_window ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
153
reStructuredText
11.833332
40
0.509804
NVIDIA-Omniverse/kit-extension-template/README.md
# *Omniverse Kit* Extensions Project Template This project is a template for developing extensions for *Omniverse Kit*. # Getting Started ## Install Omniverse and some Apps 1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download) 2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*. ## Add a new extension to your *Omniverse App* 1. Fork and clone this repo, for example in `C:\projects\kit-extension-template` 2. In the *Omniverse App* open extension manager: *Window* &rarr; *Extensions*. 3. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar. 4. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `exts` subfolder there as another search path: `C:\projects\kit-extension-template\exts` ![Extension Manager Window](/images/add-ext-search-path.png) 5. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it. 6. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload. ### Few tips * Now that `exts` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*. * Look at the *Console* window for warnings and errors. It also has a small button to open current log file. * All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`. * Extension name is a folder name in `exts` folder, in this example: `omni.hello.world`. * Most important thing extension has is a config file: `extension.toml`, take a peek. ## Next Steps: Alternative way to add a new extension To get a better understanding and learn a few other things, we recommend following next steps: 1. Remove search path added in the previous section. 1. Open this cloned repo using Visual Studio Code: `code C:\projects\kit-extension-template`. It will suggest installing a few extensions to improve python experience. 2. In the terminal (CTRL + \`) run `link_app.bat` (more in [Linking with an *Omniverse* app](#linking-with-an-omniverse-app) section). 3. Run this app with `exts` folder added as an extensions search path and new extension enabled: ```bash > app\omni.code.bat --ext-folder exts --enable omni.hello.world ``` - `--ext-folder [path]` - adds new folder to the search path - `--enable [extension]` - enables an extension on startup. Use `-h` for help: ```bash > app\omni.code.bat -h ``` 4. After the *App* started you should see: * new "My Window" window popup. * extension search paths in *Extensions* window as in the previous section. * extension enabled in the list of extensions. 5. If you look inside `omni.code.bat` or any other *Omniverse App*, they all run *Omniverse Kit* (`kit.exe`). *Omniverse Kit* is the Omniverse Application runtime that powers *Apps* build out of extensions. Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Code*: ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world ``` It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!): ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world --enable omni.kit.window.extensions ``` You should see a menu in the top left. From here you can enable more extensions from the UI. ### Few tips * In the *Extensions* window, press *Bread* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be: all extensions and dependencies. * Extensions system documentation: http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/extensions.html # Running Tests To run tests we run a new process where only the tested extension (and it's dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests: 1. Run: `app\kit\test_ext.bat omni.hello.world --ext-folder exts` That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code! 2. Alternatively, in *Extension Manager* (*Window &rarr; Extensions*) find your extension, click on *TESTS* tab, click *Run Test* For more information about testing refer to: [testing doc](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/ext_testing.html). # Linking with an *Omniverse* app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app create ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Adding a new extension Adding a new extension is as simple as copying and renaming existing one: 1. copy `exts/omni.hello.world` to `exts/[new extension name]` 2. rename python module (namespace) in `exts/[new extension name]/omni/hello/world` to `exts/[new extension name]/[new python module]` 3. update `exts/[new extension name]/config/extension.toml`, most importantly specify new python module to load: ```toml [[python.module]] name = "[new python module]" ``` No restart is needed, you should be able to find and enable `[new extension name]` in extension manager. # Sharing extensions To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). 1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery. 2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes. # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
6,864
Markdown
47.687943
318
0.750291
NVIDIA-Omniverse/kit-extension-template/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
NVIDIA-Omniverse/kit-extension-template/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
NVIDIA-Omniverse/kit-extension-template/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") 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 install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
NVIDIA-Omniverse/kit-extension-template/exts/omni.hello.world/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Simple UI Extension Template" description = "The simplest python extension example. Use it as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Path (relative to the root) of changelog changelog = "docs/CHANGELOG.md" # URL of the extension source repository. repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.hello.world" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,206
TOML
26.431818
105
0.739635
NVIDIA-Omniverse/kit-extension-template/exts/omni.hello.world/omni/hello/world/extension.py
import omni.ext import omni.ui as ui # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print(f"[omni.hello.world] some_public_function was called with {x}") return x ** x # 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 MyExtension(omni.ext.IExt): # 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.hello.world] MyExtension startup") self._count = 0 self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_click(): self._count += 1 label.text = f"count: {self._count}" def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Add", clicked_fn=on_click) ui.Button("Reset", clicked_fn=on_reset) def on_shutdown(self): print("[omni.hello.world] MyExtension shutdown")
1,557
Python
34.40909
119
0.594733
NVIDIA-Omniverse/kit-extension-template/exts/omni.hello.world/omni/hello/world/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
NVIDIA-Omniverse/kit-extension-template/exts/omni.hello.world/omni/hello/world/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
NVIDIA-Omniverse/kit-extension-template/exts/omni.hello.world/omni/hello/world/tests/test_hello_world.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 # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.hello.world # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # 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_hello_public_function(self): result = omni.hello.world.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,668
Python
34.510638
142
0.681055
NVIDIA-Omniverse/kit-extension-template/exts/omni.hello.world/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
NVIDIA-Omniverse/kit-extension-template/exts/omni.hello.world/docs/README.md
# Simple UI Extension Template The simplest python extension example. Use it as a starting point for your extensions.
119
Markdown
28.999993
86
0.806723
NVIDIA-Omniverse/USD-Tutorials-And-Examples/README.md
# USD Tutorials and Examples ## About This project showcases educational material for [Pixar's Universal Scene Description](https://graphics.pixar.com/usd/docs/index.html) (USD). For convenience, the Jupyter notebook from the GTC session is available on Google Colaboratory, which offers an interactive environment from the comfort of your web browser. Colaboratory makes it possible to: * Try code snippets without building or installing USD on your machine * Run the samples on any device * Share code experiments with others Should you prefer to run the notebook on your local machine instead, simply download and execute it after [installing Jupyter](https://jupyter.org). ## Sample Notebook Follow along the tutorial using the sample notebook from the GTC session, or get acquainted with USD using other examples: |Notebook|Google Colab link| |--------|:----------------:| |Introduction to USD|[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/usd_introduction.ipynb)| |Opening USD Stages|[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/opening_stages.ipynb)| |Prims, Attributes and Metadata|[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/prims_attributes_and_metadata.ipynb)| |Hierarchy and Traversal|[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/hierarchy_and_traversal.ipynb)| ## Additional Resources * [Pixar's USD](https://graphics.pixar.com/usd) * [USD at NVIDIA](https://usd.nvidia.com) * [USD training content on _NVIDIA On-Demand_](https://www.nvidia.com/en-us/on-demand/playlist/playList-911c5614-4b7f-4668-b9eb-37f627ac8d17/)
2,140
Markdown
78.296293
263
0.784112
NVIDIA-Omniverse/kit-project-template/repo.toml
######################################################################################################################## # Repo tool base settings ######################################################################################################################## [repo] # Use the Kit Template repo configuration as a base. Only override things specific to the repo. import_configs = [ "${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml", "${root}/_repo/deps/repo_kit_tools/kit-template/repo-external.toml", ] extra_tool_paths = [ "${root}/kit/dev", ] ######################################################################################################################## # Extensions precacher ######################################################################################################################## [repo_precache_exts] # Apps to run and precache apps = [ "${root}/source/apps/my_name.my_app.kit" ]
949
TOML
31.75862
120
0.33509
NVIDIA-Omniverse/kit-project-template/README.md
# *Omniverse Kit* Project Template This project is a template for developing apps and extensions for *Omniverse Kit*. # Important Links - [Omniverse Documentation Site](https://docs.omniverse.nvidia.com/kit/docs/kit-project-template) - [Github Repo for this Project Template](https://github.com/NVIDIA-Omniverse/kit-project-template) - [Extension System](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html) # Getting Started 1. Fork/Clone the Kit Project Template repo [link](https://github.com/NVIDIA-Omniverse/kit-project-template) to a local folder, for example in `C:\projects\kit-project-template` 2. (Optional) Open this cloned repo using Visual Studio Code: `code C:\projects\kit-project-template`. It will likely suggest installing a few extensions to improve python experience. None are required, but they may be helpful. 3. In a CLI terminal (if in VS Code, CTRL + \` or choose Terminal->New Terminal from the menu) run `pull_kit_kernel.bat` (windows) / `pull_kit_kernel.sh` (linux) to pull the *Omniverse Kit Kernel*. `kit` folder link will be created under the main folder in which your project is located. 4. Run the example app that includes example extensions: `source/apps/my_name.my_app.bat` (windows) / `./source/apps/my_name.my_app.sh` (linux) to ensure everything is working. The first start will take a while as it will pull all the extensions from the extension registry and build various caches. Subsequent starts will be much faster. Once finished, you should see a "Kit Base Editor" window and a welcome screen. Feel free to browse through the base application and exit when finished. You are now ready to begin development! ## An Omniverse App If you look inside a `source/apps/my_name.my_app.bat` or any other *Omniverse App*, they all run off of an SDK we call *Omniverse Kit* . The base application for *Omniverse Kit* (`kit.exe`) is the runtime that powers *Apps* build out of extensions. Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **All other functionality is provided by extensions.** To start an app we pass a `kit` file, which is a configuration file with a `kit` extension. It describes which extensions to pull and load, and which settings to apply. One kit file fully describes an app, but you may find value in having several for different methods to run and test your application. Notice that it includes `omni.hello.world` extension; that is an example extension found in this repo. All the other extensions are pulled from the `extension registry` on first startup. More info on building kit files: [doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html) ### Packaging an App Once you have developed, tested, and documented your app or extension, you will want to publish it. Before publishing the app, we must first assemble all its components into a single deliverable. This step is called "packaging". To package an app run `tools/package.bat` (or `repo package`). The package will be created in the `_build/packages` folder. To use the package, unzip the package that was created by the above step into its own separate folder. Then, run `pull_kit_kernel.bat` inside the new folder once before running the app. ### Version Lock An app `kit` file fully defines all the extensions, but their versions are not `locked`, which is to say that by default the latest versions of a given extension will be used. Also, many extensions have dependencies themselves which cause kit to download and enable other extensions. This said, for the final app it is important that it always gets the same extensions and the same versions on each run. This is meant to provide reliable and reproducible builds. This is called a *version lock* and we have a separate section at the end of `kit` file to lock versions of all extensions and all their dependencies. It is also important to update the version lock section when adding new extensions or updating existing ones. To update version lock the `precache_exts` tool is used. **To update version lock run:** `tools/update_version_lock.bat`. Once you've done this, use your source control methods to commit any changes to a kit file as part of the source necessary to reproduce the build. The packaging tool will verify that version locks exist and will fail if they do not. More info on dependency management: [doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html#application-dependencies-management) ## An Omniverse Extension This template includes one simple extension: `omni.hello.world`. It is loaded in the example app, but can also be loaded and tested in any other *Omniverse App*. You should feel free to copy or rename this extension to one that you wish to create. Please refer to Omniverse Documentation for more information on developing extensions. ### Using Omniverse Launcher 1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download) 2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*. ### Add a new extension to your *Omniverse App* If you want to add extensions from this repo to your other existing Omniverse App. 1. In the *Omniverse App* open extension manager: *Window* &rarr; *Extensions*. 2. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar. 3. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `source/extensions` subfolder there as another search path: `C:/projects/kit-project-template/source/extensions` ![Extension Manager Window](/images/add-ext-search-path.png) 4. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it. 5. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload. ### Adding a new extension * Now that `source/extensions` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*. * Look at the *Console* window for warnings and errors. It also has a small button to open current log file. * All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`. * Extension name is a folder name in `source/extensions`, in this example: `omni.hello.world`. This is most often the same name as the "Extension ID". * The most important thing that an extension has is its config file: `extension.toml`. You should familiarize yourself with its contents. * In the *Extensions* window, press *Burger* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be by displaying all its dependencies. * Extensions system documentation can be found [here](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html) ### Alternative way to add a new extension To get a better understanding of the extension topology, we recommend following: 1. Run bare `kit.exe` with `source/extensions` folder added as an extensions search path and new extension enabled: ```bash > kit\kit.exe --ext-folder source/extensions --enable omni.hello.world ``` - `--ext-folder [path]` - adds new folder to the search path - `--enable [extension]` - enables an extension on startup. Use `-h` for help: ```bash > kit\kit.exe -h ``` 2. After the *App* starts you should see: * new "My Window" window popup. * extension search paths in *Extensions* window as in the previous section. * extension enabled in the list of extensions. It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!): ```bash > kit\kit.exe --ext-folder source/extensions --enable omni.hello.world --enable omni.kit.window.extensions ``` You should see a menu in the top left. From this UI you can browse and enable more extensions. It is important to note that these enabled extensions are NOT added to your kit file, but instead live in a local "user" file as an addendum. If you want the extension to be a part of your app, you must add its name to the list of dependencies in the `[dependencies]` section. # A third way to add an extension Here is how to add an extension by copying the "hello world" extension as a template: 1. copy `source/extensions/omni.hello.world` to `source/extensions/[new extension id]` 2. rename python module (namespace) in `source/extensions/[new extension id]/omni/hello/world` to `source/extensions/[new extension id]/[new python module]` 3. update `source/extensions/[new extension name]/config/extension.toml`, most importantly specify new python module to load: 4. Optionally, add the `[extension id]` to the `[dependencies]` section of the app's kit file. [[python.module]] name = "[new python module]" # Running Tests To run tests we run a new configuration where only the tested extension (and its dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests: 1. Run: `tools\test_ext.bat omni.hello.world` That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code! 2. Alternatively, in *Extension Manager* (*Window &rarr; Extensions*) find your extension, click on *TESTS* tab, click *Run Test* For more information about testing refer to: [testing doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/testing_exts_python.html). No restart is needed, you should be able to find and enable `[new extension name]` in extension manager. # Sharing extensions To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). 1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery. 2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes. # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions. # License By using any part of the files in the KIT-PROJECT-TEMPLATE repo you agree to the terms of the NVIDIA Omniverse License Agreement, the most recent version of which is available [here](https://docs.omniverse.nvidia.com/composer/latest/common/NVIDIA_Omniverse_License_Agreement.html).
11,077
Markdown
69.560509
533
0.769613
NVIDIA-Omniverse/kit-project-template/deps/user.toml
[exts."omni.kit.registry.nucleus"] registries = [ { name = "kit/default", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/shared" }, { name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" }, ] [app.exts] folders.'++' = ["${local-config-path}/source/extensions"]
367
TOML
35.799996
136
0.667575
NVIDIA-Omniverse/kit-project-template/tools/VERSION.md
105.0
5
Markdown
4.999995
5
0.8
NVIDIA-Omniverse/kit-project-template/tools/deps/repo-deps.packman.xml
<project toolsVersion="5.0"> <dependency name="repo_build" linkPath="../../_repo/deps/repo_build"> <package name="repo_build" version="0.40.0"/> </dependency> <dependency name="repo_ci" linkPath="../../_repo/deps/repo_ci"> <package name="repo_ci" version="0.5.1" /> </dependency> <dependency name="repo_changelog" linkPath="../../_repo/deps/repo_changelog"> <package name="repo_changelog" version="0.3.0" /> </dependency> <dependency name="repo_format" linkPath="../_repo/deps/repo_format"> <package name="repo_format" version="2.7.0" /> </dependency> <dependency name="repo_kit_tools" linkPath="../../_repo/deps/repo_kit_tools"> <package name="repo_kit_tools" version="0.12.18"/> </dependency> <dependency name="repo_licensing" linkPath="../../_repo/deps/repo_licensing">. <package name="repo_licensing" version="1.11.2" /> </dependency> <dependency name="repo_man" linkPath="../../_repo/deps/repo_man"> <package name="repo_man" version="1.32.1"/> </dependency> <dependency name="repo_package" linkPath="../../_repo/deps/repo_package"> <package name="repo_package" version="5.8.5" /> </dependency> <dependency name="repo_source" linkPath="../../_repo/deps/repo_source"> <package name="repo_source" version="0.4.2"/> </dependency> <dependency name="repo_test" linkPath="../../_repo/deps/repo_test"> <package name="repo_test" version="2.5.6"/> </dependency> </project>
1,448
XML
42.90909
80
0.649171
NVIDIA-Omniverse/kit-project-template/tools/deps/kit-sdk.packman.xml
<project toolsVersion="5.0"> <dependency name="kit_sdk_${config}" linkPath="../../kit" tags="${config} non-redist"> <package name="kit-kernel" version="105.1+release.127680.dd92291b.tc.${platform}.${config}"/> </dependency> </project>
243
XML
39.66666
97
0.666667
NVIDIA-Omniverse/kit-project-template/tools/repoman/repoman.py
import os import sys import io import contextlib import packmanapi REPO_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..") REPO_DEPS_FILE = os.path.join(REPO_ROOT, "tools/deps/repo-deps.packman.xml") def bootstrap(): """ Bootstrap all omni.repo modules. Pull with packman from repo.packman.xml and add them all to python sys.path to enable importing. """ #with contextlib.redirect_stdout(io.StringIO()): deps = packmanapi.pull(REPO_DEPS_FILE) for dep_path in deps.values(): if dep_path not in sys.path: sys.path.append(dep_path) if __name__ == "__main__": bootstrap() import omni.repo.man omni.repo.man.main(REPO_ROOT)
709
Python
23.482758
100
0.662905
NVIDIA-Omniverse/kit-project-template/tools/packman/packmanconf.py
# Use this file to bootstrap packman into your Python environment (3.7.x). Simply # add the path by doing sys.insert to where packmanconf.py is located and then execute: # # >>> import packmanconf # >>> packmanconf.init() # # It will use the configured remote(s) and the version of packman in the same folder, # giving you full access to the packman API via the following module # # >> import packmanapi # >> dir(packmanapi) import os import platform import sys def init(): """Call this function to initialize the packman configuration. Calls to the packman API will work after successfully calling this function. Note: This function only needs to be called once during the execution of your program. Calling it repeatedly is harmless but wasteful. Compatibility with your Python interpreter is checked and upon failure the function will report what is required. Example: >>> import packmanconf >>> packmanconf.init() >>> import packmanapi >>> packmanapi.set_verbosity_level(packmanapi.VERBOSITY_HIGH) """ major = sys.version_info[0] minor = sys.version_info[1] if major != 3 or minor != 10: raise RuntimeError( f"This version of packman requires Python 3.10.x, but {major}.{minor} was provided" ) conf_dir = os.path.dirname(os.path.abspath(__file__)) os.environ["PM_INSTALL_PATH"] = conf_dir packages_root = get_packages_root(conf_dir) version = get_version(conf_dir) module_dir = get_module_dir(conf_dir, packages_root, version) sys.path.insert(1, module_dir) def get_packages_root(conf_dir: str) -> str: root = os.getenv("PM_PACKAGES_ROOT") if not root: platform_name = platform.system() if platform_name == "Windows": drive, _ = os.path.splitdrive(conf_dir) root = os.path.join(drive, "packman-repo") elif platform_name == "Darwin": # macOS root = os.path.join( os.path.expanduser("~"), "/Library/Application Support/packman-cache" ) elif platform_name == "Linux": try: cache_root = os.environ["XDG_HOME_CACHE"] except KeyError: cache_root = os.path.join(os.path.expanduser("~"), ".cache") return os.path.join(cache_root, "packman") else: raise RuntimeError(f"Unsupported platform '{platform_name}'") # make sure the path exists: os.makedirs(root, exist_ok=True) return root def get_module_dir(conf_dir, packages_root: str, version: str) -> str: module_dir = os.path.join(packages_root, "packman-common", version) if not os.path.exists(module_dir): import tempfile tf = tempfile.NamedTemporaryFile(delete=False) target_name = tf.name tf.close() url = f"http://bootstrap.packman.nvidia.com/packman-common@{version}.zip" print(f"Downloading '{url}' ...") import urllib.request urllib.request.urlretrieve(url, target_name) from importlib.machinery import SourceFileLoader # import module from path provided script_path = os.path.join(conf_dir, "bootstrap", "install_package.py") ip = SourceFileLoader("install_package", script_path).load_module() print("Unpacking ...") ip.install_package(target_name, module_dir) os.unlink(tf.name) return module_dir def get_version(conf_dir: str): path = os.path.join(conf_dir, "packman") if not os.path.exists(path): # in dev repo fallback path += ".sh" with open(path, "rt", encoding="utf8") as launch_file: for line in launch_file.readlines(): if line.startswith("PM_PACKMAN_VERSION"): _, value = line.split("=") return value.strip() raise RuntimeError(f"Unable to find 'PM_PACKMAN_VERSION' in '{path}'")
3,932
Python
35.416666
95
0.632503
NVIDIA-Omniverse/kit-project-template/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
NVIDIA-Omniverse/kit-project-template/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import os import stat import time from typing import Any, Callable RENAME_RETRY_COUNT = 100 RENAME_RETRY_DELAY = 0.1 logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") def remove_directory_item(path): if os.path.islink(path) or os.path.isfile(path): try: os.remove(path) except PermissionError: # make sure we have access and try again: os.chmod(path, stat.S_IRWXU) os.remove(path) else: # try first to delete the dir because this will work for folder junctions, otherwise we would follow the junctions and cause destruction! clean_out_folder = False try: # make sure we have access preemptively - this is necessary because recursing into a directory without permissions # will only lead to heart ache os.chmod(path, stat.S_IRWXU) os.rmdir(path) except OSError: clean_out_folder = True if clean_out_folder: # we should make sure the directory is empty names = os.listdir(path) for name in names: fullname = os.path.join(path, name) remove_directory_item(fullname) # now try to again get rid of the folder - and not catch if it raises: os.rmdir(path) class StagingDirectory: def __init__(self, staging_path): self.staging_path = staging_path self.temp_folder_path = None os.makedirs(staging_path, exist_ok=True) def __enter__(self): self.temp_folder_path = tempfile.mkdtemp(prefix="ver-", dir=self.staging_path) return self def get_temp_folder_path(self): return self.temp_folder_path # this function renames the temp staging folder to folder_name, it is required that the parent path exists! def promote_and_rename(self, folder_name): abs_dst_folder_name = os.path.join(self.staging_path, folder_name) os.rename(self.temp_folder_path, abs_dst_folder_name) def __exit__(self, type, value, traceback): # Remove temp staging folder if it's still there (something went wrong): path = self.temp_folder_path if os.path.isdir(path): remove_directory_item(path) def rename_folder(staging_dir: StagingDirectory, folder_name: str): try: staging_dir.promote_and_rename(folder_name) except OSError as exc: # if we failed to rename because the folder now exists we can assume that another packman process # has managed to update the package before us - in all other cases we re-raise the exception abs_dst_folder_name = os.path.join(staging_dir.staging_path, folder_name) if os.path.exists(abs_dst_folder_name): logger.warning( f"Directory {abs_dst_folder_name} already present, package installation already completed" ) else: raise def call_with_retry( op_name: str, func: Callable, retry_count: int = 3, retry_delay: float = 20 ) -> Any: retries_left = retry_count while True: try: return func() except (OSError, IOError) as exc: logger.warning(f"Failure while executing {op_name} [{str(exc)}]") if retries_left: retry_str = "retry" if retries_left == 1 else "retries" logger.warning( f"Retrying after {retry_delay} seconds" f" ({retries_left} {retry_str} left) ..." ) time.sleep(retry_delay) else: logger.error("Maximum retries exceeded, giving up") raise retries_left -= 1 def rename_folder_with_retry(staging_dir: StagingDirectory, folder_name): dst_path = os.path.join(staging_dir.staging_path, folder_name) call_with_retry( f"rename {staging_dir.get_temp_folder_path()} -> {dst_path}", lambda: rename_folder(staging_dir, folder_name), RENAME_RETRY_COUNT, RENAME_RETRY_DELAY, ) def install_package(package_path, install_path): staging_path, version = os.path.split(install_path) with StagingDirectory(staging_path) as staging_dir: output_folder = staging_dir.get_temp_folder_path() with zipfile.ZipFile(package_path, allowZip64=True) as zip_file: zip_file.extractall(output_folder) # attempt the rename operation rename_folder_with_retry(staging_dir, version) print(f"Package successfully installed to {install_path}") if __name__ == "__main__": executable_paths = os.getenv("PATH") paths_list = executable_paths.split(os.path.pathsep) if executable_paths else [] target_path_np = os.path.normpath(sys.argv[2]) target_path_np_nc = os.path.normcase(target_path_np) for exec_path in paths_list: if os.path.normcase(os.path.normpath(exec_path)) == target_path_np_nc: raise RuntimeError(f"packman will not install to executable path '{exec_path}'") install_package(sys.argv[1], target_path_np)
5,776
Python
36.270968
145
0.645083
NVIDIA-Omniverse/kit-project-template/source/extensions/omni.hello.world/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Simple UI Extension Template" description = "The simplest python extension example. Use it as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Path (relative to the root) of changelog changelog = "docs/CHANGELOG.md" # URL of the extension source repository. repository = "https://github.com/NVIDIA-Omniverse/kit-project-template" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.hello.world" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,204
TOML
26.386363
105
0.739203
NVIDIA-Omniverse/kit-project-template/source/extensions/omni.hello.world/omni/hello/world/extension.py
# Copyright 2019-2023 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ext import omni.ui as ui # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print(f"[omni.hello.world] some_public_function was called with {x}") return x ** x # 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 MyExtension(omni.ext.IExt): # 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.hello.world] MyExtension startup") self._count = 0 self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_click(): self._count += 1 label.text = f"count: {self._count}" def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Add", clicked_fn=on_click) ui.Button("Reset", clicked_fn=on_reset) def on_shutdown(self): print("[omni.hello.world] MyExtension shutdown")
2,141
Python
36.578947
119
0.64269
NVIDIA-Omniverse/kit-project-template/source/extensions/omni.hello.world/omni/hello/world/__init__.py
# Copyright 2019-2023 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .extension import *
609
Python
39.666664
74
0.770115
NVIDIA-Omniverse/kit-project-template/source/extensions/omni.hello.world/omni/hello/world/tests/__init__.py
# Copyright 2019-2023 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .test_hello_world import *
617
Python
37.624998
74
0.768233
NVIDIA-Omniverse/kit-project-template/source/extensions/omni.hello.world/omni/hello/world/tests/test_hello_world.py
# Copyright 2019-2023 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # 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 # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.hello.world # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # 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_hello_public_function(self): result = omni.hello.world.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
2,253
Python
35.950819
142
0.70395
NVIDIA-Omniverse/kit-project-template/source/extensions/omni.hello.world/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
NVIDIA-Omniverse/kit-project-template/source/extensions/omni.hello.world/docs/README.md
# Simple UI Extension Template The simplest python extension example. Use it as a starting point for your extensions.
119
Markdown
28.999993
86
0.806723
NVIDIA-Omniverse/kit-project-template/source/package/description.toml
# Description of the application for the Omniverse Launcher name = "My App" # displayed application name shortName = "My App" # displayed application name in smaller card and library view version = "${version}" # version must be semantic kind = "app" # enum of "app", "connector" and "experience" for now latest = true # boolean for if this version is the latest version slug = "my_app" # unique identifier for component, all lower case, persists between versions productArea = "My Company" # displayed before application name in launcher category = "Apps" # category of content channel = "release" # 3 filter types [ "alpha", "beta", "release "] enterpriseStatus = false # Set true if you want this package to show in enterprise launcher # values for filtering content tags = [ "Media & Entertainment", "Manufacturing", "Product Design", "Scene Composition", "Visualization", "Rendering" ] # string array, each line is a new line, keep lines under 256 char and keep lines under 4 description = [ "My App is an application to showcase how to build an Omniverse App. ", "FEATURES:", "- Small and simple.", "- Easy to change." ] # array of links for more info on product [[links]] title = "Release Notes" url = "https://google.com" [[links]] title = "Documentation" url = "https://google.com"
1,398
TOML
34.871794
104
0.67525
NVIDIA-Omniverse/Blender-Addon-UMM/README.md
# DEPRECATED This repo has been deprecated. Please see [NVIDIA-Omniverse/blender_omniverse_addons](https://github.com/NVIDIA-Omniverse/blender_omniverse_addons)
164
Markdown
31.999994
148
0.804878
NVIDIA-Omniverse/Blender-Addon-UMM/omni/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. """ To invoke in Blender script editor: import bpy bpy.ops.universalmaterialmap.generator() bpy.ops.universalmaterialmap.converter() INFO_HT_header Header VIEW3D_HT_tool_header Info Header: INFO_HT_HEADER 3D View Header: VIEW3D_HT_HEADER Timeline Header: TIME_HT_HEADER Outliner Header: OUTLINER_HT_HEADER Properties Header: PROPERTIES_HT_HEADER, etc. """ """ Menu location problem https://blender.stackexchange.com/questions/3393/add-custom-menu-at-specific-location-in-the-header#:~:text=Blender%20has%20a%20built%20in,%3EPython%2D%3EUI%20Menu. """ bl_info = { 'name': 'Universal Material Map', 'author': 'NVIDIA Corporation', 'description': 'A Blender AddOn based on the Universal Material Map framework.', 'blender': (3, 1, 0), 'location': 'View3D', 'warning': '', 'category': 'Omniverse' } import sys import importlib import bpy from .universalmaterialmap.blender import developer_mode if developer_mode: print('UMM DEBUG: Initializing "{0}"'.format(__file__)) ordered_module_names = [ 'omni.universalmaterialmap', 'omni.universalmaterialmap.core', 'omni.universalmaterialmap.core.feature', 'omni.universalmaterialmap.core.singleton', 'omni.universalmaterialmap.core.data', 'omni.universalmaterialmap.core.util', 'omni.universalmaterialmap.core.operator', 'omni.universalmaterialmap.core.service', 'omni.universalmaterialmap.core.service.core', 'omni.universalmaterialmap.core.service.delegate', 'omni.universalmaterialmap.core.service.resources', 'omni.universalmaterialmap.core.service.store', 'omni.universalmaterialmap.core.converter', 'omni.universalmaterialmap.core.converter.core', 'omni.universalmaterialmap.core.converter.util', 'omni.universalmaterialmap.core.generator', 'omni.universalmaterialmap.core.generator.core', 'omni.universalmaterialmap.core.generator.util', 'omni.universalmaterialmap.blender', 'omni.universalmaterialmap.blender.menu', 'omni.universalmaterialmap.blender.converter', 'omni.universalmaterialmap.blender.generator', 'omni.universalmaterialmap.blender.material', ] for module_name in sys.modules: if 'omni.' not in module_name: continue if module_name not in ordered_module_names: raise Exception('Unexpected module name in sys.modules: {0}'.format(module_name)) for module_name in ordered_module_names: if module_name in sys.modules: print('UMM reloading: {0}'.format(module_name)) importlib.reload(sys.modules.get(module_name)) if developer_mode: from .universalmaterialmap.blender.converter import OT_InstanceToDataConverter, OT_DataToInstanceConverter, OT_DataToDataConverter, OT_ApplyDataToInstance, OT_DescribeShaderGraph from .universalmaterialmap.blender.converter import OT_CreateTemplateOmniPBR, OT_CreateTemplateOmniGlass from .universalmaterialmap.blender.menu import UniversalMaterialMapMenu from .universalmaterialmap.blender.generator import OT_Generator else: from .universalmaterialmap.blender.converter import OT_CreateTemplateOmniPBR, OT_CreateTemplateOmniGlass from .universalmaterialmap.blender.menu import UniversalMaterialMapMenu def draw_item(self, context): layout = self.layout layout.menu(UniversalMaterialMapMenu.bl_idname) def register(): bpy.utils.register_class(OT_CreateTemplateOmniPBR) bpy.utils.register_class(OT_CreateTemplateOmniGlass) if developer_mode: bpy.utils.register_class(OT_DataToInstanceConverter) bpy.utils.register_class(OT_DataToDataConverter) bpy.utils.register_class(OT_ApplyDataToInstance) bpy.utils.register_class(OT_InstanceToDataConverter) bpy.utils.register_class(OT_DescribeShaderGraph) bpy.utils.register_class(OT_Generator) bpy.utils.register_class(UniversalMaterialMapMenu) # lets add ourselves to the main header bpy.types.NODE_HT_header.append(draw_item) def unregister(): bpy.utils.unregister_class(OT_CreateTemplateOmniPBR) bpy.utils.unregister_class(OT_CreateTemplateOmniGlass) if developer_mode: bpy.utils.unregister_class(OT_DataToInstanceConverter) bpy.utils.unregister_class(OT_DataToDataConverter) bpy.utils.unregister_class(OT_ApplyDataToInstance) bpy.utils.unregister_class(OT_InstanceToDataConverter) bpy.utils.unregister_class(OT_DescribeShaderGraph) bpy.utils.unregister_class(OT_Generator) bpy.utils.unregister_class(UniversalMaterialMapMenu) bpy.types.NODE_HT_header.remove(draw_item) if __name__ == "__main__": register() # The menu can also be called from scripts # bpy.ops.wm.call_menu(name=UniversalMaterialMapMenu.bl_idname)
5,725
Python
35.471337
182
0.731528
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/util.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import sys from .data import Plug def to_plug_value_type(value: typing.Any, assumed_value_type: str) -> str: """Returns matching :class:`omni.universalmaterialmap.core.data.Plug` value type.""" if sys.version_info.major < 3: if isinstance(value, basestring): return Plug.VALUE_TYPE_STRING else: if isinstance(value, str): return Plug.VALUE_TYPE_STRING if type(value) == bool: return Plug.VALUE_TYPE_BOOLEAN if isinstance(value, int): return Plug.VALUE_TYPE_INTEGER if isinstance(value, float): return Plug.VALUE_TYPE_FLOAT try: test = iter(value) is_iterable = True except TypeError: is_iterable = False if is_iterable: if assumed_value_type == Plug.VALUE_TYPE_LIST: return Plug.VALUE_TYPE_LIST bum_booleans = 0 num_integers = 0 num_floats = 0 num_strings = 0 for o in value: if sys.version_info.major < 3: if isinstance(value, basestring): num_strings += 1 continue else: if isinstance(value, str): num_strings += 1 continue if type(o) == bool: bum_booleans += 1 continue if isinstance(o, int): num_integers += 1 continue if isinstance(o, float): num_floats += 1 if num_floats > 0: if len(value) == 2: return Plug.VALUE_TYPE_VECTOR2 if len(value) == 3: return Plug.VALUE_TYPE_VECTOR3 if len(value) == 4: return Plug.VALUE_TYPE_VECTOR4 if len(value) == 2 and assumed_value_type == Plug.VALUE_TYPE_VECTOR2: return assumed_value_type if len(value) == 3 and assumed_value_type == Plug.VALUE_TYPE_VECTOR3: return assumed_value_type if len(value) == 4 and assumed_value_type == Plug.VALUE_TYPE_VECTOR4: return assumed_value_type return Plug.VALUE_TYPE_LIST return Plug.VALUE_TYPE_ANY
3,068
Python
30.639175
88
0.592894
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/extension.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from . import *
876
Python
38.863635
74
0.729452
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
859
Python
41.999998
74
0.732247
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/data.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import uuid import sys import importlib from .service.core import IDelegate class ChangeNotification(object): def __init__(self, item: object, property_name: str, old_value: typing.Any, new_value: typing.Any): super(ChangeNotification, self).__init__() self._item: object = item self._property_name: str = property_name self._old_value: typing.Any = old_value self._new_value: typing.Any = new_value @property def item(self) -> object: """ """ return self._item @property def property_name(self) -> str: """ """ return self._property_name @property def old_value(self) -> typing.Any: """ """ return self._old_value @property def new_value(self) -> typing.Any: """ """ return self._new_value class Notifying(object): """Base class providing change notification capability""" def __init__(self): super(Notifying, self).__init__() self._changed_callbacks: typing.Dict[uuid.uuid4, typing.Callable[[ChangeNotification], typing.NoReturn]] = dict() def add_changed_fn(self, callback: typing.Callable[[ChangeNotification], typing.NoReturn]) -> uuid.uuid4: for key, value in self._changed_callbacks.items(): if value == callback: return key key = uuid.uuid4() self._changed_callbacks[key] = callback return key def remove_changed_fn(self, callback_id: uuid.uuid4) -> None: if callback_id in self._changed_callbacks.keys(): del self._changed_callbacks[callback_id] def _notify(self, notification: ChangeNotification): for callback in self._changed_callbacks.values(): callback(notification) def destroy(self): self._changed_callbacks = None class Subscribing(Notifying): def __init__(self): super(Subscribing, self).__init__() self._subscriptions: typing.Dict[Notifying, uuid.uuid4] = dict() def _subscribe(self, notifying: Notifying) -> uuid.uuid4: if notifying in self._subscriptions.keys(): return self._subscriptions[notifying] self._subscriptions[notifying] = notifying.add_changed_fn(self._on_notification) def _unsubscribe(self, notifying: Notifying) -> None: if notifying in self._subscriptions.keys(): callback_id = self._subscriptions[notifying] del self._subscriptions[notifying] notifying.remove_changed_fn(callback_id=callback_id) def _on_notification(self, notification: ChangeNotification) -> None: pass class ManagedListInsert(object): def __init__(self, notifying: Notifying, index: int): super(ManagedListInsert, self).__init__() self._notifying: Notifying = notifying self._index: int = index @property def notifying(self) -> Notifying: """ """ return self._notifying @property def index(self) -> int: """ """ return self._index class ManagedListRemove(object): def __init__(self, notifying: Notifying, index: int): super(ManagedListRemove, self).__init__() self._notifying: Notifying = notifying self._index: int = index @property def notifying(self) -> Notifying: """ """ return self._notifying @property def index(self) -> int: """ """ return self._index class ManagedListNotification(object): ADDED_ITEMS: int = 0 UPDATED_ITEMS: int = 1 REMOVED_ITEMS: int = 2 def __init__(self, managed_list: 'ManagedList', items: typing.List[typing.Union[ManagedListInsert, ChangeNotification, ManagedListRemove]]): super(ManagedListNotification, self).__init__() self._managed_list: ManagedList = managed_list self._inserted_items: typing.List[ManagedListInsert] = [] self._change_notifications: typing.List[ChangeNotification] = [] self._removed_items: typing.List[ManagedListRemove] = [] self._kind: int = -1 if isinstance(items[0], ManagedListInsert): self._kind = ManagedListNotification.ADDED_ITEMS self._inserted_items = typing.cast(typing.List[ManagedListInsert], items) elif isinstance(items[0], ChangeNotification): self._kind = ManagedListNotification.UPDATED_ITEMS self._change_notifications = typing.cast(typing.List[ChangeNotification], items) elif isinstance(items[0], ManagedListRemove): self._kind = ManagedListNotification.REMOVED_ITEMS self._removed_items = typing.cast(typing.List[ManagedListRemove], items) else: raise Exception('Unexpected object: "{0}" of type "{1}".'.format(items[0], type(items[0]))) @property def managed_list(self) -> 'ManagedList': """ """ return self._managed_list @property def kind(self) -> int: """ """ return self._kind @property def inserted_items(self) -> typing.List[ManagedListInsert]: """ """ return self._inserted_items @property def change_notifications(self) -> typing.List[ChangeNotification]: """ """ return self._change_notifications @property def removed_items(self) -> typing.List[ManagedListRemove]: """ """ return self._removed_items class ManagedList(object): def __init__(self, items: typing.List[Notifying] = None): super(ManagedList, self).__init__() self._subscriptions: typing.Dict[Notifying, uuid.uuid4] = dict() self._changed_callbacks: typing.Dict[uuid.uuid4, typing.Callable[[ManagedListNotification], typing.NoReturn]] = dict() self._managed_items: typing.List[Notifying] = [] if items: for o in items: self._manage_item(notifying=o) def __iter__(self): return iter(self._managed_items) def _manage_item(self, notifying: Notifying) -> typing.Union[Notifying, None]: """ Subscribes to managed item. Returns item only if it became managed. """ if notifying in self._managed_items: return None self._managed_items.append(notifying) self._subscriptions[notifying] = notifying.add_changed_fn(self._on_notification) return notifying def _unmanage_item(self, notifying: Notifying) -> typing.Union[typing.Tuple[Notifying, int], typing.Tuple[None, int]]: """ Unsubscribes to managed item. Returns item only if it became unmanaged. """ if notifying not in self._managed_items: return None, -1 index = self._managed_items.index(notifying) self._managed_items.remove(notifying) callback_id = self._subscriptions[notifying] del self._subscriptions[notifying] notifying.remove_changed_fn(callback_id=callback_id) return notifying, index def _on_notification(self, notification: ChangeNotification) -> None: self._notify( notification=ManagedListNotification( managed_list=self, items=[notification] ) ) def _notify(self, notification: ManagedListNotification): for callback in self._changed_callbacks.values(): callback(notification) def add_changed_fn(self, callback: typing.Callable[[ManagedListNotification], typing.NoReturn]) -> uuid.uuid4: for key, value in self._changed_callbacks.items(): if value == callback: return key key = uuid.uuid4() self._changed_callbacks[key] = callback return key def remove_changed_fn(self, callback_id: uuid.uuid4) -> None: if callback_id in self._changed_callbacks.keys(): del self._changed_callbacks[callback_id] def append(self, notifying: Notifying) -> None: if self._manage_item(notifying=notifying) is not None: self._notify( ManagedListNotification( managed_list=self, items=[ManagedListInsert(notifying=notifying, index=self.index(notifying=notifying))] ) ) def extend(self, notifying: typing.List[Notifying]) -> None: added = [] for o in notifying: o = self._manage_item(notifying=o) if o: added.append(o) if len(added) == 0: return self._notify( ManagedListNotification( managed_list=self, items=[ManagedListInsert(notifying=o, index=self.index(notifying=o)) for o in added] ) ) def remove(self, notifying: Notifying) -> None: notifying, index = self._unmanage_item(notifying=notifying) if notifying: self._notify( ManagedListNotification( managed_list=self, items=[ManagedListRemove(notifying=notifying, index=index)] ) ) def remove_all(self) -> None: items = [ManagedListRemove(notifying=o, index=i) for i, o in enumerate(self._managed_items)] for callback_id, notifying in self._subscriptions.items(): notifying.remove_changed_fn(callback_id=callback_id) self._subscriptions = dict() self._managed_items = [] self._notify( ManagedListNotification( managed_list=self, items=items ) ) def pop(self, index: int = 0) -> Notifying: notifying, index = self._unmanage_item(self._managed_items[index]) self._notify( ManagedListNotification( managed_list=self, items=[ManagedListRemove(notifying=notifying, index=index)] ) ) return notifying def index(self, notifying: Notifying) -> int: if notifying in self._managed_items: return self._managed_items.index(notifying) return -1 class Serializable(Subscribing): """Base class providing serialization method template""" def __init__(self): super(Serializable, self).__init__() def serialize(self) -> dict: """ """ return dict() def deserialize(self, data: dict) -> None: """ """ pass class Base(Serializable): """Base class providing id property""" @classmethod def Create(cls) -> 'Base': return cls() def __init__(self): super(Base, self).__init__() self._id: str = str(uuid.uuid4()) def serialize(self) -> dict: """ """ output = super(Base, self).serialize() output['_id'] = self._id return output def deserialize(self, data: dict) -> None: """ """ super(Base, self).deserialize(data=data) self._id = data['_id'] if '_id' in data.keys() else str(uuid.uuid4()) @property def id(self) -> str: """ """ return self._id class DagNode(Base): """Base class providing input and outputs of :class:`omni.universalmaterialmap.core.data.Plug` """ def __init__(self): super(DagNode, self).__init__() self._inputs: typing.List[Plug] = [] self._outputs: typing.List[Plug] = [] self._computing: bool = False def serialize(self) -> dict: """ """ output = super(DagNode, self).serialize() output['_inputs'] = [plug.serialize() for plug in self.inputs] output['_outputs'] = [plug.serialize() for plug in self.outputs] return output def deserialize(self, data: dict) -> None: """ """ super(DagNode, self).deserialize(data=data) old_inputs = self._inputs[:] old_outputs = self._outputs[:] while len(self._inputs): self._unsubscribe(notifying=self._inputs.pop()) while len(self._outputs): self._unsubscribe(notifying=self._outputs.pop()) plugs = [] if '_inputs' in data.keys(): for o in data['_inputs']: plug = Plug(parent=self) plug.deserialize(data=o) plugs.append(plug) self._inputs = plugs plugs = [] if '_outputs' in data.keys(): for o in data['_outputs']: plug = Plug(parent=self) plug.deserialize(data=o) plugs.append(plug) self._outputs = plugs for o in self._inputs: self._subscribe(notifying=o) for o in self._outputs: self._subscribe(notifying=o) if not old_inputs == self._inputs: self._notify( ChangeNotification( item=self, property_name='inputs', old_value=old_inputs, new_value=self._inputs[:] ) ) if not old_inputs == self._outputs: self._notify( ChangeNotification( item=self, property_name='outputs', old_value=old_outputs, new_value=self._outputs[:] ) ) def _on_notification(self, notification: ChangeNotification) -> None: if notification.item == self: return # Re-broadcast notification self._notify(notification=notification) def invalidate(self, plug: 'Plug'): pass def compute(self) -> None: """ """ if self._computing: return self._computing = True self._compute_inputs(input_plugs=self._inputs) self._compute_outputs(output_plugs=self._outputs) self._computing = False def _compute_inputs(self, input_plugs: typing.List['Plug']): # Compute dependencies for plug in input_plugs: if not plug.input: continue if not plug.input.parent: continue if not plug.input.is_invalid: continue plug.input.parent.compute() # Set computed_value for plug in input_plugs: if plug.input: plug.computed_value = plug.input.computed_value else: plug.computed_value = plug.value def _compute_outputs(self, output_plugs: typing.List['Plug']): # Compute dependencies for plug in output_plugs: if not plug.input: continue if not plug.input.parent: continue if not plug.input.is_invalid: continue plug.input.parent.compute() # Set computed_value for plug in output_plugs: if plug.input: plug.computed_value = plug.input.computed_value else: plug.computed_value = plug.value def add_input(self) -> 'Plug': raise NotImplementedError() def can_remove_plug(self, plug: 'Plug') -> bool: return plug.is_removable def remove_plug(self, plug: 'Plug') -> None: if not plug.is_removable: raise Exception('Plug is not removable') notifications = [] if plug in self._inputs: old_value = self._inputs[:] self._unsubscribe(notifying=plug) self._inputs.remove(plug) notifications.append( ChangeNotification( item=self, property_name='inputs', old_value=old_value, new_value=self._inputs[:] ) ) if plug in self._outputs: old_value = self._outputs[:] self._unsubscribe(notifying=plug) self._outputs.remove(plug) notifications.append( ChangeNotification( item=self, property_name='outputs', old_value=old_value, new_value=self._outputs[:] ) ) destination: Plug for destination in plug.outputs: destination.input = None for notification in notifications: self._notify(notification=notification) @property def can_add_input(self) -> bool: return False @property def inputs(self) -> typing.List['Plug']: """ """ return self._inputs @property def outputs(self) -> typing.List['Plug']: """ """ return self._outputs class GraphEntity(DagNode): """Base class providing omni.kit.widget.graph properties for a data item.""" OPEN = 0 MINIMIZED = 1 CLOSED = 2 def __init__(self): super(GraphEntity, self).__init__() self._display_name: str = '' self._position: typing.Union[typing.Tuple[float, float], None] = None self._expansion_state: int = GraphEntity.OPEN self._show_inputs: bool = True self._show_outputs: bool = True self._show_peripheral: bool = False def serialize(self) -> dict: """ """ output = super(GraphEntity, self).serialize() output['_display_name'] = self._display_name output['_position'] = self._position output['_expansion_state'] = self._expansion_state output['_show_inputs'] = self._show_inputs output['_show_outputs'] = self._show_outputs output['_show_peripheral'] = self._show_peripheral return output def deserialize(self, data: dict) -> None: """ """ super(GraphEntity, self).deserialize(data=data) self._display_name = data['_display_name'] if '_display_name' in data.keys() else '' self._position = data['_position'] if '_position' in data.keys() else None self._expansion_state = data['_expansion_state'] if '_expansion_state' in data.keys() else GraphEntity.OPEN self._show_inputs = data['_show_inputs'] if '_show_inputs' in data.keys() else True self._show_outputs = data['_show_outputs'] if '_show_outputs' in data.keys() else True self._show_peripheral = data['_show_peripheral'] if '_show_peripheral' in data.keys() else False @property def display_name(self) -> str: """ """ return self._display_name @display_name.setter def display_name(self, value: str) -> None: """ """ if self._display_name is value: return notification = ChangeNotification( item=self, property_name='display_name', old_value=self._display_name, new_value=value ) self._display_name = value self._notify(notification=notification) @property def position(self) -> typing.Union[typing.Tuple[float, float], None]: """ """ return self._position @position.setter def position(self, value: typing.Union[typing.Tuple[float, float], None]) -> None: """ """ if self._position is value: return notification = ChangeNotification( item=self, property_name='position', old_value=self._position, new_value=value ) self._position = value self._notify(notification=notification) @property def expansion_state(self) -> int: """ """ return self._expansion_state @expansion_state.setter def expansion_state(self, value: int) -> None: """ """ if self._expansion_state is value: return notification = ChangeNotification( item=self, property_name='expansion_state', old_value=self._expansion_state, new_value=value ) self._expansion_state = value self._notify(notification=notification) @property def show_inputs(self) -> bool: """ """ return self._show_inputs @show_inputs.setter def show_inputs(self, value: bool) -> None: """ """ if self._show_inputs is value: return notification = ChangeNotification( item=self, property_name='show_inputs', old_value=self._show_inputs, new_value=value ) self._show_inputs = value self._notify(notification=notification) @property def show_outputs(self) -> bool: """ """ return self._show_outputs @show_outputs.setter def show_outputs(self, value: bool) -> None: """ """ if self._show_outputs is value: return notification = ChangeNotification( item=self, property_name='show_outputs', old_value=self._show_outputs, new_value=value ) self._show_outputs = value self._notify(notification=notification) @property def show_peripheral(self) -> bool: """ """ return self._show_peripheral @show_peripheral.setter def show_peripheral(self, value: bool) -> None: """ """ if self._show_peripheral is value: return notification = ChangeNotification( item=self, property_name='show_peripheral', old_value=self._show_peripheral, new_value=value ) self._show_peripheral = value self._notify(notification=notification) class Connection(Serializable): def __init__(self): super(Connection, self).__init__() self._source_id = '' self._destination_id = '' def serialize(self) -> dict: output = super(Connection, self).serialize() output['_source_id'] = self._source_id output['_destination_id'] = self._destination_id return output def deserialize(self, data: dict) -> None: super(Connection, self).deserialize(data=data) self._source_id = data['_source_id'] if '_source_id' in data.keys() else '' self._destination_id = data['_destination_id'] if '_destination_id' in data.keys() else '' @property def source_id(self): return self._source_id @property def destination_id(self): return self._destination_id class Plug(Base): """ A Plug can be: a source an output both a source and an output a container for a static value - most likely as an output a container for an editable value - most likely as an output plug.default_value Starting point and for resetting. plug.value Apply as computed_value if there is no input or dependency providing a value. plug.computed_value Final value. Could be thought of as plug.output_value. Plug is_dirty on input connect input disconnect value change if not connected A Plug is_dirty if it is_dirty its input is_dirty any dependency is_dirty """ VALUE_TYPE_ANY = 'any' VALUE_TYPE_FLOAT = 'float' VALUE_TYPE_INTEGER = 'int' VALUE_TYPE_STRING = 'str' VALUE_TYPE_BOOLEAN = 'bool' VALUE_TYPE_NODE_ID = 'node_id' VALUE_TYPE_VECTOR2 = 'vector2' VALUE_TYPE_VECTOR3 = 'vector3' VALUE_TYPE_VECTOR4 = 'vector4' VALUE_TYPE_ENUM = 'enum' VALUE_TYPE_LIST = 'list' VALUE_TYPES = [ VALUE_TYPE_ANY, VALUE_TYPE_FLOAT, VALUE_TYPE_INTEGER, VALUE_TYPE_STRING, VALUE_TYPE_BOOLEAN, VALUE_TYPE_NODE_ID, VALUE_TYPE_VECTOR2, VALUE_TYPE_VECTOR3, VALUE_TYPE_VECTOR4, VALUE_TYPE_ENUM, VALUE_TYPE_LIST, ] @classmethod def Create( cls, parent: DagNode, name: str, display_name: str, value_type: str = 'any', editable: bool = False, is_removable: bool = False, ) -> 'Plug': instance = cls(parent=parent) instance._name = name instance._display_name = display_name instance._value_type = value_type instance._is_editable = editable instance._is_removable = is_removable return instance def __init__(self, parent: DagNode): super(Plug, self).__init__() self._parent: DagNode = parent self._name: str = '' self._display_name: str = '' self._value_type: str = Plug.VALUE_TYPE_ANY self._internal_value_type: str = Plug.VALUE_TYPE_ANY self._is_peripheral: bool = False self._is_editable: bool = False self._is_removable: bool = False self._default_value: typing.Any = None self._computed_value: typing.Any = None self._value: typing.Any = None self._is_invalid: bool = False self._input: typing.Union[Plug, typing.NoReturn] = None self._outputs: typing.List[Plug] = [] self._enum_values: typing.List = [] def serialize(self) -> dict: output = super(Plug, self).serialize() output['_name'] = self._name output['_display_name'] = self._display_name output['_value_type'] = self._value_type output['_internal_value_type'] = self._internal_value_type output['_is_peripheral'] = self._is_peripheral output['_is_editable'] = self._is_editable output['_is_removable'] = self._is_removable output['_default_value'] = self._default_value output['_value'] = self._value output['_enum_values'] = self._enum_values return output def deserialize(self, data: dict) -> None: super(Plug, self).deserialize(data=data) self._input = None self._name = data['_name'] if '_name' in data.keys() else '' self._display_name = data['_display_name'] if '_display_name' in data.keys() else '' self._value_type = data['_value_type'] if '_value_type' in data.keys() else Plug.VALUE_TYPE_ANY self._internal_value_type = data['_internal_value_type'] if '_internal_value_type' in data.keys() else None self._is_peripheral = data['_is_peripheral'] if '_is_peripheral' in data.keys() else False self._is_editable = data['_is_editable'] if '_is_editable' in data.keys() else False self._is_removable = data['_is_removable'] if '_is_removable' in data.keys() else False self._default_value = data['_default_value'] if '_default_value' in data.keys() else None self._value = data['_value'] if '_value' in data.keys() else self._default_value self._enum_values = data['_enum_values'] if '_enum_values' in data.keys() else [] def invalidate(self) -> None: if self._is_invalid: return self._is_invalid = True if self.parent: self.parent.invalidate(self) @property def parent(self) -> DagNode: return self._parent @property def name(self) -> str: return self._name @name.setter def name(self, value: str) -> None: if self._name is value: return notification = ChangeNotification( item=self, property_name='name', old_value=self._name, new_value=value ) self._name = value self._notify(notification=notification) @property def display_name(self) -> str: return self._display_name @display_name.setter def display_name(self, value: str) -> None: if self._display_name is value: return notification = ChangeNotification( item=self, property_name='display_name', old_value=self._display_name, new_value=value ) self._display_name = value self._notify(notification=notification) @property def value_type(self) -> str: return self._value_type @value_type.setter def value_type(self, value: str) -> None: if self._value_type is value: return notification = ChangeNotification( item=self, property_name='value_type', old_value=self._value_type, new_value=value ) self._value_type = value self._notify(notification=notification) @property def internal_value_type(self) -> str: return self._internal_value_type @internal_value_type.setter def internal_value_type(self, value: str) -> None: if self._internal_value_type is value: return notification = ChangeNotification( item=self, property_name='internal_value_type', old_value=self._internal_value_type, new_value=value ) self._internal_value_type = value self._notify(notification=notification) @property def is_removable(self) -> bool: return self._is_removable @property def is_peripheral(self) -> bool: return self._is_peripheral @is_peripheral.setter def is_peripheral(self, value: bool) -> None: if self._is_peripheral is value: return notification = ChangeNotification( item=self, property_name='is_peripheral', old_value=self._is_peripheral, new_value=value ) self._is_peripheral = value self._notify(notification=notification) @property def computed_value(self) -> typing.Any: return self._computed_value @computed_value.setter def computed_value(self, value: typing.Any) -> None: if self._computed_value is value: self._is_invalid = False self._value = self._computed_value return notification = ChangeNotification( item=self, property_name='computed_value', old_value=self._computed_value, new_value=value ) if self._input and self._input.is_invalid: print('WARNING: Universal Material Map: Compute encountered an unexpected state: input invalid after compute. Results may be incorrect.') print('\tplug: "{0}"'.format(self.name)) if self._parent: print('\tplug.parent: "{0}"'.format(self._parent.__class__.__name__)) print('\tplug.input: "{0}"'.format(self._input.name)) if self._input.parent: print('\tplug.input.parent: "{0}"'.format(self._input.parent.__class__.__name__)) return self._is_invalid = False self._computed_value = value self._value = self._computed_value self._notify(notification=notification) @property def value(self) -> typing.Any: return self._value @value.setter def value(self, value: typing.Any) -> None: if self._value is value: return notification = ChangeNotification( item=self, property_name='value', old_value=self._value, new_value=value ) self._value = value self._notify(notification=notification) if self._input is None: self.invalidate() @property def is_invalid(self) -> typing.Any: if self._input and self._input._is_invalid: return True return self._is_invalid @property def input(self) -> typing.Union['Plug', typing.NoReturn]: return self._input @input.setter def input(self, value: typing.Union['Plug', typing.NoReturn]) -> None: if self._input is value: return notification = ChangeNotification( item=self, property_name='input', old_value=self._input, new_value=value ) self._input = value self._notify(notification=notification) self.invalidate() @property def outputs(self) -> typing.List['Plug']: return self._outputs @property def is_editable(self) -> bool: return self._is_editable @is_editable.setter def is_editable(self, value: bool) -> None: if self._is_editable is value: return notification = ChangeNotification( item=self, property_name='is_editable', old_value=self._is_editable, new_value=value ) self._is_editable = value self._notify(notification=notification) @property def default_value(self) -> typing.Any: return self._default_value @default_value.setter def default_value(self, value: typing.Any) -> None: if self._default_value is value: return notification = ChangeNotification( item=self, property_name='default_value', old_value=self._default_value, new_value=value ) self._default_value = value self._notify(notification=notification) @property def enum_values(self) -> typing.List: return self._enum_values @enum_values.setter def enum_values(self, value: typing.List) -> None: if self._enum_values is value: return notification = ChangeNotification( item=self, property_name='enum_values', old_value=self._enum_values, new_value=value ) self._enum_values = value self._notify(notification=notification) class Node(DagNode): @classmethod def Create(cls, class_name: str) -> 'Node': instance = typing.cast(Node, super(Node, cls).Create()) instance._class_name = class_name return instance def __init__(self): super(Node, self).__init__() self._class_name: str = '' def serialize(self) -> dict: output = super(Node, self).serialize() output['_class_name'] = self._class_name return output def deserialize(self, data: dict) -> None: super(Node, self).deserialize(data=data) self._class_name = data['_class_name'] if '_class_name' in data.keys() else '' @property def class_name(self): return self._class_name class Client(Serializable): ANY_VERSION = 'any' NO_VERSION = 'none' DCC_OMNIVERSE_CREATE = 'Omniverse Create' DCC_3DS_MAX = '3ds MAX' DCC_MAYA = 'Maya' DCC_HOUDINI = 'Houdini' DCC_SUBSTANCE_DESIGNER = 'Substance Designer' DCC_SUBSTANCE_PAINTER = 'Substance Painter' DCC_BLENDER = 'Blender' @classmethod def Autodesk_3dsMax(cls, version: str = ANY_VERSION) -> 'Client': instance = Client() instance._name = Client.DCC_3DS_MAX instance._version = version return instance @classmethod def Autodesk_Maya(cls, version: str = ANY_VERSION) -> 'Client': instance = Client() instance._name = Client.DCC_MAYA instance._version = version return instance @classmethod def OmniverseCreate(cls, version: str = ANY_VERSION) -> 'Client': instance = Client() instance._name = Client.DCC_OMNIVERSE_CREATE instance._version = version return instance @classmethod def Blender(cls, version: str = ANY_VERSION) -> 'Client': instance = Client() instance._name = Client.DCC_BLENDER instance._version = version return instance def __init__(self): super(Client, self).__init__() self._name: str = '' self._version: str = '' def __eq__(self, other: 'Client') -> bool: if not isinstance(other, Client): return False return other.name == self._name and other.version == self._version def is_compatible(self, other: 'Client') -> bool: if not isinstance(other, Client): return False if other == self: return True return other._version == Client.ANY_VERSION or self._version == Client.ANY_VERSION def serialize(self) -> dict: output = super(Client, self).serialize() output['_name'] = self._name output['_version'] = self._version return output def deserialize(self, data: dict) -> None: super(Client, self).deserialize(data=data) self._name = data['_name'] if '_name' in data.keys() else '' self._version = data['_version'] if '_version' in data.keys() else '' @property def name(self) -> str: return self._name @name.setter def name(self, value: str) -> None: self._name = value @property def version(self) -> str: return self._version @version.setter def version(self, value: str) -> None: self._version = value class AssemblyMetadata(Serializable): CATEGORY_BASE = 'Base Materials' CATEGORY_CONNECTOR = 'Connector Materials' CATEGORIES = [ CATEGORY_BASE, CATEGORY_CONNECTOR, ] def __init__(self): super(AssemblyMetadata, self).__init__() self._category = '' self._name = '' self._keywords: typing.List[str] = [] self._supported_clients: typing.List[Client] = [] def serialize(self) -> dict: output = super(AssemblyMetadata, self).serialize() output['_category'] = self._category output['_name'] = self._name output['_keywords'] = self._keywords output['_supported_clients'] = [o.serialize() for o in self._supported_clients] return output def deserialize(self, data: dict) -> None: super(AssemblyMetadata, self).deserialize(data=data) self._category = data['_category'] if '_category' in data.keys() else '' self._name = data['_name'] if '_name' in data.keys() else '' self._keywords = data['_keywords'] if '_keywords' in data.keys() else '' items = [] if '_supported_clients' in data.keys(): for o in data['_supported_clients']: item = Client() item.deserialize(data=o) items.append(item) self._supported_clients = items @property def category(self) -> str: return self._category @category.setter def category(self, value: str) -> None: self._category = value @property def name(self) -> str: return self._name @name.setter def name(self, value: str) -> None: self._name = value @property def keywords(self) -> typing.List[str]: return self._keywords @keywords.setter def keywords(self, value: typing.List[str]) -> None: self._keywords = value @property def supported_clients(self) -> typing.List[Client]: return self._supported_clients class Target(GraphEntity): def __init__(self): super(Target, self).__init__() self._nodes: typing.List[Node] = [] self._metadata: AssemblyMetadata = AssemblyMetadata() self._root_node_id: str = '' self._root_node: Node = None self._revision: int = 0 self._store_id: str = '' self._connections: typing.List[Connection] = [] def serialize(self) -> dict: output = super(Target, self).serialize() output['_nodes'] = [node.serialize() for node in self.nodes] output['_metadata'] = self._metadata.serialize() output['_root_node_id'] = self._root_node_id output['_revision'] = self._revision output['_connections'] = [o.serialize() for o in self._connections] return output def deserialize(self, data: dict) -> None: super(Target, self).deserialize(data=data) self._root_node_id = data['_root_node_id'] if '_root_node_id' in data.keys() else '' nodes = [] if '_nodes' in data.keys(): for o in data['_nodes']: node = Node() node.deserialize(data=o) nodes.append(node) self._nodes = nodes root_node = None if self._root_node_id: for node in self._nodes: if node.id == self._root_node_id: root_node = node break self._root_node = root_node metadata = AssemblyMetadata() if '_metadata' in data.keys(): metadata.deserialize(data=data['_metadata']) self._metadata = metadata self._revision = data['_revision'] if '_revision' in data.keys() else 0 items = [] if '_connections' in data.keys(): for o in data['_connections']: item = Connection() item.deserialize(data=o) items.append(item) self._connections = items for connection in self._connections: input_plug: Plug = None output_plug: Plug = None for node in self._nodes: for plug in node.inputs: if connection.source_id == plug.id: input_plug = plug elif connection.destination_id == plug.id: input_plug = plug for plug in node.outputs: if connection.source_id == plug.id: output_plug = plug elif connection.destination_id == plug.id: output_plug = plug if input_plug is not None and output_plug is not None: break if input_plug is None or output_plug is None: continue if output_plug not in input_plug.outputs: input_plug.outputs.append(output_plug) output_plug.input = input_plug def connect(self, source: Plug, destination: Plug) -> None: for connection in self._connections: if connection.source_id == source.id and connection.destination_id == destination.id: return connection = Connection() connection._source_id = source.id connection._destination_id = destination.id self._connections.append(connection) if destination not in source.outputs: source.outputs.append(destination) destination.input = source @property def nodes(self) -> typing.List[Node]: return self._nodes @property def metadata(self) -> AssemblyMetadata: return self._metadata @property def root_node(self) -> Node: return self._root_node @root_node.setter def root_node(self, value: Node) -> None: self._root_node = value self._root_node_id = self._root_node.id if self._root_node else '' @property def revision(self) -> int: return self._revision @revision.setter def revision(self, value: int) -> None: self._revision = value @property def store_id(self) -> str: return self._store_id @store_id.setter def store_id(self, value: int) -> None: if self._store_id is value: return notification = ChangeNotification( item=self, property_name='store_id', old_value=self._store_id, new_value=value ) self._store_id = value self._notify(notification=notification) class TargetInstance(GraphEntity): @classmethod def FromAssembly(cls, assembly: Target) -> 'TargetInstance': instance = cls() instance._target_id = assembly.id instance.target = assembly instance.display_name = assembly.display_name return instance def __init__(self): super(TargetInstance, self).__init__() self._target_id: str = '' self._target: typing.Union[Target, typing.NoReturn] = None self._is_setting_target = False def serialize(self) -> dict: super(TargetInstance, self).serialize() output = GraphEntity.serialize(self) output['_target_id'] = self._target_id output['_inputs'] = [] output['_outputs'] = [] return output def deserialize(self, data: dict) -> None: """ Does not invoke super on DagNode base class because inputs and outputs are derived from assembly instance. """ data['_inputs'] = [] data['_outputs'] = [] GraphEntity.deserialize(self, data=data) self._target_id = data['_target_id'] if '_target_id' in data.keys() else '' def invalidate(self, plug: 'Plug' = None): """ Invalidate any plug that is a destination of an output plug named plug.name. """ # If a destination is invalidated it is assumed compute will be invoked once a destination endpoint has been found do_compute = True output: Plug destination: Plug for output in self.outputs: if not plug or output.name == plug.name: for destination in output.outputs: destination.invalidate() do_compute = False if do_compute: self.compute() @property def target_id(self) -> str: return self._target_id @property def target(self) -> typing.Union[Target, typing.NoReturn]: return self._target @target.setter def target(self, value: typing.Union[Target, typing.NoReturn]) -> None: if self._target is value: return if not self._target_id and value: raise Exception('Target ID "" does not match assembly instance "{0}".'.format(value.id)) if self._target_id and not value: raise Exception('Target ID "{0}" does not match assembly instance "None".'.format(self._target_id)) if self._target_id and value and not self._target_id == value.id: raise Exception('Target ID "{0}" does not match assembly instance "{1}".'.format(self._target_id, value.id)) self._is_setting_target = True notification = ChangeNotification( item=self, property_name='target', old_value=self._target, new_value=value ) self._target = value self._inputs = [] self._outputs = [] if self._target: node_id_plug = Plug.Create( parent=self, name='node_id_output', display_name='Node Id', value_type=Plug.VALUE_TYPE_STRING ) node_id_plug._id = self._target.id node_id_plug.value = self._target.id self._outputs.append(node_id_plug) for node in self._target.nodes: for o in node.inputs: plug = Plug(parent=self) plug.deserialize(data=o.serialize()) self._inputs.append(plug) for o in node.outputs: plug = Plug(parent=self) plug.deserialize(data=o.serialize()) self._outputs.append(plug) self._is_setting_target = False self._notify(notification=notification) self.invalidate() class Operator(Base): def __init__( self, id: str, name: str, required_inputs: int, min_inputs: int, max_inputs: int, num_outputs: int, ): super(Operator, self).__init__() self._id = id self._name: str = name self._required_inputs: int = required_inputs self._min_inputs: int = min_inputs self._max_inputs: int = max_inputs self._num_outputs: int = num_outputs self._computing: bool = False def compute(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): """ Base class only computes input_plugs. It is assumed that extending class computes output plugs. """ if self._computing: return self._computing = True if len(input_plugs) < self._required_inputs: raise Exception('Array of inputs not of required length "{0}". Actual length "{1}". Operator: "{2}"'.format(self._required_inputs, len(input_plugs), self.__class__.__name__)) for plug in input_plugs: if plug.input: if plug.input in input_plugs: print('WARNING: Universal Material Map: Invalid state in compute graph. Compute cancelled.') print('\tInput {0}.{1} is dependent on another input on the same node.'.format(plug.parent.display_name, plug.name)) print('\tDependency: {0}.{1}'.format(plug.input.parent.display_name, plug.input.name)) print('\tThis is not supported.') print('\tComputations likely to not behave as expected. It is recommended you restart the solution using this data.') self._computing = False return if plug.input in output_plugs: print('WARNING: Universal Material Map: Invalid state in compute graph. Compute cancelled.') print('\tInput {0}.{1} is dependent on another output on the same node.'.format( plug.parent.display_name, plug.name)) print('\tDependency: {0}.{1}'.format(plug.input.parent.display_name, plug.input.name)) print('\tThis is not supported.') print('\tComputations likely to not behave as expected. It is recommended you restart the solution using this data.') self._computing = False return for plug in output_plugs: if plug.input: if plug.input in output_plugs: print('WARNING: Universal Material Map: Invalid state in compute graph. Compute cancelled.') print('\tInput {0}.{1} is dependent on another output on the same node.'.format( plug.parent.display_name, plug.name)) print('\tDependency: {0}.{1}'.format(plug.input.parent.display_name, plug.input.name)) print('\tThis is not supported.') print('\tComputations likely to not behave as expected. It is recommended you restart the solution using this data.') self._computing = False return self._compute_inputs(input_plugs=input_plugs) self._compute_outputs(input_plugs=input_plugs, output_plugs=output_plugs) self._computing = False def _compute_inputs(self, input_plugs: typing.List[Plug]): # Compute dependencies for plug in input_plugs: if not plug.input: continue if not plug.input.parent: continue if not plug.input.is_invalid: continue plug.input.parent.compute() # Set computed_value for plug in input_plugs: if plug.input: plug.computed_value = plug.input.computed_value else: plug.computed_value = plug.value def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): raise NotImplementedError(self.__class__) def generate_input(self, parent: 'DagNode', index: int) -> Plug: """ Base class provides method template but does nothing. """ pass def generate_output(self, parent: 'DagNode', index: int) -> Plug: """ Base class provides method template but does nothing. """ pass def test(self) -> None: parent = OperatorInstance() inputs = [] while len(inputs) < self.min_inputs: inputs.append( self.generate_input(parent=parent, index=len(inputs)) ) outputs = [] while len(outputs) < self.num_outputs: outputs.append( self.generate_output(parent=parent, index=len(outputs)) ) self._prepare_plugs_for_test(input_plugs=inputs, output_plugs=outputs) self._perform_test(input_plugs=inputs, output_plugs=outputs) self._assert_test(input_plugs=inputs, output_plugs=outputs) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass def _perform_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): self.compute(input_plugs=input_plugs, output_plugs=output_plugs) def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): raise NotImplementedError() def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: if not plug.is_removable: raise Exception('Plug is not removable') notifications = [] if plug in operator_instance._inputs: old_value = operator_instance._inputs[:] operator_instance._inputs.remove(plug) operator_instance._unsubscribe(notifying=plug) notifications.append( ChangeNotification( item=operator_instance, property_name='inputs', old_value=old_value, new_value=operator_instance._inputs[:] ) ) if plug in operator_instance._outputs: old_value = operator_instance._outputs[:] operator_instance._outputs.remove(plug) operator_instance._unsubscribe(notifying=plug) notifications.append( ChangeNotification( item=operator_instance, property_name='outputs', old_value=old_value, new_value=operator_instance._outputs[:] ) ) destination: Plug for destination in plug.outputs: destination.input = None for notification in notifications: for callback in operator_instance._changed_callbacks.values(): callback(notification) @property def name(self) -> str: return self._name @property def min_inputs(self) -> int: return self._min_inputs @property def max_inputs(self) -> int: return self._max_inputs @property def required_inputs(self) -> int: return self._required_inputs @property def num_outputs(self) -> int: return self._num_outputs class GraphOutput(Operator): """ Output resolves to a node id. """ def __init__(self): super(GraphOutput, self).__init__( id='5f39ab48-5bee-46fe-9a22-0f678013568e', name='Graph Output', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=1 ) def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_node_id', display_name='Node Id', value_type=Plug.VALUE_TYPE_NODE_ID) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output_node_id', display_name='Node Id', value_type=Plug.VALUE_TYPE_NODE_ID) raise Exception('Output index "{0}" not supported.'.format(index)) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = input_plugs[0].computed_value def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].computed_value = self.id def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == self.id: raise Exception('Test failed.') class OperatorInstance(GraphEntity): @classmethod def FromOperator(cls, operator: Operator) -> 'OperatorInstance': instance = OperatorInstance() instance._is_deserializing = True instance._operator = operator instance._display_name = operator.name while len(instance._inputs) < operator.min_inputs: instance._inputs.append( operator.generate_input(parent=instance, index=len(instance._inputs)) ) while len(instance._outputs) < operator.num_outputs: instance._outputs.append( operator.generate_output(parent=instance, index=len(instance._outputs)) ) instance._operator_module = operator.__class__.__module__ instance._operator_class_name = operator.__class__.__name__ instance._is_deserializing = False instance.invalidate() return instance def __init__(self): super(OperatorInstance, self).__init__() self._description: str = '' self._operator_module: str = '' self._operator_class_name: str = '' self._operator: Operator = None self._is_deserializing = False def serialize(self) -> dict: output = super(OperatorInstance, self).serialize() output['_description'] = self._description output['_operator_module'] = self._operator_module output['_operator_class_name'] = self._operator_class_name return output def deserialize(self, data: dict) -> None: self._is_deserializing = True super(OperatorInstance, self).deserialize(data=data) self._description = data['_description'] if '_description' in data.keys() else '' self._operator_module = data['_operator_module'] if '_operator_module' in data.keys() else '' self._operator_class_name = data['_operator_class_name'] if '_operator_class_name' in data.keys() else '' if not self._operator_module: raise Exception('Unexpected data: no valid "operator module" defined') if not self._operator_class_name: raise Exception('Unexpected data: no valid "operator class name" defined') if self._operator_module not in sys.modules.keys(): importlib.import_module(self._operator_module) module_pointer = sys.modules[self._operator_module] class_pointer = module_pointer.__dict__[self._operator_class_name] self._operator = typing.cast(Operator, class_pointer()) notifying = [] while len(self._inputs) < self._operator.min_inputs: plug = self._operator.generate_input(parent=self, index=len(self._inputs)) self._inputs.append(plug) notifying.append(plug) while len(self._outputs) < self._operator.num_outputs: plug = self._operator.generate_output(parent=self, index=len(self._outputs)) self._outputs.append(plug) notifying.append(plug) self._is_deserializing = False for o in notifying: self._subscribe(notifying=o) self.invalidate() def invalidate(self, plug: 'Plug' = None): """ Because one plug changed we assume any connected plug to any output needs to be invalidated. """ if self._is_deserializing: return # Set all outputs to invalid output: Plug for output in self.outputs: output._is_invalid = True # If a destination is invalidated it is assumed compute will be invoked once a destination endpoint has been found do_compute = True destination: Plug for output in self.outputs: for destination in output.outputs: destination.invalidate() do_compute = False if do_compute: self.compute() def compute(self) -> None: if self._operator: self._operator.compute(input_plugs=self._inputs, output_plugs=self._outputs) def add_input(self) -> Plug: if not self.can_add_input: raise Exception('Cannot add another input.') old_value = self._inputs[:] plug = self._operator.generate_input(parent=self, index=len(self._inputs)) self._inputs.append(plug) self._subscribe(notifying=plug) notification = ChangeNotification( item=self, property_name='inputs', old_value=old_value, new_value=self._inputs[:] ) self._notify(notification=notification) for o in self.outputs: o.invalidate() return plug def remove_plug(self, plug: 'Plug') -> None: self._operator.remove_plug(operator_instance=self, plug=plug) @property def operator(self) -> Operator: return self._operator @property def description(self) -> str: return self._description @description.setter def description(self, value: str) -> None: if self._description is value: return notification = ChangeNotification( item=self, property_name='description', old_value=self._description, new_value=value ) self._description = value self._notify(notification=notification) @DagNode.can_add_input.getter def can_add_input(self) -> bool: if self._operator.max_inputs == -1: return True return len(self._inputs) < self._operator.max_inputs - 1 class StyleInfo(object): def __init__( self, name: str, background_color: int, border_color: int, connection_color: int, node_background_color: int, footer_icon_filename: str, ): super(StyleInfo, self).__init__() self._name: str = name self._background_color: int = background_color self._border_color: int = border_color self._connection_color: int = connection_color self._node_background_color: int = node_background_color self._footer_icon_filename: str = footer_icon_filename @property def name(self) -> str: return self._name @property def background_color(self) -> int: return self._background_color @property def border_color(self) -> int: return self._border_color @property def connection_color(self) -> int: return self._connection_color @property def node_background_color(self) -> int: return self._node_background_color @property def footer_icon_filename(self) -> str: return self._footer_icon_filename class ConversionGraph(Base): # STYLE_OUTPUT: StyleInfo = StyleInfo( # name='output', # background_color=0xFF2E2E2E, # border_color=0xFFB97E9C, # connection_color=0xFF80C26F, # node_background_color=0xFF444444, # footer_icon_filename='Material.svg' # ) STYLE_SOURCE_NODE: StyleInfo = StyleInfo( name='source_node', background_color=0xFF2E2E2E, border_color=0xFFE5AAC8, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='Material.svg' ) STYLE_ASSEMBLY_REFERENCE: StyleInfo = StyleInfo( name='assembly_reference', background_color=0xFF2E2E2E, border_color=0xFFB97E9C, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='Material.svg' ) STYLE_OPERATOR_INSTANCE: StyleInfo = StyleInfo( name='operator_instance', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_color.svg' ) STYLE_VALUE_RESOLVER: StyleInfo = StyleInfo( name='value_resolver', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='value_resolver.svg' ) STYLE_BOOLEAN_SWITCH: StyleInfo = StyleInfo( name='boolean_switch', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='boolean_switch.svg' ) STYLE_CONSTANT_BOOLEAN: StyleInfo = StyleInfo( name='constant_boolean', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_boolean.svg' ) STYLE_CONSTANT_COLOR: StyleInfo = StyleInfo( name='constant_color', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_color.svg' ) STYLE_CONSTANT_FLOAT: StyleInfo = StyleInfo( name='constant_float', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_float.svg' ) STYLE_CONSTANT_INTEGER: StyleInfo = StyleInfo( name='constant_integer', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_integer.svg' ) STYLE_CONSTANT_STRING: StyleInfo = StyleInfo( name='constant_string', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_string.svg' ) STYLE_EQUAL: StyleInfo = StyleInfo( name='equal', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='equal.svg' ) STYLE_GREATER_THAN: StyleInfo = StyleInfo( name='greater_than', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='greater_than.svg' ) STYLE_LESS_THAN: StyleInfo = StyleInfo( name='less_than', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='less_than.svg' ) STYLE_MERGE_RGB: StyleInfo = StyleInfo( name='merge_rgb', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='merge_rgb.svg' ) STYLE_NOT: StyleInfo = StyleInfo( name='not', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='not.svg' ) STYLE_OR: StyleInfo = StyleInfo( name='or', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='or.svg' ) STYLE_SPLIT_RGB: StyleInfo = StyleInfo( name='split_rgb', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='split_rgb.svg' ) STYLE_TRANSPARENCY_RESOLVER: StyleInfo = StyleInfo( name='transparency_resolver', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='transparency_resolver.svg' ) STYLE_OUTPUT: StyleInfo = StyleInfo( name='output', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='output.svg' ) STYLE_INFOS = ( STYLE_OUTPUT, STYLE_SOURCE_NODE, STYLE_ASSEMBLY_REFERENCE, STYLE_OPERATOR_INSTANCE, STYLE_VALUE_RESOLVER, STYLE_BOOLEAN_SWITCH, STYLE_CONSTANT_BOOLEAN, STYLE_CONSTANT_COLOR, STYLE_CONSTANT_FLOAT, STYLE_CONSTANT_INTEGER, STYLE_CONSTANT_STRING, STYLE_EQUAL, STYLE_GREATER_THAN, STYLE_LESS_THAN, STYLE_NOT, STYLE_OR, STYLE_SPLIT_RGB, STYLE_TRANSPARENCY_RESOLVER, STYLE_MERGE_RGB, ) def __init__(self): super(ConversionGraph, self).__init__() self._graph_output: OperatorInstance = OperatorInstance.FromOperator(operator=GraphOutput()) self._target_instances: typing.List[TargetInstance] = [] self._operator_instances: typing.List[OperatorInstance] = [self._graph_output] self._connections: typing.List[Connection] = [] self._library: Library = None self._source_node_id: str = '' self._source_node: TargetInstance = None self._filename: str = '' self._exists_on_disk: bool = False self._revision: int = 0 def _on_notification(self, notification: ChangeNotification) -> None: if notification.item == self: return # Re-broadcast notification self._notify(notification=notification) def serialize(self) -> dict: output = super(ConversionGraph, self).serialize() output['_target_instances'] = [o.serialize() for o in self._target_instances] output['_operator_instances'] = [o.serialize() for o in self._operator_instances] output['_connections'] = [o.serialize() for o in self._connections] output['_source_node_id'] = self._source_node_id output['_revision'] = self._revision return output def deserialize(self, data: dict) -> None: super(ConversionGraph, self).deserialize(data=data) notifications = [] # _source_node_id old = self._source_node_id new = data['_source_node_id'] if '_source_node_id' in data.keys() else '' if not old == new: self._source_node_id = new notifications.append( ChangeNotification( item=self, property_name='source_node_id', old_value=old, new_value=new ) ) # _revision old = self._revision new = data['_revision'] if '_revision' in data.keys() else 0 if not old == new: self._revision = new notifications.append( ChangeNotification( item=self, property_name='revision', old_value=old, new_value=new ) ) # _target_instances old = self._target_instances[:] while len(self._target_instances): self._unsubscribe(notifying=self._target_instances.pop()) items = [] if '_target_instances' in data.keys(): for o in data['_target_instances']: item = TargetInstance() item.deserialize(data=o) items.append(item) self._target_instances = items if not self._target_instances == old: notifications.append( ChangeNotification( item=self, property_name='target_instances', old_value=old, new_value=self._target_instances ) ) # _source_node old = self._source_node source_node = None if self._source_node_id: items = [o for o in self._target_instances if o.id == self._source_node_id] source_node = items[0] if len(items) else None self._source_node = source_node if not self._source_node == old: notifications.append( ChangeNotification( item=self, property_name='source_node', old_value=old, new_value=self._source_node ) ) # _operator_instances # _graph_output old_operator_instances = self._operator_instances old_graph_output = self._graph_output items = [] self._graph_output = None if '_operator_instances' in data.keys(): for o in data['_operator_instances']: item = OperatorInstance() item.deserialize(data=o) items.append(item) if isinstance(item.operator, GraphOutput): self._graph_output = item if not self._graph_output: self._graph_output = OperatorInstance.FromOperator(operator=GraphOutput()) items.insert(0, self._graph_output) self._operator_instances = items if not self._operator_instances == old_operator_instances: notifications.append( ChangeNotification( item=self, property_name='operator_instances', old_value=old_operator_instances, new_value=self._operator_instances ) ) if not self._graph_output == old_graph_output: notifications.append( ChangeNotification( item=self, property_name='old_graph_output', old_value=old_operator_instances, new_value=self._graph_output ) ) items = [] if '_connections' in data.keys(): for o in data['_connections']: item = Connection() item.deserialize(data=o) items.append(item) self._connections = items for o in self._target_instances: self._subscribe(notifying=o) for o in self._operator_instances: self._subscribe(notifying=o) for o in notifications: self._notify(notification=o) def build_dag(self) -> None: for connection in self._connections: source = self._get_plug(plug_id=connection.source_id) destination = self._get_plug(plug_id=connection.destination_id) if not source or not destination: continue if destination not in source.outputs: source.outputs.append(destination) destination.input = source def _get_plug(self, plug_id: str) -> typing.Union[Plug, typing.NoReturn]: for assembly_reference in self._target_instances: for plug in assembly_reference.inputs: if plug.id == plug_id: return plug for plug in assembly_reference.outputs: if plug.id == plug_id: return plug for operator_instance in self._operator_instances: for plug in operator_instance.outputs: if plug.id == plug_id: return plug for plug in operator_instance.inputs: if plug.id == plug_id: return plug return None def add_node(self, node: OperatorInstance) -> None: self._operator_instances.append(node) def add_connection(self, source: Plug, destination: Plug) -> None: connection = Connection() connection._source_id = source.id connection._destination_id = destination.id self._connections.append(connection) if destination not in source.outputs: source.outputs.append(destination) destination.input = source def add(self, entity: GraphEntity) -> None: if isinstance(entity, TargetInstance): if entity in self._target_instances: return self._target_instances.append(entity) self._subscribe(notifying=entity) return if isinstance(entity, OperatorInstance): if entity in self._operator_instances: return self._operator_instances.append(entity) self._subscribe(notifying=entity) return raise NotImplementedError() def can_be_removed(self, entity: GraphEntity) -> bool: if not entity: return False if entity not in self._target_instances and entity not in self._operator_instances: return False if entity == self._graph_output: return False return True def remove(self, entity: GraphEntity) -> None: if not self.can_be_removed(entity=entity): raise Exception('Not allowed: entity is not allowed to be deleted.') if isinstance(entity, TargetInstance): if entity in self._target_instances: self._unsubscribe(notifying=entity) self._target_instances.remove(entity) to_remove = [] for connection in self._connections: if connection.source_id == entity.id or connection.destination_id == entity.id: to_remove.append(connection) for connection in to_remove: self.remove_connection(connection=connection) return if isinstance(entity, OperatorInstance): if entity in self._operator_instances: self._unsubscribe(notifying=entity) self._operator_instances.remove(entity) to_remove = [] for connection in self._connections: if connection.source_id == entity.id or connection.destination_id == entity.id: to_remove.append(connection) for connection in to_remove: self.remove_connection(connection=connection) return raise NotImplementedError() def remove_connection(self, connection: Connection) -> None: if connection in self._connections: self._connections.remove(connection) source = self._get_plug(plug_id=connection.source_id) destination = self._get_plug(plug_id=connection.destination_id) if source and destination: if destination in source.outputs: source.outputs.remove(destination) if destination.input == source: destination.input = None def get_entity_by_id(self, identifier: str) -> typing.Union[GraphEntity, typing.NoReturn]: entities = [entity for entity in self._target_instances if entity.id == identifier] if len(entities): return entities[0] entities = [entity for entity in self._operator_instances if entity.id == identifier] if len(entities): return entities[0] return None def get_output_entity(self) -> typing.Union[TargetInstance, typing.NoReturn]: """ Computes the dependency graph and returns the resulting Target reference. Make sure relevant source node plug values have been set prior to invoking this method. """ if not self._graph_output: return None self._graph_output.invalidate() assembly_id = self._graph_output.outputs[0].computed_value for item in self._target_instances: if item.target_id == assembly_id: return item return None def get_object_style_name(self, entity: GraphEntity) -> str: if not entity: return '' # TODO: Style computed output entity # if entity == self.get_output_entity(): # return ConversionGraph.STYLE_OUTPUT.name if entity == self.source_node: return ConversionGraph.STYLE_SOURCE_NODE.name if isinstance(entity, TargetInstance): return ConversionGraph.STYLE_ASSEMBLY_REFERENCE.name if isinstance(entity, OperatorInstance): if entity.operator: if entity.operator.__class__.__name__ == 'ConstantBoolean': return ConversionGraph.STYLE_CONSTANT_BOOLEAN.name if entity.operator.__class__.__name__ == 'ConstantColor': return ConversionGraph.STYLE_CONSTANT_COLOR.name if entity.operator.__class__.__name__ == 'ConstantFloat': return ConversionGraph.STYLE_CONSTANT_FLOAT.name if entity.operator.__class__.__name__ == 'ConstantInteger': return ConversionGraph.STYLE_CONSTANT_INTEGER.name if entity.operator.__class__.__name__ == 'ConstantString': return ConversionGraph.STYLE_CONSTANT_STRING.name if entity.operator.__class__.__name__ == 'BooleanSwitch': return ConversionGraph.STYLE_BOOLEAN_SWITCH.name if entity.operator.__class__.__name__ == 'ValueResolver': return ConversionGraph.STYLE_VALUE_RESOLVER.name if entity.operator.__class__.__name__ == 'SplitRGB': return ConversionGraph.STYLE_SPLIT_RGB.name if entity.operator.__class__.__name__ == 'MergeRGB': return ConversionGraph.STYLE_MERGE_RGB.name if entity.operator.__class__.__name__ == 'LessThan': return ConversionGraph.STYLE_LESS_THAN.name if entity.operator.__class__.__name__ == 'GreaterThan': return ConversionGraph.STYLE_GREATER_THAN.name if entity.operator.__class__.__name__ == 'Or': return ConversionGraph.STYLE_OR.name if entity.operator.__class__.__name__ == 'Equal': return ConversionGraph.STYLE_EQUAL.name if entity.operator.__class__.__name__ == 'Not': return ConversionGraph.STYLE_NOT.name if entity.operator.__class__.__name__ == 'MayaTransparencyResolver': return ConversionGraph.STYLE_TRANSPARENCY_RESOLVER.name if entity.operator.__class__.__name__ == 'GraphOutput': return ConversionGraph.STYLE_OUTPUT.name return ConversionGraph.STYLE_OPERATOR_INSTANCE.name return '' def get_output_targets(self) -> typing.List[TargetInstance]: return [o for o in self._target_instances if not o == self._source_node] @property def target_instances(self) -> typing.List[TargetInstance]: return self._target_instances[:] @property def operator_instances(self) -> typing.List[OperatorInstance]: return self._operator_instances[:] @property def connections(self) -> typing.List[Connection]: return self._connections[:] @property def filename(self) -> str: return self._filename @filename.setter def filename(self, value: str) -> None: if self._filename is value: return notification = ChangeNotification( item=self, property_name='filename', old_value=self._filename, new_value=value ) self._filename = value self._notify(notification=notification) @property def library(self) -> 'Library': return self._library @property def graph_output(self) -> OperatorInstance: return self._graph_output @property def source_node(self) -> TargetInstance: return self._source_node @source_node.setter def source_node(self, value: TargetInstance) -> None: if self._source_node is value: return node_notification = ChangeNotification( item=self, property_name='source_node', old_value=self._source_node, new_value=value ) node_id_notification = ChangeNotification( item=self, property_name='source_node_id', old_value=self._source_node_id, new_value=value.id if value else '' ) self._source_node = value self._source_node_id = self._source_node.id if self._source_node else '' self._notify(notification=node_notification) self._notify(notification=node_id_notification) @property def exists_on_disk(self) -> bool: return self._exists_on_disk @property def revision(self) -> int: return self._revision @revision.setter def revision(self, value: int) -> None: if self._revision is value: return notification = ChangeNotification( item=self, property_name='revision', old_value=self._revision, new_value=value ) self._revision = value self._notify(notification=notification) class FileHeader(Serializable): @classmethod def FromInstance(cls, instance: Serializable) -> 'FileHeader': header = cls() header._module = instance.__class__.__module__ header._class_name = instance.__class__.__name__ return header @classmethod def FromData(cls, data: dict) -> 'FileHeader': if '_module' not in data.keys(): raise Exception('Unexpected data: key "_module" not in dictionary') if '_class_name' not in data.keys(): raise Exception('Unexpected data: key "_class_name" not in dictionary') header = cls() header._module = data['_module'] header._class_name = data['_class_name'] return header def __init__(self): super(FileHeader, self).__init__() self._module = '' self._class_name = '' def serialize(self) -> dict: output = dict() output['_module'] = self._module output['_class_name'] = self._class_name return output @property def module(self) -> str: return self._module @property def class_name(self) -> str: return self._class_name class FileUtility(Serializable): @classmethod def FromInstance(cls, instance: Serializable) -> 'FileUtility': utility = cls() utility._header = FileHeader.FromInstance(instance=instance) utility._content = instance return utility @classmethod def FromData(cls, data: dict) -> 'FileUtility': if '_header' not in data.keys(): raise Exception('Unexpected data: key "_header" not in dictionary') if '_content' not in data.keys(): raise Exception('Unexpected data: key "_content" not in dictionary') utility = cls() utility._header = FileHeader.FromData(data=data['_header']) if utility._header.module not in sys.modules.keys(): importlib.import_module(utility._header.module) module_pointer = sys.modules[utility._header.module] class_pointer = module_pointer.__dict__[utility._header.class_name] utility._content = class_pointer() if isinstance(utility._content, Serializable): utility._content.deserialize(data=data['_content']) return utility def __init__(self): super(FileUtility, self).__init__() self._header: FileHeader = None self._content: Serializable = None def serialize(self) -> dict: output = dict() output['_header'] = self._header.serialize() output['_content'] = self._content.serialize() return output def assert_content_serializable(self): data = self.content.serialize() self._assert(data=data) def _assert(self, data: dict): for key, value in data.items(): if isinstance(value, dict): self._assert(data=value) elif isinstance(value, list): for item in value: if isinstance(item, dict): self._assert(data=item) else: print(item) else: print(key, value) @property def header(self) -> FileHeader: return self._header @property def content(self) -> Serializable: return self._content class Library(Base): """ A Library represents a UMM data set. It can contain any of the following types of files: - Settings - Conversion Graph - Target - Conversion Manifest A Library is divided into a "core" and a "user" data set. "core": - Files provided by NVIDIA. - Installed and updated by UMM. - Adding, editing, and deleting files require running in "Developer Mode". - Types: - Conversion Graph - Target - Conversion Manifest "user" - Files created and updated by user. - Types: - Conversion Graph - Target - Conversion Manifest Overrides ./core/Conversion Manifest ...or... each file header has an attribute: source = core, source = user if source == core then it is read-only to users. TARGET: problem with that is what if user needs to update an existing target? ...why would they? ...because they may want to edit property states in the Target... would want their own. CONVERSION GRAPH ...they could just Save As and make a different one. no problem here. do need to change the 'source' attribute to 'user' though. CONVERSION MANIFEST 2 files ConversionManifest.json ConversionManifest_user.json (overrides ConversionManifest.json) Limitation: User cannot all together remove a manifest item """ @classmethod def Create( cls, library_id: str, name: str, manifest: IDelegate = None, conversion_graph: IDelegate = None, target: IDelegate = None, settings: IDelegate = None ) -> 'Library': instance = typing.cast(Library, super(Library, cls).Create()) instance._id = library_id instance._name = name instance._manifest = manifest instance._conversion_graph = conversion_graph instance._target = target instance._settings = settings return instance def __init__(self): super(Library, self).__init__() self._name: str = '' self._manifest: typing.Union[IDelegate, typing.NoReturn] = None self._conversion_graph: typing.Union[IDelegate, typing.NoReturn] = None self._target: typing.Union[IDelegate, typing.NoReturn] = None self._settings: typing.Union[IDelegate, typing.NoReturn] = None def serialize(self) -> dict: output = super(Library, self).serialize() output['_name'] = self._name return output def deserialize(self, data: dict) -> None: super(Library, self).deserialize(data=data) self._name = data['_name'] if '_name' in data.keys() else '' @property def name(self) -> str: return self._name @name.setter def name(self, value: str) -> None: self._name = value @property def manifest(self) -> typing.Union[IDelegate, typing.NoReturn]: return self._manifest @property def conversion_graph(self) -> typing.Union[IDelegate, typing.NoReturn]: return self._conversion_graph @property def target(self) -> typing.Union[IDelegate, typing.NoReturn]: return self._target @property def settings(self) -> typing.Union[IDelegate, typing.NoReturn]: return self._settings @property def is_read_only(self) -> bool: return not self._conversion_graph or not self._target or not self._conversion_graph class Settings(Serializable): def __init__(self): super(Settings, self).__init__() self._libraries: typing.List[Library] = [] self._store_id = 'Settings.json' self._render_contexts: typing.List[str] = [] def serialize(self) -> dict: output = super(Settings, self).serialize() output['_libraries'] = [o.serialize() for o in self._libraries] output['_render_contexts'] = self._render_contexts return output def deserialize(self, data: dict) -> None: super(Settings, self).deserialize(data=data) items = [] if '_libraries' in data.keys(): for o in data['_libraries']: item = Library() item.deserialize(data=o) items.append(item) self._libraries = items self._render_contexts = data['_render_contexts'] if '_render_contexts' in data.keys() else [] @property def libraries(self) -> typing.List[Library]: return self._libraries @property def store_id(self) -> str: return self._store_id @property def render_contexts(self) -> typing.List[str]: return self._render_contexts class ClassInfo(object): def __init__(self, display_name: str, class_name: str): super(ClassInfo, self).__init__() self._display_name = display_name self._class_name = class_name @property def display_name(self) -> str: return self._display_name @property def class_name(self) -> str: return self._class_name class OmniMDL(object): OMNI_GLASS: ClassInfo = ClassInfo(display_name='Omni Glass', class_name='OmniGlass.mdl|OmniGlass') OMNI_GLASS_OPACITY: ClassInfo = ClassInfo(display_name='Omni Glass Opacity', class_name='OmniGlass_Opacity.mdl|OmniGlass_Opacity') OMNI_PBR: ClassInfo = ClassInfo(display_name='Omni PBR', class_name='OmniPBR.mdl|OmniPBR') OMNI_PBR_CLEAR_COAT: ClassInfo = ClassInfo(display_name='Omni PBR Clear Coat', class_name='OmniPBR_ClearCoat.mdl|OmniPBR_ClearCoat') OMNI_PBR_CLEAR_COAT_OPACITY: ClassInfo = ClassInfo(display_name='Omni PBR Clear Coat Opacity', class_name='OmniPBR_ClearCoat_Opacity.mdl|OmniPBR_ClearCoat_Opacity') OMNI_PBR_OPACITY = ClassInfo(display_name='Omni PBR Opacity', class_name='OmniPBR_Opacity.mdl|OmniPBR_Opacity') OMNI_SURFACE: ClassInfo = ClassInfo(display_name='OmniSurface', class_name='OmniSurface.mdl|OmniSurface') OMNI_SURFACE_LITE: ClassInfo = ClassInfo(display_name='OmniSurfaceLite', class_name='OmniSurfaceLite.mdl|OmniSurfaceLite') OMNI_SURFACE_UBER: ClassInfo = ClassInfo(display_name='OmniSurfaceUber', class_name='OmniSurfaceUber.mdl|OmniSurfaceUber') class MayaShader(object): LAMBERT: ClassInfo = ClassInfo(display_name='Lambert', class_name='lambert') class ConversionMap(Serializable): @classmethod def Create( cls, render_context: str, application: str, document: ConversionGraph, ) -> 'ConversionMap': if not isinstance(document, ConversionGraph): raise Exception('Argument "document" unexpected class: "{0}"'.format(type(document))) instance = cls() instance._render_context = render_context instance._application = application instance._conversion_graph_id = document.id instance._conversion_graph = document return instance def __init__(self): super(ConversionMap, self).__init__() self._render_context: str = '' self._application: str = '' self._conversion_graph_id: str = '' self._conversion_graph: ConversionGraph = None def __eq__(self, other: 'ConversionMap') -> bool: if not isinstance(other, ConversionMap): return False if not self.render_context == other.render_context: return False if not self.application == other.application: return False if not self.conversion_graph_id == other.conversion_graph_id: return False return True def serialize(self) -> dict: output = super(ConversionMap, self).serialize() output['_render_context'] = self._render_context output['_application'] = self._application output['_conversion_graph_id'] = self._conversion_graph_id return output def deserialize(self, data: dict) -> None: super(ConversionMap, self).deserialize(data=data) self._render_context = data['_render_context'] if '_render_context' in data.keys() else '' self._application = data['_application'] if '_application' in data.keys() else '' self._conversion_graph_id = data['_conversion_graph_id'] if '_conversion_graph_id' in data.keys() else '' self._conversion_graph = None @property def render_context(self) -> str: return self._render_context @property def application(self) -> str: return self._application @property def conversion_graph_id(self) -> str: return self._conversion_graph_id @property def conversion_graph(self) -> ConversionGraph: return self._conversion_graph class ConversionManifest(Serializable): def __init__(self): super(ConversionManifest, self).__init__() self._version_major: int = 100 self._version_minor: int = 0 self._conversion_maps: typing.List[ConversionMap] = [] self._store_id = 'ConversionManifest.json' def serialize(self) -> dict: output = super(ConversionManifest, self).serialize() output['_version_major'] = self._version_major output['_version_minor'] = self._version_minor output['_conversion_maps'] = [o.serialize() for o in self._conversion_maps] return output def deserialize(self, data: dict) -> None: super(ConversionManifest, self).deserialize(data=data) self._version_major = data['_version_major'] if '_version_major' in data.keys() else 100 self._version_minor = data['_version_minor'] if '_version_minor' in data.keys() else 0 items = [] if '_conversion_maps' in data.keys(): for o in data['_conversion_maps']: item = ConversionMap() item.deserialize(data=o) items.append(item) self._conversion_maps = items def set_version(self, major: int = 100, minor: int = 0) -> None: self._version_major = major self._version_minor = minor def add( self, render_context: str, application: str, document: ConversionGraph, ) -> ConversionMap: item = ConversionMap.Create( render_context=render_context, application=application, document=document, ) self._conversion_maps.append(item) return item def remove(self, item: ConversionMap) -> None: if item in self._conversion_maps: self._conversion_maps.remove(item) @property def conversion_maps(self) -> typing.List[ConversionMap]: return self._conversion_maps[:] @property def version(self) -> str: return '{0}.{1}'.format(self._version_major, self._version_minor) @property def version_major(self) -> int: return self._version_major @property def version_minor(self) -> int: return self._version_minor @property def store_id(self) -> str: return self._store_id
100,965
Python
32.949563
187
0.58241
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/feature.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. VIEWPORT: bool = False """ BROWSE_FOR_LIBRARY - add ability to browse for a UMM library. - includes creating a new one. Without this features it is up to Connectors to create and register libraries on install. """ BROWSE_FOR_LIBRARY: bool = False POLLING: bool = False COPY: bool = True
1,155
Python
32.028571
89
0.730736
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/operator.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import sys import typing from .data import Operator, Plug, DagNode, OperatorInstance from . import util class ConstantFloat(Operator): def __init__(self): super(ConstantFloat, self).__init__( id='293c38db-c9b3-4b37-ab02-c4ff6052bcb6', name='Constant Float', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else 0.0 def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Float', value_type=Plug.VALUE_TYPE_FLOAT, editable=True ) plug.value = 0.0 return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = len(self.id) * 0.3 def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == len(self.id) * 0.3: raise Exception('Test failed.') class ConstantInteger(Operator): def __init__(self): super(ConstantInteger, self).__init__( id='293c38db-c9b3-4b37-ab02-c4ff6052bcb7', name='Constant Integer', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else 0 def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Integer', value_type=Plug.VALUE_TYPE_INTEGER, editable=True ) plug.value = 0 return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = len(self.id) def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == len(self.id): raise Exception('Test failed.') class ConstantBoolean(Operator): def __init__(self): super(ConstantBoolean, self).__init__( id='293c38db-c9b3-4b37-ab02-c4ff6052bcb8', name='Constant Boolean', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else False def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN, editable=True ) plug.value = True return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = False def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if output.computed_value: raise Exception('Test failed.') class ConstantString(Operator): def __init__(self): super(ConstantString, self).__init__( id='cb169ec0-5ddb-45eb-98d1-5d09f1ca759g', name='Constant String', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else '' # print('ConstantString._compute_outputs(): output_plugs[0].computed_value', output_plugs[0].computed_value) def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='String', value_type=Plug.VALUE_TYPE_STRING, editable=True ) plug.value = '' plug.default_value = '' return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = self.id def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == self.id: raise Exception('Test failed.') class ConstantRGB(Operator): def __init__(self): super(ConstantRGB, self).__init__( id='60f21797-dd62-4b06-9721-53882aa42e81', name='Constant RGB', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else (0, 0, 0) def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Color', value_type=Plug.VALUE_TYPE_VECTOR3, editable=True ) plug.value = (0, 0, 0) return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = (0.1, 0.2, 0.3) def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == (0.1, 0.2, 0.3): raise Exception('Test failed.') class ConstantRGBA(Operator): def __init__(self): super(ConstantRGBA, self).__init__( id='0ab39d82-5862-4332-af7a-329200ae1d14', name='Constant RGBA', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else (0, 0, 0, 0) def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Color', value_type=Plug.VALUE_TYPE_VECTOR4, editable=True ) plug.value = (0, 0, 0, 1) return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = (0.1, 0.2, 0.3, 0.4) def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == (0.1, 0.2, 0.3, 0.4): raise Exception('Test failed.') class BooleanSwitch(Operator): """ Outputs the value of input 2 if input 1 is TRUE. Otherwise input 3 will be output. Input 1 must be a boolean. Input 2 and 3 can be of any value type. """ def __init__(self): super(BooleanSwitch, self).__init__( id='a628ab13-f19f-45b3-81cf-6824dd6e7b5d', name='Boolean Switch', required_inputs=3, min_inputs=3, max_inputs=3, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): debug = False value = None if debug: print('BooleanSwitch') print('\tinput_plugs[0].input:', input_plugs[0].input) if input_plugs[0].input is not None: if debug: print('\tinput_plugs[0].input.computed_value:', input_plugs[0].input.computed_value) print('\tinput_plugs[1].input:', input_plugs[1].input) if input_plugs[1].input is not None: print('\tinput_plugs[1].input.computed_value:', input_plugs[1].input.computed_value) print('\tinput_plugs[2].input:', input_plugs[2].input) if input_plugs[2].input is not None: print('\tinput_plugs[2].input.computed_value:', input_plugs[2].input.computed_value) if input_plugs[0].input.computed_value: value = input_plugs[1].input.computed_value if input_plugs[1].input is not None else False else: value = input_plugs[2].input.computed_value if input_plugs[2].input is not None else False elif debug: print('\tskipping evaluating inputs') if debug: print('\tvalue:', value) print('\toutput_plugs[0].computed_value is value', output_plugs[0].computed_value is value) output_plugs[0].computed_value = value if value is not None else False def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='input_boolean', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN) plug.value = False return plug if index == 1: return Plug.Create(parent=parent, name='on_true', display_name='True Output', value_type=Plug.VALUE_TYPE_ANY) if index == 2: return Plug.Create(parent=parent, name='on_false', display_name='False Output', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='output', display_name='Output', value_type=Plug.VALUE_TYPE_ANY) plug.value = False return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = True input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantString()) fake.outputs[0].value = 'Input 1 value' input_plugs[1].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantString()) fake.outputs[0].value = 'Input 2 value' input_plugs[2].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == 'Input 1 value': raise Exception('Test failed.') class SplitRGB(Operator): def __init__(self): super(SplitRGB, self).__init__( id='1cbcf8c6-328c-49b6-b4fc-d16fd78d4868', name='Split RGB', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=3 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None: output_plugs[0].computed_value = 0 output_plugs[1].computed_value = 0 output_plugs[2].computed_value = 0 else: value = input_plugs[0].input.computed_value try: test = iter(value) is_iterable = True except TypeError: is_iterable = False if is_iterable and len(value) == 3: output_plugs[0].computed_value = value[0] output_plugs[1].computed_value = value[1] output_plugs[2].computed_value = value[2] else: output_plugs[0].computed_value = output_plugs[0].default_value output_plugs[1].computed_value = output_plugs[1].default_value output_plugs[2].computed_value = output_plugs[2].default_value def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_rgb', display_name='RGB', value_type=Plug.VALUE_TYPE_VECTOR3) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='red', display_name='Red', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 1: plug = Plug.Create( parent=parent, name='green', display_name='Green', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 2: plug = Plug.Create( parent=parent, name='blue', display_name='Blue', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantRGB()) fake.outputs[0].value = (0.1, 0.2, 0.3) input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 0.1: raise Exception('Test failed.') if not output_plugs[1].computed_value == 0.2: raise Exception('Test failed.') if not output_plugs[2].computed_value == 0.3: raise Exception('Test failed.') class MergeRGB(Operator): def __init__(self): super(MergeRGB, self).__init__( id='1cbcf8c6-328d-49b6-b4fc-d16fd78d4868', name='Merge RGB', required_inputs=3, min_inputs=3, max_inputs=3, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): rgb = [0.0, 0.0, 0.0] for i in range(3): if input_plugs[i].input is not None: assumed_value_type = input_plugs[i].input.value_type if util.to_plug_value_type(value=input_plugs[i].input.computed_value, assumed_value_type=assumed_value_type) == Plug.VALUE_TYPE_FLOAT: rgb[i] = input_plugs[i].input.computed_value output_plugs[0].computed_value = tuple(rgb) def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_r', display_name='R', value_type=Plug.VALUE_TYPE_FLOAT) if index == 1: return Plug.Create(parent=parent, name='input_g', display_name='G', value_type=Plug.VALUE_TYPE_FLOAT) if index == 2: return Plug.Create(parent=parent, name='input_B', display_name='B', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='rgb', display_name='RGB', value_type=Plug.VALUE_TYPE_VECTOR3, editable=False ) plug.value = (0, 0, 0) return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.1 input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.2 input_plugs[1].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.3 input_plugs[2].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == (0.1, 0.2, 0.3): raise Exception('Test failed.') class SplitRGBA(Operator): def __init__(self): super(SplitRGBA, self).__init__( id='2c48e13c-2b58-48b9-a3b6-5f977c402b2e', name='Split RGBA', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=4 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None: output_plugs[0].computed_value = 0 output_plugs[1].computed_value = 0 output_plugs[2].computed_value = 0 output_plugs[3].computed_value = 0 return value = input_plugs[0].input.computed_value try: test = iter(value) is_iterable = True except TypeError: is_iterable = False if is_iterable and len(value) == 4: output_plugs[0].computed_value = value[0] output_plugs[1].computed_value = value[1] output_plugs[2].computed_value = value[2] output_plugs[3].computed_value = value[3] else: output_plugs[0].computed_value = output_plugs[0].default_value output_plugs[1].computed_value = output_plugs[1].default_value output_plugs[2].computed_value = output_plugs[2].default_value output_plugs[3].computed_value = output_plugs[3].default_value def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_rgba', display_name='RGBA', value_type=Plug.VALUE_TYPE_VECTOR4) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='red', display_name='Red', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 1: plug = Plug.Create( parent=parent, name='green', display_name='Green', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 2: plug = Plug.Create( parent=parent, name='blue', display_name='Blue', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 3: plug = Plug.Create( parent=parent, name='alpha', display_name='Alpha', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantRGB()) fake.outputs[0].value = (0.1, 0.2, 0.3, 0.4) input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 0.1: raise Exception('Test failed.') if not output_plugs[1].computed_value == 0.2: raise Exception('Test failed.') if not output_plugs[2].computed_value == 0.3: raise Exception('Test failed.') if not output_plugs[3].computed_value == 0.4: raise Exception('Test failed.') class MergeRGBA(Operator): def __init__(self): super(MergeRGBA, self).__init__( id='92e57f3d-8514-4786-a4ed-2767139a15eb', name='Merge RGBA', required_inputs=4, min_inputs=4, max_inputs=4, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): rgba = [0.0, 0.0, 0.0, 0.0] for i in range(4): if input_plugs[i].input is not None: assumed_value_type = input_plugs[i].input.value_type if util.to_plug_value_type(value=input_plugs[i].input.computed_value, assumed_value_type=assumed_value_type) == Plug.VALUE_TYPE_FLOAT: rgba[i] = input_plugs[i].input.computed_value output_plugs[0].computed_value = tuple(rgba) def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_r', display_name='R', value_type=Plug.VALUE_TYPE_FLOAT) if index == 1: return Plug.Create(parent=parent, name='input_g', display_name='G', value_type=Plug.VALUE_TYPE_FLOAT) if index == 2: return Plug.Create(parent=parent, name='input_b', display_name='B', value_type=Plug.VALUE_TYPE_FLOAT) if index == 3: return Plug.Create(parent=parent, name='input_a', display_name='A', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='rgba', display_name='RGBA', value_type=Plug.VALUE_TYPE_VECTOR3, editable=False ) plug.value = (0, 0, 0, 0) return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.1 input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.2 input_plugs[1].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.3 input_plugs[2].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.4 input_plugs[3].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == (0.1, 0.2, 0.3, 0.4): raise Exception('Test failed.') class LessThan(Operator): def __init__(self): super(LessThan, self).__init__( id='996df9bd-08d5-451b-a67c-80d0de7fba32', name='Less Than', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None or input_plugs[1].input is None: for output in output_plugs: output.computed_value = False return value = input_plugs[0].input.computed_value compare = input_plugs[1].input.computed_value result = False try: result = value < compare except Exception as error: print('WARNING: Universal Material Map: ' 'unable to compare if "{0}" is less than "{1}". ' 'Setting output to "{2}".'.format( value, compare, result )) output_plugs[0].computed_value = result def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value', display_name='Value', value_type=Plug.VALUE_TYPE_FLOAT) if index == 1: return Plug.Create(parent=parent, name='comparison', display_name='Comparison', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Is Less Than', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.1 input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.2 input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class GreaterThan(Operator): def __init__(self): super(GreaterThan, self).__init__( id='1e751c3a-f6cd-43a2-aa72-22cb9d82ad19', name='Greater Than', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None or input_plugs[1].input is None: output_plugs[0].computed_value = False return value = input_plugs[0].input.computed_value compare = input_plugs[1].input.computed_value result = False try: result = value > compare except Exception as error: print('WARNING: Universal Material Map: ' 'unable to compare if "{0}" is greater than "{1}". ' 'Setting output to "{2}".'.format( value, compare, result )) output_plugs[0].computed_value = result def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value', display_name='Value', value_type=Plug.VALUE_TYPE_FLOAT) if index == 1: return Plug.Create(parent=parent, name='comparison', display_name='Comparison', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Is Greater Than', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.1 input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.2 input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if output_plugs[0].computed_value: raise Exception('Test failed.') class Or(Operator): def __init__(self): super(Or, self).__init__( id='d0288faf-cb2e-4765-8923-1a368b45f62c', name='Or', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None and input_plugs[1].input is None: output_plugs[0].computed_value = False return value_1 = input_plugs[0].input.computed_value if input_plugs[0].input else False value_2 = input_plugs[1].input.computed_value if input_plugs[1].input else False if value_1 is None and value_2 is None: output_plugs[0].computed_value = False return if value_1 is None: output_plugs[0].computed_value = True if value_2 else False return if value_2 is None: output_plugs[0].computed_value = True if value_1 else False return output_plugs[0].computed_value = value_1 or value_2 def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value_1', display_name='Value 1', value_type=Plug.VALUE_TYPE_ANY) if index == 1: return Plug.Create(parent=parent, name='value_2', display_name='Value 2', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Is True', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = True input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = False input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class And(Operator): def __init__(self): super(And, self).__init__( id='9c5e4fb9-9948-4075-a7d6-ae9bc04e25b5', name='And', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None and input_plugs[1].input is None: output_plugs[0].computed_value = False return value_1 = input_plugs[0].input.computed_value if input_plugs[0].input else False value_2 = input_plugs[1].input.computed_value if input_plugs[1].input else False if value_1 is None and value_2 is None: output_plugs[0].computed_value = False return if value_1 is None: output_plugs[0].computed_value = True if value_2 else False return if value_2 is None: output_plugs[0].computed_value = True if value_1 else False return output_plugs[0].computed_value = value_1 and value_2 def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value_1', display_name='Value 1', value_type=Plug.VALUE_TYPE_ANY) if index == 1: return Plug.Create(parent=parent, name='value_2', display_name='Value 2', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Is True', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = True input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = True input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class Equal(Operator): def __init__(self): super(Equal, self).__init__( id='fb353972-aebd-4d32-8231-f644f75d322c', name='Equal', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None and input_plugs[1].input is None: output_plugs[0].computed_value = True return if input_plugs[0].input is None or input_plugs[1].input is None: output_plugs[0].computed_value = False return value_1 = input_plugs[0].input.computed_value value_2 = input_plugs[1].input.computed_value if value_1 is None and value_2 is None: output_plugs[0].computed_value = True return if value_1 is None or value_2 is None: output_plugs[0].computed_value = False return result = False try: result = value_1 == value_2 except Exception as error: print('WARNING: Universal Material Map: ' 'unable to compare if "{0}" is equal to "{1}". ' 'Setting output to "{2}".'.format( value_1, value_2, result )) output_plugs[0].computed_value = result def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value_1', display_name='Value 1', value_type=Plug.VALUE_TYPE_ANY) if index == 1: return Plug.Create(parent=parent, name='value_1', display_name='Value 2', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Are Equal', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantString()) fake.outputs[0].value = self.id input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantString()) fake.outputs[0].value = self.id input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class Not(Operator): def __init__(self): super(Not, self).__init__( id='7b8b67df-ce2e-445c-98b7-36ea695c77e3', name='Not', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None: output_plugs[0].computed_value = False return value_1 = input_plugs[0].input.computed_value if value_1 is None: output_plugs[0].computed_value = False return output_plugs[0].computed_value = not value_1 def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = False input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class ValueTest(Operator): def __init__(self): super(ValueTest, self).__init__( id='2899f66b-2e8d-467b-98d1-5f590cf98e7a', name='Value Test', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None: output_plugs[0].computed_value = None return output_plugs[0].computed_value = input_plugs[0].input.computed_value def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input', display_name='Input', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Output', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantInteger()) fake.outputs[0].value = 10 input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 10: raise Exception('Test failed.') class ValueResolver(Operator): def __init__(self): super(ValueResolver, self).__init__( id='74306cd0-b668-4a92-9e15-7b23486bd89a', name='Value Resolver', required_inputs=8, min_inputs=8, max_inputs=8, num_outputs=7 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): assumed_value_type = input_plugs[0].input.value_type if input_plugs[0].input else input_plugs[0].value_type computed_value = input_plugs[0].input.computed_value if input_plugs[0].input else False value_type = util.to_plug_value_type(value=computed_value, assumed_value_type=assumed_value_type) if value_type == Plug.VALUE_TYPE_BOOLEAN: output_plugs[0].computed_value = computed_value else: output_plugs[0].computed_value = input_plugs[1].computed_value if value_type == Plug.VALUE_TYPE_VECTOR3: output_plugs[1].computed_value = computed_value else: output_plugs[1].computed_value = input_plugs[2].computed_value if value_type == Plug.VALUE_TYPE_FLOAT: output_plugs[2].computed_value = computed_value else: output_plugs[2].computed_value = input_plugs[3].computed_value if value_type == Plug.VALUE_TYPE_INTEGER: output_plugs[3].computed_value = computed_value else: output_plugs[3].computed_value = input_plugs[4].computed_value if value_type == Plug.VALUE_TYPE_STRING: output_plugs[4].computed_value = computed_value else: output_plugs[4].computed_value = input_plugs[5].computed_value if value_type == Plug.VALUE_TYPE_VECTOR4: output_plugs[5].computed_value = computed_value else: output_plugs[5].computed_value = input_plugs[6].computed_value if value_type == Plug.VALUE_TYPE_LIST: output_plugs[6].computed_value = computed_value else: output_plugs[6].computed_value = input_plugs[7].computed_value for index, input_plug in enumerate(input_plugs): if index == 0: continue input_plug.is_editable = not input_plug.input for output_plug in output_plugs: output_plug.is_editable = False def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input', display_name='Input', value_type=Plug.VALUE_TYPE_ANY) if index == 1: plug = Plug.Create( parent=parent, name='boolean', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN, editable=True, ) plug.value = False return plug if index == 2: plug = Plug.Create( parent=parent, name='color', display_name='Color', value_type=Plug.VALUE_TYPE_VECTOR3, editable=True, ) plug.value = (0, 0, 0) return plug if index == 3: plug = Plug.Create( parent=parent, name='float', display_name='Float', value_type=Plug.VALUE_TYPE_FLOAT, editable=True, ) plug.value = 0 return plug if index == 4: plug = Plug.Create( parent=parent, name='integer', display_name='Integer', value_type=Plug.VALUE_TYPE_INTEGER, editable=True, ) plug.value = 0 return plug if index == 5: plug = Plug.Create( parent=parent, name='string', display_name='String', value_type=Plug.VALUE_TYPE_STRING, editable=True, ) plug.value = '' return plug if index == 6: plug = Plug.Create( parent=parent, name='rgba', display_name='RGBA', value_type=Plug.VALUE_TYPE_VECTOR4, editable=True, ) plug.value = (0, 0, 0, 1) return plug if index == 7: plug = Plug.Create( parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST, editable=False, ) plug.value = [] return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='boolean', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN, editable=False, ) plug.value = False return plug if index == 1: plug = Plug.Create( parent=parent, name='color', display_name='Color', value_type=Plug.VALUE_TYPE_VECTOR3, editable=False, ) plug.value = (0, 0, 0) return plug if index == 2: plug = Plug.Create( parent=parent, name='float', display_name='Float', value_type=Plug.VALUE_TYPE_FLOAT, editable=False, ) plug.value = 0 return plug if index == 3: plug = Plug.Create( parent=parent, name='integer', display_name='Integer', value_type=Plug.VALUE_TYPE_INTEGER, editable=False, ) plug.value = 0 return plug if index == 4: plug = Plug.Create( parent=parent, name='string', display_name='String', value_type=Plug.VALUE_TYPE_STRING, editable=False, ) plug.value = '' return plug if index == 5: plug = Plug.Create( parent=parent, name='rgba', display_name='RGBA', value_type=Plug.VALUE_TYPE_VECTOR4, editable=False, ) plug.value = (0, 0, 0, 1) return plug if index == 6: plug = Plug.Create( parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST, editable=False, ) plug.value = [] return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantInteger()) fake.outputs[0].value = 10 input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[3].computed_value == 10: raise Exception('Test failed.') class MayaTransparencyResolver(Operator): """ Specialty operator based on Maya transparency attribute. If the input is of type string - and is not an empty string - then the output will be TRUE. If the input is a tripple float - and any value is greater than zero - then the output will also be TRUE. In all other cases the output will be FALSE. """ def __init__(self): super(MayaTransparencyResolver, self).__init__( id='2b523832-ac84-4051-9064-6046121dcd48', name='Maya Transparency Resolver', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): is_transparent = False assumed_value_type = input_plugs[0].input.value_type if input_plugs[0].input else input_plugs[0].value_type computed_value = input_plugs[0].input.computed_value if input_plugs[0].input else False value_type = util.to_plug_value_type(value=computed_value, assumed_value_type=assumed_value_type) if value_type == Plug.VALUE_TYPE_STRING: is_transparent = not computed_value == '' elif value_type == Plug.VALUE_TYPE_VECTOR3: for value in computed_value: if value > 0: is_transparent = True break elif value_type == Plug.VALUE_TYPE_FLOAT: is_transparent = computed_value > 0 output_plugs[0].computed_value = is_transparent def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input', display_name='Input', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='is_transparent', display_name='Is Transparent', value_type=Plug.VALUE_TYPE_BOOLEAN, ) plug.value = False return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantRGB()) fake.outputs[0].value = (0.5, 0.5, 0.5) input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class ListGenerator(Operator): def __init__(self): super(ListGenerator, self).__init__( id='a410f7a0-280a-451f-a26c-faf9a8e302b4', name='List Generator', required_inputs=0, min_inputs=0, max_inputs=-1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output = [] for input_plug in input_plugs: output.append(input_plug.computed_value) output_plugs[0].computed_value = output def generate_input(self, parent: DagNode, index: int) -> Plug: return Plug.Create( parent=parent, name='[{0}]'.format(index), display_name='[{0}]'.format(index), value_type=Plug.VALUE_TYPE_ANY, editable=False, is_removable=True, ) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='list', display_name='list', value_type=Plug.VALUE_TYPE_LIST) raise Exception('Output index "{0}" not supported.'.format(index)) def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: super(ListGenerator, self).remove_plug(operator_instance=operator_instance, plug=plug) for index, plug in enumerate(operator_instance.inputs): plug.name = '[{0}]'.format(index) plug.display_name = '[{0}]'.format(index) for plug in operator_instance.outputs: plug.invalidate() def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass class ListIndex(Operator): def __init__(self): super(ListIndex, self).__init__( id='e4a81506-fb6b-4729-8273-f68e97f5bc6b', name='List Index', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): try: test = iter(input_plugs[0].computed_value) index = input_plugs[1].computed_value if 0 <= index < len(input_plugs[0].computed_value): output_plugs[0].computed_value = input_plugs[0].computed_value[index] else: output_plugs[0].computed_value = None except TypeError: output_plugs[0].computed_value = None def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST) if index == 1: plug = Plug.Create( parent=parent, name='index', display_name='Index', value_type=Plug.VALUE_TYPE_INTEGER, editable=True ) plug.computed_value = 0 return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Output', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].value = ['hello', 'world'] input_plugs[1].value = 1 def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 'world': raise Exception('Test failed.') class MDLColorSpace(Operator): def __init__(self): super(MDLColorSpace, self).__init__( id='cf0b97c8-fb55-4cf3-8afc-23ebd4a0a6c7', name='MDL Color Space', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else 'auto' def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_ENUM, editable=True ) plug.enum_values = ['auto', 'raw', 'sRGB'] plug.default_value = 'auto' plug.value = 'auto' return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = output_plugs[0].enum_values[2] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == output_plugs[0].enum_values[2]: raise Exception('Test failed.') class MDLTextureResolver(Operator): def __init__(self): super(MDLTextureResolver, self).__init__( id='af766adb-cf54-4a8b-a598-44b04fbcf630', name='MDL Texture Resolver', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): filepath = input_plugs[0].input.computed_value if input_plugs[0].input else '' value_type = util.to_plug_value_type(value=filepath, assumed_value_type=Plug.VALUE_TYPE_STRING) filepath = filepath if value_type == Plug.VALUE_TYPE_STRING else '' colorspace = input_plugs[1].computed_value output_plugs[0].computed_value = [filepath, colorspace] def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input', display_name='Input', value_type=Plug.VALUE_TYPE_STRING) if index == 1: plug = Plug.Create( parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_ENUM, editable=True ) plug.enum_values = ['auto', 'raw', 'sRGB'] plug.default_value = 'auto' plug.value = 'auto' return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST, editable=False, ) plug.default_value = ['', 'auto'] plug.value = ['', 'auto'] return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].value = 'c:/folder/color.png' input_plugs[1].value = 'raw' def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[3].computed_value == ['c:/folder/color.png', 'raw']: raise Exception('Test failed.') class SplitTextureData(Operator): def __init__(self): super(SplitTextureData, self).__init__( id='6a411798-434c-4ad4-b464-0bd2e78cdcec', name='Split Texture Data', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=2 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): is_valid_input = False try: value = input_plugs[0].computed_value test = iter(value) if len(value) == 2: if sys.version_info.major < 3: if isinstance(value[0], basestring) and isinstance(value[1], basestring): is_valid_input = True else: if isinstance(value[0], str) and isinstance(value[1], str): is_valid_input = True except TypeError: pass if is_valid_input: output_plugs[0].computed_value = value[0] output_plugs[1].computed_value = value[1] else: output_plugs[0].computed_value = '' output_plugs[1].computed_value = 'auto' def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST) plug.default_value = ['', 'auto'] plug.computed_value = ['', 'auto'] return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='texture_path', display_name='Texture Path', value_type=Plug.VALUE_TYPE_STRING) plug.default_value = '' plug.computed_value = '' return plug if index == 1: plug = Plug.Create(parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_STRING) plug.default_value = 'auto' plug.computed_value = 'auto' return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].computed_value = ['hello.png', 'world'] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 'hello.png': raise Exception('Test failed.') if not output_plugs[1].computed_value == 'world': raise Exception('Test failed.') class Multiply(Operator): def __init__(self): super(Multiply, self).__init__( id='0f5c9828-f582-48aa-b055-c12b91e692a7', name='Multiply', required_inputs=0, min_inputs=2, max_inputs=-1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): values = [] for input_plug in input_plugs: if isinstance(input_plug.computed_value, int): values.append(input_plug.computed_value) continue if isinstance(input_plug.computed_value, float): values.append(input_plug.computed_value) if len(values) < 2: output_plugs[0].computed_value = 0 else: product = 1.0 for o in values: product *= o output_plugs[0].computed_value = product for input_plug in input_plugs: input_plug.is_editable = not input_plug.input def generate_input(self, parent: DagNode, index: int) -> Plug: plug = Plug.Create( parent=parent, name='[{0}]'.format(index), display_name='[{0}]'.format(index), value_type=Plug.VALUE_TYPE_FLOAT, editable=True, is_removable=index > 1, ) plug.default_value = 1.0 plug.value = 1.0 plug.computed_value = 1.0 return plug def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='product', display_name='product', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Output index "{0}" not supported.'.format(index)) def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: super(Multiply, self).remove_plug(operator_instance=operator_instance, plug=plug) for index, plug in enumerate(operator_instance.inputs): plug.name = '[{0}]'.format(index) plug.display_name = '[{0}]'.format(index) for plug in operator_instance.outputs: plug.invalidate() def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].computed_value = 2 input_plugs[1].computed_value = 2 def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 4: raise Exception('Test failed.') class ColorSpaceResolver(Operator): MAPPING = { 'MDL|auto|Blender': 'sRGB', 'MDL|srgb|Blender': 'sRGB', 'MDL|raw|Blender': 'Raw', 'Blender|filmic log|MDL': 'raw', 'Blender|linear|MDL': 'raw', 'Blender|linear aces|MDL': 'raw', 'Blender|non-color|MDL': 'raw', 'Blender|raw|MDL': 'raw', 'Blender|srgb|MDL': 'sRGB', 'Blender|xyz|MDL': 'raw', } DEFAULT = { 'Blender': 'Linear', 'MDL': 'auto', } def __init__(self): super(ColorSpaceResolver, self).__init__( id='c159df8f-a0a2-4300-b897-e8eaa689a901', name='Color Space Resolver', required_inputs=3, min_inputs=3, max_inputs=3, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): color_space = input_plugs[0].computed_value.lower() from_color_space = input_plugs[1].computed_value to_color_space = input_plugs[2].computed_value key = '{0}|{1}|{2}'.format( from_color_space, color_space, to_color_space ) if key in ColorSpaceResolver.MAPPING: output_plugs[0].computed_value = ColorSpaceResolver.MAPPING[key] else: output_plugs[0].computed_value = ColorSpaceResolver.DEFAULT[to_color_space] def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_STRING, editable=False, is_removable=False, ) plug.default_value = '' plug.computed_value = '' return plug if index == 1: plug = Plug.Create( parent=parent, name='from_color_space', display_name='From', value_type=Plug.VALUE_TYPE_ENUM, editable=True ) plug.enum_values = ['MDL', 'Blender'] plug.default_value = 'MDL' plug.computed_value = 'MDL' return plug if index == 2: plug = Plug.Create( parent=parent, name='to_color_space', display_name='To', value_type=Plug.VALUE_TYPE_ENUM, editable=True ) plug.enum_values = ['Blender', 'MDL'] plug.default_value = 'Blender' plug.computed_value = 'Blender' return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_STRING, editable=False ) plug.default_value = '' plug.computed_value = '' return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): raise NotImplementedError() def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == output_plugs[0].enum_values[2]: raise Exception('Test failed.') class Add(Operator): def __init__(self): super(Add, self).__init__( id='f2818669-5454-4599-8792-2cb09f055bf9', name='Add', required_inputs=0, min_inputs=2, max_inputs=-1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output = 0 for input_plug in input_plugs: try: output += input_plug.computed_value except: pass output_plugs[0].computed_value = output def generate_input(self, parent: DagNode, index: int) -> Plug: plug = Plug.Create( parent=parent, name='[{0}]'.format(index), display_name='[{0}]'.format(index), value_type=Plug.VALUE_TYPE_FLOAT, editable=True, is_removable=True, ) plug.default_value = 0.0 plug.computed_value = 0.0 return plug def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='sum', display_name='sum', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Output index "{0}" not supported.'.format(index)) def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: super(Add, self).remove_plug(operator_instance=operator_instance, plug=plug) for index, plug in enumerate(operator_instance.inputs): plug.name = '[{0}]'.format(index) plug.display_name = '[{0}]'.format(index) for plug in operator_instance.outputs: plug.invalidate() def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass class Subtract(Operator): def __init__(self): super(Subtract, self).__init__( id='15f523f3-4e94-43a5-8306-92d07cbfa48c', name='Subtract', required_inputs=0, min_inputs=2, max_inputs=-1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output = None for input_plug in input_plugs: try: if output is None: output = input_plug.computed_value else: output -= input_plug.computed_value except: pass output_plugs[0].computed_value = output def generate_input(self, parent: DagNode, index: int) -> Plug: plug = Plug.Create( parent=parent, name='[{0}]'.format(index), display_name='[{0}]'.format(index), value_type=Plug.VALUE_TYPE_FLOAT, editable=True, is_removable=True, ) plug.default_value = 0.0 plug.computed_value = 0.0 return plug def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='difference', display_name='difference', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Output index "{0}" not supported.'.format(index)) def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: super(Subtract, self).remove_plug(operator_instance=operator_instance, plug=plug) for index, plug in enumerate(operator_instance.inputs): plug.name = '[{0}]'.format(index) plug.display_name = '[{0}]'.format(index) for plug in operator_instance.outputs: plug.invalidate() def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass class Remap(Operator): def __init__(self): super(Remap, self).__init__( id='2405c02a-facc-47a6-80ef-d35d959b0cd4', name='Remap', required_inputs=5, min_inputs=5, max_inputs=5, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): result = 0.0 old_value = input_plugs[0].computed_value try: test = iter(old_value) is_iterable = True except TypeError: is_iterable = False if not is_iterable: try: old_min = input_plugs[1].computed_value old_max = input_plugs[2].computed_value new_min = input_plugs[3].computed_value new_max = input_plugs[4].computed_value result = ((old_value - old_min) / (old_max - old_min)) * (new_max - new_min) + new_min except: pass else: result = [] for o in old_value: try: old_min = input_plugs[1].computed_value old_max = input_plugs[2].computed_value new_min = input_plugs[3].computed_value new_max = input_plugs[4].computed_value result.append(((o - old_min) / (old_max - old_min)) * (new_max - new_min) + new_min) except: pass output_plugs[0].computed_value = result def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='value', display_name='Value', value_type=Plug.VALUE_TYPE_ANY) plug.default_value = 0 plug.computed_value = 0 return plug if index == 1: plug = Plug.Create(parent=parent, name='old_min', display_name='Old Min', value_type=Plug.VALUE_TYPE_FLOAT) plug.is_editable = True plug.default_value = 0 plug.computed_value = 0 return plug if index == 2: plug = Plug.Create(parent=parent, name='old_max', display_name='Old Max', value_type=Plug.VALUE_TYPE_FLOAT) plug.is_editable = True plug.default_value = 1 plug.computed_value = 1 return plug if index == 3: plug = Plug.Create(parent=parent, name='new_min', display_name='New Min', value_type=Plug.VALUE_TYPE_FLOAT) plug.is_editable = True plug.default_value = 0 plug.computed_value = 0 return plug if index == 4: plug = Plug.Create(parent=parent, name='new_max', display_name='New Max', value_type=Plug.VALUE_TYPE_FLOAT) plug.is_editable = True plug.default_value = 10 plug.computed_value = 10 return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='remapped_value', display_name='Remapped Value', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].computed_value = 0.5 input_plugs[1].computed_value = 0 input_plugs[2].computed_value = 1 input_plugs[3].computed_value = 1 input_plugs[4].computed_value = 0 def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 0.5: raise Exception('Test failed.')
77,143
Python
37.765829
150
0.570421
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/singleton.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. def Singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance
1,123
Python
34.124999
74
0.69902
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/generator/util.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import sys import typing from ..data import Library, Target from .core import IGenerator __generators: typing.List['IGenerator'] = [] def register(generator: IGenerator) -> typing.NoReturn: """ Registers the generator at the top of the internal list - overriding previously registered generators - for future queries and processes. """ generators = getattr(sys.modules[__name__], '__generators') if generator not in generators: generators.insert(0, generator) def un_register(generator: IGenerator) -> typing.NoReturn: """ Removes the generator from internal list of generators and will ignore it for future queries and processes. """ generators = getattr(sys.modules[__name__], '__generators') if generator in generators: generators.remove(generator) def can_generate_target(class_name: str) -> bool: """ """ generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_target(class_name=class_name): return True return False def generate_target(class_name: str) -> typing.Tuple[Library, Target]: """ """ generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_target(class_name=class_name): print('UMM using generator "{0}" for class_name "{1}".'.format(generator, class_name)) return generator.generate_target(class_name=class_name) raise Exception('Registered generators does not support action.') def generate_targets() -> typing.List[typing.Tuple[Library, Target]]: """ Generates targets from all registered workers that are able to. """ targets = [] generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_targets(): print('UMM using generator "{0}" for generating targets.'.format(generator)) targets.extend(generator.generate_targets()) return targets def can_generate_target_from_instance(instance: object) -> bool: """ """ generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_target_from_instance(instance=instance): return True return False def generate_target_from_instance(instance: object) -> typing.List[typing.Tuple[Library, Target]]: """ Generates targets from all registered workers that are able to. """ generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_target_from_instance(instance=instance): print('UMM using generator "{0}" for instance "{1}".'.format(generator, instance)) return generator.generate_target_from_instance(instance=instance)
3,695
Python
40.066666
149
0.696076
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/generator/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/generator/core.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from abc import ABCMeta, abstractmethod import typing from ..data import Library, Target class IGenerator(metaclass=ABCMeta): """ """ @abstractmethod def __init__(self): super(IGenerator, self).__init__() @abstractmethod def can_generate_target(self, class_name: str) -> bool: """ """ pass @abstractmethod def generate_target(self, class_name: str) -> typing.Tuple[Library, Target]: """ """ pass @abstractmethod def can_generate_targets(self) -> bool: """ """ pass @abstractmethod def generate_targets(self) -> typing.List[typing.Tuple[Library, Target]]: """ """ pass @abstractmethod def can_generate_target_from_instance(self, instance: object) -> bool: """ """ pass @abstractmethod def generate_target_from_instance(self, instance: object) -> typing.Tuple[Library, Target]: """ """ pass
1,823
Python
27.952381
95
0.656061
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/converter/util.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. """ Convert Queries & Actions ######################### DCC Connectors and other conversion solutions will want to use this module. There are three different conversion strategies available: 1. Source *class* and *data*. The framework finds a suitable conversion template and returns data indicating a *target class* and data for setting its attributes. For example: .. code:: from omni.universalmaterialmap.core.converter import util if util.can_convert_data_to_data( class_name='lambert', render_context='MDL', source_data=[ ('color', 'color_texture.png'), ('normalCamera', 'normal_texture.png') ]): data = util.convert_data_to_data( class_name='lambert', render_context='MDL', source_data=[ ('color', 'color_texture.png'), ('normalCamera', 'normal_texture.png') ] ) ...could return: .. code:: [ ('umm_target_class', 'omnipbr'), ('diffuse_texture', 'color_texture.png'), ('normalmap_texture', 'normal_texture.png'), ] Note that the first value pair :code:`('umm_target_class', 'omnipbr')` indicates the object class that should be used for conversion. All other value pairs indicate attribute names and attribute values. Using this strategy puts very little responsibility on the conversion workers to understand assets. They merely have to apply the arguments to a conversion template, compute the internal graph, and spit out the results. It also means that the solution invoking the converter will have to gather the necessary arguments from some object or data source. 2. Source *instance* into conversion data. Here we use an object instance in order to get the same data as in strategy #1 above. For example: .. code:: from omni.universalmaterialmap.core.converter import util if util.can_convert_instance( instance=MyLambertPyNode, render_context='MDL'): data = util.convert_instance_to_data( instance=MyLambertPyNode, render_context='MDL' ) ...could return: .. code:: [ ('umm_target_class', 'omnipbr'), ('diffuse_texture', 'color_texture.png'), ('normalmap_texture', 'normal_texture.png'), ] Note that the first value pair :code:`('umm_target_class', 'omnipbr')` indicates the object class that should be used for conversion. All other value pairs indicate attribute names and attribute values. The advantage here is that the user of the framework can rely on a converter's understanding of objects and attributes. The downside is that there has to be an actual asset or dependency graph loaded. 3. Source *instance* into converted object. In this approach the converter will create a new object and set its properties/attributes based on a conversion template. For example: .. code:: from omni.universalmaterialmap.core.converter import util if util.can_convert_instance( instance=MyLambertPyNode, render_context='MDL'): node = util.convert_instance_to_instance( instance=MyLambertPyNode, render_context='MDL' ) ...could create and return an MDL material in the current Maya scene. Manifest Query ############## Module has methods for querying its conversion capabilities as indicated by library manifests. This could be useful when wanting to expose commands for converting assets within a DCC application scene. Note that this API does not require any data or object instance argument. It's a more *general* query. .. code:: from omni.universalmaterialmap.core.converter import util manifest = util.get_conversion_manifest() # Returns data indicating what source class can be converted to a render context. # # Example: # [ # ('lambert', 'MDL'), # ('blinn', 'MDL'), # ] if (my_class_name, 'MDL') in manifest: # Do something """ import sys import typing import traceback from .. import data from .core import ICoreConverter, IDataConverter, IObjectConverter _debug_mode = False __converters: typing.List['ICoreConverter'] = [] TARGET_CLASS_IDENTIFIER = 'umm_target_class' def register(converter: ICoreConverter) -> typing.NoReturn: """ Registers the converter at the top of the internal list - overriding previously registered converters - for future queries and processes. """ converters = getattr(sys.modules[__name__], '__converters') if converter not in converters: if _debug_mode: print('UMM: core.converter.util: Registering converter: "{0}"'.format(converter)) converters.insert(0, converter) elif _debug_mode: print('UMM: core.converter.util: Not registering converter because it is already registered: "{0}"'.format(converter)) def un_register(converter: ICoreConverter) -> typing.NoReturn: """ Removes the converter from internal list of converters and will ignore it for future queries and processes. """ converters = getattr(sys.modules[__name__], '__converters') if converter in converters: if _debug_mode: print('UMM: core.converter.util: un-registering converter: "{0}"'.format(converter)) converters.remove(converter) elif _debug_mode: print('UMM: core.converter.util: Not un-registering converter because it not registered to begin with: "{0}"'.format(converter)) def can_create_instance(class_name: str) -> bool: """ Resolves if a converter can create a node. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_create_instance(class_name=class_name): if _debug_mode: print('UMM: core.converter.util: converter can create instance: "{0}"'.format(converter)) return True if _debug_mode: print('UMM: core.converter.util: no converter can create instance.') return False def create_instance(class_name: str) -> object: """ Creates an asset using the first converter in the internal list that supports the class_name. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_create_instance(class_name=class_name): if _debug_mode: print('UMM: core.converter.util: converter creating instance: "{0}"'.format(converter)) return converter.create_instance(class_name=class_name) raise Exception('Registered converters does not support class "{0}".'.format(class_name)) def can_set_plug_value(instance: object, plug: data.Plug) -> bool: """ Resolves if a converter can set the plug's value given the instance and its attributes. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if _debug_mode: print('UMM: core.converter.util: converter can set plug value: "{0}"'.format(converter)) if converter.can_set_plug_value(instance=instance, plug=plug): return True if _debug_mode: print('UMM: core.converter.util: converter cannot set plug value given instance "{0}" and plug "{1}"'.format(instance, plug)) return False def set_plug_value(instance: object, plug: data.Plug) -> typing.NoReturn: """ Sets the plug's value given the value of the instance's attribute named the same as the plug. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_set_plug_value(instance=instance, plug=plug): if _debug_mode: print('UMM: core.converter.util: converter setting plug value: "{0}"'.format(converter)) return converter.set_plug_value(instance=instance, plug=plug) raise Exception('Registered converters does not support action.') def can_set_instance_attribute(instance: object, name: str) -> bool: """ Resolves if a converter can set an attribute by the given name on the instance. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if _debug_mode: print('UMM: core.converter.util: converter can set instance attribute: "{0}", "{1}", "{2}"'.format(converter, instance, name)) if converter.can_set_instance_attribute(instance=instance, name=name): return True if _debug_mode: print('UMM: core.converter.util: cannot set instance attribute: "{0}", "{1}"'.format(instance, name)) return False def set_instance_attribute(instance: object, name: str, value: typing.Any) -> typing.NoReturn: """ Sets the named attribute on the instance to the value. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_set_instance_attribute(instance=instance, name=name): if _debug_mode: print('UMM: core.converter.util: converter setting instance attribute: "{0}", "{1}", "{2}", "{3}"'.format(converter, instance, name, value)) return converter.set_instance_attribute(instance=instance, name=name, value=value) raise Exception('Registered converters does not support action.') def can_convert_instance(instance: object, render_context: str) -> bool: """ Resolves if a converter can convert the instance to another object given the render_context. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if _debug_mode: print('UMM: core.converter.util: converter can convert instance: "{0}", "{1}", "{2}"'.format(converter, instance, render_context)) if converter.can_convert_instance(instance=instance, render_context=render_context): return True return False def convert_instance_to_instance(instance: object, render_context: str) -> typing.Any: """ Interprets the instance and instantiates another object given the render_context. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_instance(instance=instance, render_context=render_context): if _debug_mode: print('UMM: core.converter.util: converter converting instance: "{0}", "{1}", "{2}"'.format(converter, instance, render_context)) return converter.convert_instance_to_instance(instance=instance, render_context=render_context) raise Exception('Registered converters does not support action.') def can_convert_instance_to_data(instance: object, render_context: str) -> bool: """ Resolves if a converter can convert the instance to another object given the render_context. """ try: converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_instance_to_data(instance=instance, render_context=render_context): return True except Exception as error: print('Warning: Universal Material Map: function "can_convert_instance_to_data": Unexpected error:') print('\targument "instance" = "{0}"'.format(instance)) print('\targument "render_context" = "{0}"'.format(render_context)) print('\terror: {0}'.format(error)) print('\tcallstack: {0}'.format(traceback.format_exc())) return False def convert_instance_to_data(instance: object, render_context: str) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ try: converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_instance_to_data(instance=instance, render_context=render_context): result = converter.convert_instance_to_data(instance=instance, render_context=render_context) print('Universal Material Map: convert_instance_to_data({0}, "{1}") generated data:'.format(instance, render_context)) print('\t(') for o in result: print('\t\t{0}'.format(o)) print('\t)') return result except Exception as error: print('Warning: Universal Material Map: function "convert_instance_to_data": Unexpected error:') print('\targument "instance" = "{0}"'.format(instance)) print('\targument "render_context" = "{0}"'.format(render_context)) print('\terror: {0}'.format(error)) print('\tcallstack: {0}'.format(traceback.format_exc())) result = dict() result['umm_notification'] = 'unexpected_error' result['message'] = 'Not able to convert "{0}" for render context "{1}" because there was an unexpected error. Details: {2}'.format(instance, render_context, error) return result raise Exception('Registered converters does not support action.') def can_convert_attribute_values(instance: object, render_context: str, destination: object) -> bool: """ Resolves if the instance's attribute values can be converted and set on the destination object's attributes. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_attribute_values(instance=instance, render_context=render_context, destination=destination): return True return False def convert_attribute_values(instance: object, render_context: str, destination: object) -> typing.NoReturn: """ Attribute values are converted and set on the destination object's attributes. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_attribute_values(instance=instance, render_context=render_context, destination=destination): return converter.convert_attribute_values(instance=instance, render_context=render_context, destination=destination) raise Exception('Registered converters does not support action.') def can_convert_data_to_data(class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> bool: """ Resolves if a converter can convert the given class and source_data to another class and target data. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IDataConverter): if converter.can_convert_data_to_data(class_name=class_name, render_context=render_context, source_data=source_data): return True return False def convert_data_to_data(class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IDataConverter): if converter.can_convert_data_to_data(class_name=class_name, render_context=render_context, source_data=source_data): result = converter.convert_data_to_data(class_name=class_name, render_context=render_context, source_data=source_data) print('Universal Material Map: convert_data_to_data("{0}", "{1}") generated data:'.format(class_name, render_context)) print('\t(') for o in result: print('\t\t{0}'.format(o)) print('\t)') return result raise Exception('Registered converters does not support action.') def can_apply_data_to_instance(source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> bool: """ Resolves if a converter can create one or more instances given the arguments. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_apply_data_to_instance(source_class_name=source_class_name, render_context=render_context, source_data=source_data, instance=instance): return True return False def apply_data_to_instance(source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> dict: """ Returns a list of created objects. """ try: converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_apply_data_to_instance(source_class_name=source_class_name, render_context=render_context, source_data=source_data, instance=instance): converter.apply_data_to_instance(source_class_name=source_class_name, render_context=render_context, source_data=source_data, instance=instance) print('Universal Material Map: apply_data_to_instance("{0}", "{1}") completed.'.format(instance, render_context)) result = dict() result['umm_notification'] = 'success' result['message'] = 'Material conversion data applied to "{0}".'.format(instance) return result result = dict() result['umm_notification'] = 'incomplete_process' result['message'] = 'Not able to convert type "{0}" for render context "{1}" because there is no Conversion Graph for that scenario. No changes were applied to "{2}".'.format(source_class_name, render_context, instance) return result except Exception as error: print('UMM: Unexpected error: {0}'.format(traceback.format_exc())) result = dict() result['umm_notification'] = 'unexpected_error' result['message'] = 'Not able to convert type "{0}" for render context "{1}" because there was an unexpected error. Some changes may have been applied to "{2}". Details: {3}'.format(source_class_name, render_context, instance, error) return result def get_conversion_manifest() -> typing.List[typing.Tuple[str, str]]: """ Returns data indicating what source class can be converted to a render context. Example: [('lambert', 'MDL'), ('blinn', 'MDL'),] """ manifest: typing.List[typing.Tuple[str, str]] = [] converters = getattr(sys.modules[__name__], '__converters') for converter in converters: manifest.extend(converter.get_conversion_manifest()) return manifest
20,886
Python
47.687646
241
0.655559
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/converter/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/converter/core.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from abc import ABCMeta, abstractmethod import typing from ..data import Plug class ICoreConverter(metaclass=ABCMeta): """ """ @abstractmethod def __init__(self): super(ICoreConverter, self).__init__() @abstractmethod def get_conversion_manifest(self) -> typing.List[typing.Tuple[str, str]]: """ Returns data indicating what source class can be converted to a render context. Example: [('lambert', 'MDL'), ('blinn', 'MDL'),] """ raise NotImplementedError() class IObjectConverter(ICoreConverter): """ """ @abstractmethod def can_create_instance(self, class_name: str) -> bool: """ Returns true if worker can generate an object of the given class name. """ raise NotImplementedError() @abstractmethod def create_instance(self, class_name: str) -> object: """ Creates an object of the given class name. """ raise NotImplementedError() @abstractmethod def can_set_plug_value(self, instance: object, plug: Plug) -> bool: """ Returns true if worker can set the plug's value given the instance and its attributes. """ raise NotImplementedError() @abstractmethod def set_plug_value(self, instance: object, plug: Plug) -> typing.NoReturn: """ Sets the plug's value given the value of the instance's attribute named the same as the plug. """ raise NotImplementedError() @abstractmethod def can_set_instance_attribute(self, instance: object, name: str): """ Resolves if worker can set an attribute by the given name on the instance. """ return False @abstractmethod def set_instance_attribute(self, instance: object, name: str, value: typing.Any) -> typing.NoReturn: """ Sets the named attribute on the instance to the value. """ raise NotImplementedError() @abstractmethod def can_convert_instance(self, instance: object, render_context: str) -> bool: """ Resolves if worker can convert the instance to another object given the render_context. """ return False @abstractmethod def convert_instance_to_instance(self, instance: object, render_context: str) -> typing.Any: """ Converts the instance to another object given the render_context. """ raise NotImplementedError() @abstractmethod def can_convert_instance_to_data(self, instance: object, render_context: str) -> bool: """ Resolves if worker can convert the instance to another object given the render_context. """ return False @abstractmethod def convert_instance_to_data(self, instance: object, render_context: str) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ raise NotImplementedError() @abstractmethod def can_convert_attribute_values(self, instance: object, render_context: str, destination: object) -> bool: """ Resolves if the instance's attribute values can be converted and set on the destination object's attributes. """ raise NotImplementedError() @abstractmethod def convert_attribute_values(self, instance: object, render_context: str, destination: object) -> typing.NoReturn: """ Attribute values are converted and set on the destination object's attributes. """ raise NotImplementedError() @abstractmethod def can_apply_data_to_instance(self, source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> bool: """ Resolves if worker can convert the instance to another object given the render_context. """ return False @abstractmethod def apply_data_to_instance(self, source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> dict: """ Returns a notification object Examples: { 'umm_notification': "success", 'message': "Material \"Material_A\" was successfully converted from \"OmniPBR\" data." } { 'umm_notification': "incomplete_process", 'message': "Not able to convert \"Material_B\" using \"CustomMDL\" since there is no Conversion Graph supporting that scenario." } { 'umm_notification': "unexpected_error", 'message': "Not able to convert \"Material_C\" using \"OmniGlass\" due to an unexpected error. Details: \"cannot set property to None\"." } """ raise NotImplementedError() class IDataConverter(ICoreConverter): """ """ @abstractmethod def can_convert_data_to_data(self, class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> bool: """ Resolves if worker can convert the given class and source_data to another class and target data. """ return False @abstractmethod def convert_data_to_data(self, class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ raise NotImplementedError()
6,404
Python
40.590909
176
0.665209
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/service/store.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import os import uuid import traceback from .. import data from .. import operator from ..feature import POLLING from ..singleton import Singleton from .core import ChangeEvent, IDelegate from .delegate import Filesystem, FilesystemManifest, FilesystemSettings from .resources import install COMMON_LIBRARY_ID = '327ef29b-8358-441b-b2f0-4a16a9afd349' libraries_directory = os.path.expanduser('~').replace('\\', '/') if not libraries_directory.endswith('/Documents'): # os.path.expanduser() has different behaviour between 2.7 and 3 libraries_directory = '{0}/Documents'.format(libraries_directory) libraries_directory = '{0}/Omniverse'.format(libraries_directory) common_library_directory = '{0}/ConnectorCommon/UMMLibrary'.format(libraries_directory) cache_directory = '{0}/Cache'.format(common_library_directory) COMMON_LIBRARY = data.Library.Create( library_id=COMMON_LIBRARY_ID, name='Common', manifest=FilesystemManifest(root_directory='{0}'.format(common_library_directory)), conversion_graph=Filesystem(root_directory='{0}/ConversionGraph'.format(common_library_directory)), target=Filesystem(root_directory='{0}/Target'.format(common_library_directory)), settings=FilesystemSettings(root_directory='{0}'.format(common_library_directory)), ) DEFAULT_LIBRARIES = [COMMON_LIBRARY] class _ItemProvider(object): """ Class provides IO interface for a single UMM Library item. """ def __init__(self, identifier: str, library_delegate: IDelegate = None, cache_delegate: IDelegate = None): super(_ItemProvider, self).__init__() self._library_delegate: typing.Union[IDelegate, typing.NoReturn] = library_delegate self._cache_delegate: typing.Union[IDelegate, typing.NoReturn] = cache_delegate self._identifier: str = identifier self._file_util: typing.Union[data.FileUtility, typing.NoReturn] = None self._content_cache: dict = dict() def revert(self) -> None: if self._file_util: self._file_util.content.deserialize(data=self._content_cache) def has_unsaved_changes(self) -> bool: if not self._file_util: return False return not self._file_util.content.serialize() == self._content_cache def read(self, update: bool = False) -> None: """ TODO: Check if path has changed since last read from disk. """ if not self._library_delegate and not self._cache_delegate: raise Exception('Not supported: No delegate available to read().') # update_cache() assumes that read() prioritizes reading with library delegate! delegate = self._library_delegate if self._library_delegate else self._cache_delegate if not self._file_util: contents = delegate.read(identifier=self._identifier) if contents is not None: self._file_util = data.FileUtility.FromData(data=contents) self._update_content_cache() elif update: contents = delegate.read(identifier=self._identifier) self._file_util.content.deserialize(data=contents) def create(self, instance: data.Serializable) -> None: self._file_util = data.FileUtility.FromInstance(instance=instance) self.write() def write(self, content: data.Serializable = None) -> None: if not self._library_delegate and not self._cache_delegate: raise Exception('Not supported: No delegate available to write().') if content: if not self._file_util: self._file_util = data.FileUtility.FromInstance(instance=content) else: self._file_util._content = content elif not self._file_util: raise Exception('Not supported: _ItemProvider not initialized properly prior to "write()"') contents = self._file_util.serialize() if self._library_delegate: self._library_delegate.write(identifier=self._identifier, contents=contents) if self._cache_delegate: self._cache_delegate.write(identifier=self._identifier, contents=contents) self._update_content_cache() def delete(self) -> None: if not self._library_delegate and not self._cache_delegate: raise Exception('Not supported: No delegate available to delete().') if self._library_delegate: self._library_delegate.delete(identifier=self._identifier) if self._cache_delegate: self._cache_delegate.delete(identifier=self._identifier) self._file_util = None self._content_cache = None def _update_content_cache(self) -> None: if not self._file_util: self._content_cache = dict() else: self._content_cache = self._file_util.content.serialize() def update_cache(self) -> bool: if not self._library_delegate or not self._cache_delegate: return False # Assumes that read() prioritizes reading with library delegate! try: self.read() except Exception as error: print('Warning: Universal Material Map error reading data with identifier "{0}". Cache will not be updated due to the read error.\n\tDetails: "{1}".\n\tCallstack: {2}'.format(self._identifier, error, traceback.format_exc())) return False self._cache_delegate.write(identifier=self._identifier, contents=self._file_util.serialize()) def on_shutdown(self): self._cache_delegate = None self._library_delegate = None self._identifier = None self._file_util = None self._content_cache = None @property def content(self) -> data.Serializable: return self._file_util.content class _LibraryProvider(object): """ Class provides IO interface for a single UMM Library. """ @staticmethod def _transfer_data(source: IDelegate, target: IDelegate) -> bool: """ Returns True if transfer was made. """ if not source or not target: return False for identifier in source.get_ids(): target.write(identifier=identifier, contents=source.read(identifier=identifier)) return True def __init__(self, library: data.Library): super(_LibraryProvider, self).__init__() self._library: data.Library = library if POLLING: self._manifest_subscription: uuid.uuid4 = None self._conversion_graph_subscription: uuid.uuid4 = None self._target_subscription: uuid.uuid4 = None self._manifest_cache: typing.Union[IDelegate, typing.NoReturn] = None self._conversion_graph_cache: typing.Union[IDelegate, typing.NoReturn] = None self._target_cache: typing.Union[IDelegate, typing.NoReturn] = None self._settings_cache: typing.Union[IDelegate, typing.NoReturn] = None self._manifest_providers: typing.Dict[str, _ItemProvider] = dict() self._conversion_graph_providers: typing.Dict[str, _ItemProvider] = dict() self._target_providers: typing.Dict[str, _ItemProvider] = dict() self._settings_providers: typing.Dict[str, _ItemProvider] = dict() self._initialize() def _initialize(self) -> None: cache: _ItemProvider for cache in self._manifest_providers.values(): cache.on_shutdown() for cache in self._conversion_graph_providers.values(): cache.on_shutdown() for cache in self._target_providers.values(): cache.on_shutdown() for cache in self._settings_providers.values(): cache.on_shutdown() self._manifest_providers = dict() self._conversion_graph_providers = dict() self._target_providers = dict() self._settings_providers = dict() if not self._library: return if not self._library.id == COMMON_LIBRARY_ID: self._manifest_cache = FilesystemManifest( root_directory='{0}/{1}'.format(cache_directory, self._library.id) ) self._conversion_graph_cache = Filesystem( root_directory='{0}/{1}/ConversionGraph'.format(cache_directory, self._library.id) ) self._target_cache = Filesystem( root_directory='{0}/{1}/Target'.format(cache_directory, self._library.id) ) self._settings_cache = FilesystemSettings( root_directory='{0}/{1}'.format(cache_directory, self._library.id) ) if not self._library.id == COMMON_LIBRARY_ID and not self._library.is_read_only: self._update_cache() def _update_cache(self) -> None: if self._library.is_read_only: return self._update_cache_table( source=self._library.manifest, target=self._manifest_cache, providers=self._manifest_providers, ) self._update_cache_table( source=self._library.conversion_graph, target=self._conversion_graph_cache, providers=self._conversion_graph_providers, ) self._update_cache_table( source=self._library.target, target=self._target_cache, providers=self._target_providers, ) self._update_cache_table( source=self._library.settings, target=self._settings_cache, providers=self._settings_providers, ) def _update_cache_table(self, source: IDelegate, target: IDelegate, providers: dict) -> None: if self._library.is_read_only: return if not source or not target: return for identifier in source.get_ids(): if identifier not in providers.keys(): provider = _ItemProvider( identifier=identifier, library_delegate=source, cache_delegate=target ) providers[identifier] = provider else: provider = providers[identifier] provider.update_cache() def get_settings(self) -> typing.List[data.Settings]: if not self._library.settings: return [] settings: typing.List[data.Settings] = [] for identifier in self._library.settings.get_ids(): if identifier not in self._settings_providers.keys(): cache = _ItemProvider( identifier=identifier, library_delegate=self._library.settings, cache_delegate=self._settings_cache ) self._settings_providers[identifier] = cache else: cache = self._settings_providers[identifier] cache.read() setting = typing.cast(data.Settings, cache.content) settings.append(setting) return settings def get_manifests(self) -> typing.List[data.ConversionManifest]: delegate = self._library.manifest if self._library.manifest else self._manifest_cache if not delegate: return [] manifests: typing.List[data.ConversionManifest] = [] conversion_graphs: typing.List[data.ConversionGraph] = None for identifier in delegate.get_ids(): if identifier not in self._manifest_providers.keys(): cache = _ItemProvider( identifier=identifier, library_delegate=self._library.manifest, cache_delegate=self._manifest_cache ) self._manifest_providers[identifier] = cache else: cache = self._manifest_providers[identifier] cache.read() manifest = typing.cast(data.ConversionManifest, cache.content) if not conversion_graphs: conversion_graphs = self.get_conversion_graphs() for item in manifest.conversion_maps: if not item._conversion_graph: for conversion_graph in conversion_graphs: if conversion_graph.id == item.conversion_graph_id: item._conversion_graph = conversion_graph break manifests.append(manifest) if POLLING: if self._library.manifest and not self._manifest_subscription: self._manifest_subscription = self._library.manifest.add_change_subscription(callback=self._on_store_manifest_changes) return manifests def get_conversion_graphs(self) -> typing.List[data.ConversionGraph]: delegate = self._library.conversion_graph if self._library.conversion_graph else self._conversion_graph_cache if not delegate: return [] conversion_graphs: typing.List[data.ConversionGraph] = [] for identifier in delegate.get_ids(): if identifier not in self._conversion_graph_providers.keys(): cache = _ItemProvider( identifier=identifier, library_delegate=self._library.conversion_graph, cache_delegate=self._conversion_graph_cache ) try: cache.read() except Exception as error: print('Warning: Universal Material Map error reading Conversion Graph data with identifier "{0}". Graph will not be available for use inside UMM.\n\tDetails: "{1}".\n\tCallstack: {2}'.format(identifier, error, traceback.format_exc())) continue self._conversion_graph_providers[identifier] = cache else: cache = self._conversion_graph_providers[identifier] try: cache.read() except Exception as error: print('Warning: Universal Material Map error reading Conversion Graph data with identifier "{0}". Graph will not be available for use inside UMM.\n\tDetails: "{1}".\n\tCallstack: {2}'.format(identifier, error, traceback.format_exc())) continue conversion_graph = typing.cast(data.ConversionGraph, cache.content) conversion_graph._library = self._library conversion_graph.filename = identifier conversion_graph._exists_on_disk = True conversion_graphs.append(conversion_graph) if POLLING: if self._library.conversion_graph and not self._conversion_graph_subscription: self._conversion_graph_subscription = self._library.conversion_graph.add_change_subscription(callback=self._on_store_conversion_graph_changes) return conversion_graphs def get_targets(self) -> typing.List[data.Target]: delegate = self._library.target if self._library.target else self._target_cache if not delegate: return [] targets: typing.List[data.Target] = [] for identifier in delegate.get_ids(): if identifier not in self._target_providers.keys(): cache = _ItemProvider( identifier=identifier, library_delegate=self._library.target, cache_delegate=self._target_cache ) self._target_providers[identifier] = cache else: cache = self._target_providers[identifier] cache.read() target = typing.cast(data.Target, cache.content) target.store_id = identifier targets.append(target) if POLLING: if self._library.target and not self._target_subscription: self._target_subscription = self._library.target.add_change_subscription(callback=self._on_store_target_changes) return targets def _on_store_manifest_changes(self, event: ChangeEvent) -> None: if not POLLING: raise NotImplementedError() print('_on_store_manifest_changes', event) def _on_store_conversion_graph_changes(self, event: ChangeEvent) -> None: if not POLLING: raise NotImplementedError() print('_on_store_conversion_graph_changes', event) def _on_store_target_changes(self, event: ChangeEvent) -> None: if not POLLING: raise NotImplementedError() print('_on_store_target_changes...', event, self) def revert(self, item: data.Serializable) -> bool: """ Returns True if the item existed in a data store and was successfully reverted. """ if isinstance(item, data.ConversionGraph): if item.filename not in self._conversion_graph_providers.keys(): return False filename = item.filename library = item.library cache = self._conversion_graph_providers[item.filename] cache.revert() item.filename = filename item._library = library item._exists_on_disk = True return True if isinstance(item, data.Target): if item.store_id not in self._target_providers.keys(): return False cache = self._target_providers[item.store_id] cache.revert() return True if isinstance(item, data.ConversionManifest): if item.store_id not in self._manifest_providers.keys(): return False cache = self._manifest_providers[item.store_id] cache.revert() return True if isinstance(item, data.Settings): if item.store_id not in self._settings_providers.keys(): return False cache = self._settings_providers[item.store_id] cache.revert() return True def write(self, item: data.Serializable, identifier: str = None, overwrite: bool = False) -> None: if isinstance(item, data.Settings): if not item.store_id: raise Exception('Not supported: Settings must have a valid store id in order to write the item.') if not self._library.settings: raise Exception('Library "{0}" with id="{1}" does not support a Settings store.'.format(self._library.name, self._library.id)) if item.store_id not in self._settings_providers.keys(): cache = _ItemProvider( identifier=item.store_id, library_delegate=self._library.settings, cache_delegate=self._settings_cache ) self._settings_providers[item.store_id] = cache else: if not overwrite: return cache = self._settings_providers[item.store_id] cache.write(content=item) return if isinstance(item, data.ConversionManifest): if not item.store_id: raise Exception('Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.store_id not in self._manifest_providers.keys(): cache = _ItemProvider( identifier=item.store_id, library_delegate=self._library.manifest, cache_delegate=self._manifest_cache ) self._manifest_providers[item.store_id] = cache else: if not overwrite: return cache = self._manifest_providers[item.store_id] cache.write(content=item) return if isinstance(item, data.ConversionGraph): if not item.filename and not identifier: raise Exception('Not supported: Conversion Manifest must have a valid store id in order to write the item.') key = identifier if identifier else item.filename if key not in self._conversion_graph_providers.keys(): cache = _ItemProvider( identifier=key, library_delegate=self._library.conversion_graph, cache_delegate=self._conversion_graph_cache ) self._conversion_graph_providers[key] = cache else: if not overwrite: return cache = self._conversion_graph_providers[key] item.revision += 1 cache.write(content=item) if identifier: item.filename = identifier item._exists_on_disk = True item._library = self._library return if isinstance(item, data.Target): if not item.store_id: raise Exception( 'Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.store_id not in self._target_providers.keys(): cache = _ItemProvider( identifier=item.store_id, library_delegate=self._library.target, cache_delegate=self._target_cache ) self._target_providers[item.store_id] = cache else: if not overwrite: return cache = self._target_providers[item.store_id] cache.write(content=item) return raise NotImplementedError() def delete(self, item: data.Serializable) -> None: if isinstance(item, data.Settings): if not item.store_id: raise Exception('Not supported: Settings must have a valid store id in order to write the item.') if not self._library.settings: raise Exception('Library "{0}" with id="{1}" does not support a Settings store.'.format(self._library.name, self._library.id)) if item.store_id not in self._settings_providers.keys(): return cache = self._settings_providers[item.store_id] cache.delete() cache.on_shutdown() del self._settings_providers[item.store_id] return if isinstance(item, data.ConversionManifest): if not item.store_id: raise Exception('Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.store_id not in self._manifest_providers.keys(): return cache = self._manifest_providers[item.store_id] cache.delete() cache.on_shutdown() del self._manifest_providers[item.store_id] return if isinstance(item, data.ConversionGraph): if not item.filename: raise Exception('Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.filename not in self._conversion_graph_providers.keys(): return cache = self._conversion_graph_providers[item.filename] cache.delete() cache.on_shutdown() del self._conversion_graph_providers[item.filename] return if isinstance(item, data.Target): if not item.store_id: raise Exception( 'Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.store_id not in self._target_providers.keys(): return cache = self._target_providers[item.store_id] cache.write(content=item) cache.on_shutdown() del self._target_providers[item.store_id] return raise NotImplementedError() def can_show_in_store(self, item: data.Serializable) -> bool: if isinstance(item, data.ConversionGraph): delegate = self._library.conversion_graph if self._library.conversion_graph else self._conversion_graph_cache if not delegate: return False return delegate.can_show_in_store(identifier=item.filename) if isinstance(item, data.Target): delegate = self._library.target if self._library.target else self._target_cache if not delegate: return False return delegate.can_show_in_store(identifier=item.store_id) return False def show_in_store(self, item: data.Serializable) -> None: if isinstance(item, data.ConversionGraph): delegate = self._library.conversion_graph if self._library.conversion_graph else self._conversion_graph_cache if not delegate: return return delegate.show_in_store(identifier=item.filename) if isinstance(item, data.Target): delegate = self._library.target if self._library.target else self._target_cache if not delegate: return return delegate.show_in_store(identifier=item.store_id) @property def library(self) -> data.Library: return self._library @library.setter def library(self, value: data.Library) -> None: if self._library == value: return if POLLING: if self._library: if self._manifest_subscription and self._library.manifest: self._library.manifest.remove_change_subscription(subscription_id=self._manifest_subscription) if self._conversion_graph_subscription and self._library.conversion_graph: self._library.conversion_graph.remove_change_subscription(subscription_id=self._conversion_graph_subscription) if self._target_subscription and self._library.target: self._library.target.remove_change_subscription(subscription_id=self._target_subscription) self._library = value self._initialize() @Singleton class __Manager: def __init__(self): install() self._library_caches: typing.Dict[str, _LibraryProvider] = dict() self._operators: typing.List[data.Operator] = [ operator.And(), operator.Add(), operator.BooleanSwitch(), operator.ColorSpaceResolver(), operator.ConstantBoolean(), operator.ConstantFloat(), operator.ConstantInteger(), operator.ConstantRGB(), operator.ConstantRGBA(), operator.ConstantString(), operator.Equal(), operator.GreaterThan(), operator.LessThan(), operator.ListGenerator(), operator.ListIndex(), operator.MayaTransparencyResolver(), operator.MergeRGB(), operator.MergeRGBA(), operator.MDLColorSpace(), operator.MDLTextureResolver(), operator.Multiply(), operator.Not(), operator.Or(), operator.Remap(), operator.SplitRGB(), operator.SplitRGBA(), operator.SplitTextureData(), operator.Subtract(), operator.ValueResolver(), operator.ValueTest(), ] for o in self._operators: if len([item for item in self._operators if item.id == o.id]) == 1: continue raise Exception('Operator id "{0}" is not unique.'.format(o.id)) provider = _LibraryProvider(library=COMMON_LIBRARY) self._library_caches[COMMON_LIBRARY_ID] = provider render_contexts = [ 'MDL', 'USDPreview', 'Blender', ] settings = provider.get_settings() if len(settings) == 0: self._settings: data.Settings = data.Settings() for render_context in render_contexts: self._settings.render_contexts.append(render_context) self._settings.render_contexts.append(render_context) self._save_settings() else: self._settings: data.Settings = settings[0] added_render_context = False for render_context in render_contexts: if render_context not in self._settings.render_contexts: self._settings.render_contexts.append(render_context) added_render_context = True if added_render_context: self._save_settings() for i in range(len(self._settings.libraries)): for library in DEFAULT_LIBRARIES: if self._settings.libraries[i].id == library.id: self._settings.libraries[i] = library break for library in DEFAULT_LIBRARIES: if len([o for o in self._settings.libraries if o.id == library.id]) == 0: self._settings.libraries.append(library) for library in self._settings.libraries: self.register_library(library=library) def _save_settings(self) -> None: if COMMON_LIBRARY_ID not in self._library_caches.keys(): raise Exception('Not supported: Common library not in cache. Unable to save settings.') cache = self._library_caches[COMMON_LIBRARY_ID] cache.write(item=self._settings, identifier=None, overwrite=True) def register_library(self, library: data.Library) -> None: preferences_changed = False to_remove = [] for item in self._settings.libraries: if item.id == library.id: if not item == library: to_remove.append(item) for item in to_remove: self._settings.libraries.remove(item) preferences_changed = True if library not in self._settings.libraries: self._settings.libraries.append(library) preferences_changed = True if preferences_changed: self._save_settings() if library.id not in self._library_caches.keys(): self._library_caches[library.id] = _LibraryProvider(library=library) else: cache = self._library_caches[library.id] cache.library = library def register_render_contexts(self, context: str) -> None: """Register a render context such as MDL or USD Preview.""" if context not in self._settings.render_contexts: self._settings.render_contexts.append(context) self._save_settings() def get_assembly(self, reference: data.TargetInstance) -> typing.Union[data.Target, None]: cache: _LibraryProvider for cache in self._library_caches.values(): for target in cache.get_targets(): if target.id == reference.target_id: return target return None def get_assemblies(self, library: data.Library = None) -> typing.List[data.Target]: if library: if library.id not in self._library_caches.keys(): return [] cache = self._library_caches[library.id] return cache.get_targets() targets: typing.List[data.Target] = [] cache: _LibraryProvider for cache in self._library_caches.values(): targets.extend(cache.get_targets()) return targets def get_documents(self, library: data.Library = None) -> typing.List[data.ConversionGraph]: conversion_graphs: typing.List[data.ConversionGraph] = [] if library: if library.id not in self._library_caches.keys(): return [] cache = self._library_caches[library.id] conversion_graphs = cache.get_conversion_graphs() else: cache: _LibraryProvider for cache in self._library_caches.values(): conversion_graphs.extend(cache.get_conversion_graphs()) for conversion_graph in conversion_graphs: self._completed_document_serialization(conversion_graph=conversion_graph) return conversion_graphs def get_document(self, library: data.Library, document_filename: str) -> typing.Union[data.ConversionGraph, typing.NoReturn]: if library.id not in self._library_caches.keys(): return None cache = self._library_caches[library.id] for conversion_graph in cache.get_conversion_graphs(): if conversion_graph.filename == document_filename: self._completed_document_serialization(conversion_graph=conversion_graph) return conversion_graph return None def can_show_in_filesystem(self, document: data.ConversionGraph) -> bool: if not document.library: return False if document.library.id not in self._library_caches.keys(): return False cache = self._library_caches[document.library.id] return cache.can_show_in_store(item=document) def show_in_filesystem(self, document: data.ConversionGraph) -> None: if not document.library: return if document.library.id not in self._library_caches.keys(): return cache = self._library_caches[document.library.id] cache.show_in_store(item=document) def get_document_by_id(self, library: data.Library, document_id: str) -> typing.Union[data.ConversionGraph, typing.NoReturn]: for conversion_graph in self.get_documents(library=library): if conversion_graph.id == document_id: return conversion_graph return None def create_new_document(self, library: data.Library) -> data.ConversionGraph: conversion_graph = data.ConversionGraph() conversion_graph._library = library conversion_graph.filename = '' self._completed_document_serialization(conversion_graph=conversion_graph) return conversion_graph def _completed_document_serialization(self, conversion_graph: data.ConversionGraph) -> None: build_dag = len(conversion_graph.target_instances) == 0 for reference in conversion_graph.target_instances: if reference.target and reference.target.id == reference.target_id: continue reference.target = self.get_assembly(reference=reference) build_dag = True if build_dag: conversion_graph.build_dag() def create_from_source(self, source: data.ConversionGraph) -> data.ConversionGraph: new_conversion_graph = data.ConversionGraph() new_id = new_conversion_graph.id new_conversion_graph.deserialize(data=source.serialize()) new_conversion_graph._id = new_id new_conversion_graph._library = source.library new_conversion_graph.filename = source.filename self._completed_document_serialization(conversion_graph=new_conversion_graph) return new_conversion_graph def revert(self, library: data.Library, instance: data.Serializable) -> bool: """ Returns True if the file existed on disk and was successfully reverted. """ if not library: return False if library.id not in self._library_caches.keys(): return False cache = self._library_caches[library.id] if cache.revert(item=instance): if isinstance(instance, data.ConversionGraph): self._completed_document_serialization(conversion_graph=instance) return True return False def find_documents(self, source_class: str, library: data.Library = None) -> typing.List[data.ConversionGraph]: conversion_graphs = [] for conversion_graph in self.get_documents(library=library): if not conversion_graph.source_node: continue for node in conversion_graph.source_node.target.nodes: if node.class_name == source_class: conversion_graphs.append(conversion_graph) return conversion_graphs def find_assembly(self, assembly_class: str, library: data.Library = None) -> typing.List[data.Target]: targets = [] for target in self.get_assemblies(library=library): for node in target.nodes: if node.class_name == assembly_class: targets.append(target) break return targets def _get_manifest_filepath(self, library: data.Library) -> str: return '{0}/ConversionManifest.json'.format(library.path) def get_conversion_manifest(self, library: data.Library) -> data.ConversionManifest: if library.id not in self._library_caches.keys(): return data.ConversionManifest() cache = self._library_caches[library.id] manifests = cache.get_manifests() if len(manifests): manifest = manifests[0] for conversion_map in manifest.conversion_maps: if conversion_map.conversion_graph is None: continue self._completed_document_serialization(conversion_graph=conversion_map.conversion_graph) return manifest return data.ConversionManifest() def save_conversion_manifest(self, library: data.Library, manifest: data.ConversionManifest) -> None: if library.id not in self._library_caches.keys(): return cache = self._library_caches[library.id] cache.write(item=manifest) def write(self, filename: str, instance: data.Serializable, library: data.Library, overwrite: bool = False) -> None: if not filename.strip(): raise Exception('Invalid filename: empty string.') if library.id not in self._library_caches.keys(): raise Exception('Cannot write to a library that is not registered') if not filename.lower().endswith('.json'): filename = '{0}.json'.format(filename) cache = self._library_caches[library.id] cache.write(item=instance, identifier=filename, overwrite=overwrite) def delete_document(self, document: data.ConversionGraph) -> bool: if not document.library: return False if document.library.id not in self._library_caches.keys(): return False cache = self._library_caches[document.library.id] cache.delete(item=document) return True def is_graph_entity_id(self, identifier: str) -> bool: for item in self.get_assemblies(): if item.id == identifier: return True return False def get_graph_entity(self, identifier: str) -> data.GraphEntity: for item in self.get_assemblies(): if item.id == identifier: return data.TargetInstance.FromAssembly(assembly=item) for item in self.get_operators(): if item.id == identifier: return data.OperatorInstance.FromOperator(operator=item) raise Exception('Graph Entity with id "{0}" cannot be found'.format(identifier)) def register_operator(self, operator: data.Operator): if operator not in self._operators: self._operators.append(operator) def get_operators(self) -> typing.List[data.Operator]: return self._operators def is_operator_id(self, identifier: str) -> bool: for item in self.get_operators(): if item.id == identifier: return True return False def on_shutdown(self): if len(self._library_caches.keys()): provider: _LibraryProvider for provider in self._library_caches.values(): provider.library = None self._library_caches = dict() @property def libraries(self) -> typing.List[data.Library]: return self._settings.libraries def register_library(library: data.Library) -> None: """ """ __Manager().register_library(library=library) def get_libraries() -> typing.List[data.Library]: """ """ return __Manager().libraries def get_library(library_id: str) -> data.Library: """ """ for library in __Manager().libraries: if library.id == library_id: return library raise Exception('Library with id "{0}" not found.'.format(library_id)) def get_assembly(reference: data.TargetInstance) -> data.Target: """ """ # TODO: Is this still needed? return __Manager().get_assembly(reference=reference) def write(filename: str, instance: data.Serializable, library: data.Library, overwrite: bool = False) -> None: """ """ __Manager().write(filename=filename, instance=instance, library=library, overwrite=overwrite) def get_assemblies(library: data.Library = None) -> typing.List[data.Target]: """ """ return __Manager().get_assemblies(library=library) def is_graph_entity_id(identifier: str) -> bool: """ """ return __Manager().is_graph_entity_id(identifier=identifier) def get_graph_entity(identifier: str) -> data.GraphEntity: """ """ return __Manager().get_graph_entity(identifier=identifier) def get_documents(library: data.Library = None) -> typing.List[data.ConversionGraph]: """ """ return __Manager().get_documents(library=library) def get_document(library: data.Library, document_filename: str) -> typing.Union[data.ConversionGraph, typing.NoReturn]: """ """ # TODO: Is this still needed? return __Manager().get_document(library=library, document_filename=document_filename) def create_new_document(library: data.Library) -> data.ConversionGraph: """ """ return __Manager().create_new_document(library=library) def create_from_source(source: data.ConversionGraph) -> data.ConversionGraph: """ """ return __Manager().create_from_source(source=source) def revert(library: data.Library, instance: data.Serializable) -> bool: """ Returns True if the file existed on disk and was successfully reverted. """ return __Manager().revert(library, instance) def find_documents(source_class: str, library: data.Library = None) -> typing.List[data.ConversionGraph]: """ """ # TODO: Is this still needed? return __Manager().find_documents(source_class=source_class, library=library) def find_assembly(assembly_class: str, library: data.Library = None) -> typing.List[data.Target]: """ """ # TODO: Is this still needed? return __Manager().find_assembly(assembly_class=assembly_class, library=library) def register_operator(operator: data.Operator): """ """ __Manager().register_operator(operator=operator) def get_operators() -> typing.List[data.Operator]: """ """ return __Manager().get_operators() def is_operator_id(identifier: str) -> bool: """ """ return __Manager().is_operator_id(identifier=identifier) def delete_document(document: data.ConversionGraph) -> bool: """ """ return __Manager().delete_document(document=document) def get_conversion_manifest(library: data.Library) -> data.ConversionManifest: """ """ return __Manager().get_conversion_manifest(library=library) def get_render_contexts() -> typing.List[str]: """Returns list of registered render contexts.""" return __Manager()._settings.render_contexts[:] def register_render_contexts(context: str) -> None: """Register a render context such as MDL or USD Preview.""" __Manager().register_render_contexts(context=context) def can_show_in_filesystem(document: data.ConversionGraph) -> bool: """Checks if the operating system can display where a document is saved on disk.""" return __Manager().can_show_in_filesystem(document=document) def show_in_filesystem(document: data.ConversionGraph) -> None: """Makes the operating system display where a document is saved on disk.""" return __Manager().show_in_filesystem(document=document) def on_shutdown() -> None: """Makes the operating system display where a document is saved on disk.""" return __Manager().on_shutdown()
44,912
Python
38.60582
254
0.614557
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/service/delegate.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import os import json import subprocess import threading import platform import uuid from ..feature import POLLING from .core import ChangeEvent, IDelegate class Filesystem(IDelegate): def __init__(self, root_directory: str): super(Filesystem, self).__init__() if POLLING: self.__is_polling: bool = False self.__poll_timer: threading.Timer = None self.__poll_data: typing.Dict[str, float] = dict() self.__poll_subscriptions: typing.Dict[uuid.uuid4, typing.Callable[[ChangeEvent], typing.NoReturn]] = dict() self.__pending_write_ids: typing.List[str] = [] self.__pending_delete_ids: typing.List[str] = [] self._root_directory: str = root_directory def __start_polling(self) -> None: if not POLLING: return if self.__is_polling: return self.__is_polling = True # Store current state in self.__poll_data so that __on_timer we only notify of changes since starting to poll self.__poll_data = dict() self.__pending_change_ids = [] identifiers = self.get_ids() for identifier in identifiers: filepath = '{0}/{1}'.format(self._root_directory, identifier) modified_time = os.path.getmtime(filepath) if platform.system() == 'Windows' else os.stat(filepath).st_mtime self.__poll_data[identifier] = modified_time self.__poll_timer = threading.Timer(5, self.__on_timer) self.__poll_timer.start() def __on_timer(self): print('UMM PING') if not POLLING: return if not self.__is_polling: return try: identifiers = self.get_ids() added = [o for o in identifiers if o not in self.__poll_data.keys() and o not in self.__pending_write_ids] removed = [o for o in self.__poll_data.keys() if o not in identifiers and o not in self.__pending_delete_ids] modified_maybe = [o for o in identifiers if o not in added and o not in removed and o not in self.__pending_write_ids] modified = [] for identifier in modified_maybe: filepath = '{0}/{1}'.format(self._root_directory, identifier) modified_time = os.path.getmtime(filepath) if platform.system() == 'Windows' else os.stat(filepath).st_mtime if self.__poll_data[identifier] == modified_time: continue modified.append(identifier) self.__poll_data[identifier] = modified_time for identifier in added: filepath = '{0}/{1}'.format(self._root_directory, identifier) self.__poll_data[identifier] = os.path.getmtime(filepath) if platform.system() == 'Windows' else os.stat(filepath).st_mtime for identifier in removed: del self.__poll_data[identifier] if len(added) + len(modified) + len(removed) > 0: event = ChangeEvent(added=tuple(added), modified=tuple(modified), removed=tuple(removed)) for callbacks in self.__poll_subscriptions.values(): callbacks(event) except Exception as error: print('WARNING: Universal Material Map failed to poll {0} for file changes.\nDetail: {1}'.format(self._root_directory, error)) self.__poll_timer.run() def __stop_polling(self) -> None: if not POLLING: return self.__is_polling = False try: self.__poll_timer.cancel() except: pass self.__poll_data = dict() def can_poll(self) -> bool: if not POLLING: return False return True def start_polling(self): if not POLLING: return self.__start_polling() def stop_polling(self): if not POLLING: return self.__stop_polling() def add_change_subscription(self, callback: typing.Callable[[ChangeEvent], typing.NoReturn]) -> uuid.uuid4: if not POLLING: raise NotImplementedError('Polling feature not enabled.') for key, value in self.__poll_subscriptions.items(): if value == callback: return key key = uuid.uuid4() self.__poll_subscriptions[key] = callback self.start_polling() return key def remove_change_subscription(self, subscription_id: uuid.uuid4) -> None: if not POLLING: raise NotImplementedError('Polling feature not enabled.') if subscription_id in self.__poll_subscriptions.keys(): del self.__poll_subscriptions[subscription_id] if len(self.__poll_subscriptions.keys()) == 0: self.stop_polling() def get_ids(self) -> typing.List[str]: identifiers: typing.List[str] = [] for directory, sub_directories, filenames in os.walk(self._root_directory): for filename in filenames: if not filename.lower().endswith('.json'): continue identifiers.append(filename) break return identifiers def read(self, identifier: str) -> typing.Union[typing.Dict, typing.NoReturn]: if not identifier.lower().endswith('.json'): raise Exception('Invalid identifier: "{0}" does not end with ".json".'.format(identifier)) filepath = '{0}/{1}'.format(self._root_directory, identifier) if os.path.exists(filepath): try: with open(filepath, 'r') as pointer: contents = json.load(pointer) if not isinstance(contents, dict): raise Exception('Not supported: Load of file "{0}" did not resolve to a dictionary. Could be due to reading same file twice too fast.'.format(filepath)) return contents except Exception as error: print('Failed to open file "{0}"'.format(filepath)) raise error return None def write(self, identifier: str, contents: typing.Dict) -> None: if not identifier.lower().endswith('.json'): raise Exception('Invalid identifier: "{0}" does not end with ".json".'.format(identifier)) if not isinstance(contents, dict): raise Exception('Not supported: Argument "contents" is not an instance of dict.') if not os.path.exists(self._root_directory): os.makedirs(self._root_directory) if POLLING: if identifier not in self.__pending_write_ids: self.__pending_write_ids.append(identifier) filepath = '{0}/{1}'.format(self._root_directory, identifier) with open(filepath, 'w') as pointer: json.dump(contents, pointer, indent=4) if POLLING: # Store the modified time so that we don't trigger a notification. We only want notifications when changes are caused by external modifiers. self.__poll_data[identifier] = os.path.getmtime(filepath) if platform.system() == 'Windows' else os.stat(filepath).st_mtime self.__pending_write_ids.remove(identifier) def delete(self, identifier: str) -> None: if not identifier.lower().endswith('.json'): raise Exception('Invalid identifier: "{0}" does not end with ".json".'.format(identifier)) if POLLING: if identifier not in self.__pending_delete_ids: self.__pending_delete_ids.append(identifier) filepath = '{0}/{1}'.format(self._root_directory, identifier) if os.path.exists(filepath): os.remove(filepath) if POLLING: # Remove the item from self.__poll_data so that we don't trigger a notification. We only want notifications when changes are caused by external modifiers. if identifier in self.__poll_data.keys(): del self.__poll_data[identifier] self.__pending_delete_ids.remove(identifier) def can_show_in_store(self, identifier: str) -> bool: filepath = '{0}/{1}'.format(self._root_directory, identifier) return os.path.exists(filepath) def show_in_store(self, identifier: str) -> None: filepath = '{0}/{1}'.format(self._root_directory, identifier) if os.path.exists(filepath): subprocess.Popen(r'explorer /select,"{0}"'.format(filepath.replace('/', '\\'))) class FilesystemManifest(Filesystem): def __init__(self, root_directory: str): super(FilesystemManifest, self).__init__(root_directory=root_directory) def get_ids(self) -> typing.List[str]: identifiers: typing.List[str] = [] for directory, sub_directories, filenames in os.walk(self._root_directory): for filename in filenames: if not filename.lower() == 'conversionmanifest.json': continue identifiers.append(filename) break return identifiers class FilesystemSettings(Filesystem): def __init__(self, root_directory: str): super(FilesystemSettings, self).__init__(root_directory=root_directory) def get_ids(self) -> typing.List[str]: identifiers: typing.List[str] = [] for directory, sub_directories, filenames in os.walk(self._root_directory): for filename in filenames: if not filename.lower() == 'settings.json': continue identifiers.append(filename) break return identifiers
10,456
Python
40.995984
176
0.608072
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/service/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/service/core.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import abc import typing import uuid class ChangeEvent(object): def __init__(self, added: typing.Tuple[str], modified: typing.Tuple[str], removed: typing.Tuple[str]): super(ChangeEvent, self).__init__() self.__added: typing.Tuple[str] = added self.__modified: typing.Tuple[str] = modified self.__removed: typing.Tuple[str] = removed def __str__(self): o = 'omni.universalmaterialmap.core.service.core.ChangeEvent(' o += '\n\tadded: ' o += ', '.join(self.__added) o += '\n\tmodified: ' o += ', '.join(self.__modified) o += '\n\tremoved: ' o += ', '.join(self.__removed) o += '\n)' return o @property def added(self) -> typing.Tuple[str]: return self.__added @property def modified(self) -> typing.Tuple[str]: return self.__modified @property def removed(self) -> typing.Tuple[str]: return self.__removed class IDelegate(metaclass=abc.ABCMeta): """ Interface for an online library database table. """ @abc.abstractmethod def get_ids(self) -> typing.List[str]: """ Returns a list of identifiers. """ raise NotImplementedError @abc.abstractmethod def read(self, identifier: str) -> typing.Dict: """ Returns a JSON dictionary if an item by the given identifier exists - otherwise None """ raise NotImplementedError @abc.abstractmethod def write(self, identifier: str, contents: typing.Dict) -> str: """ Creates or updates an item by using the JSON contents data. """ raise NotImplementedError @abc.abstractmethod def delete(self, identifier: str) -> None: """ Deletes an item by the given identifier if it exists. """ raise NotImplementedError @abc.abstractmethod def can_show_in_store(self, identifier: str) -> bool: """ Deletes an item by the given identifier if it exists. """ raise NotImplementedError @abc.abstractmethod def show_in_store(self, identifier: str) -> None: """ Deletes an item by the given identifier if it exists. """ raise NotImplementedError @abc.abstractmethod def can_poll(self) -> bool: """ States if delegate is able to poll file changes and provide subscription to those changes. """ raise NotImplementedError @abc.abstractmethod def start_polling(self) -> None: """ Starts monitoring files for changes. """ raise NotImplementedError @abc.abstractmethod def stop_polling(self) -> None: """ Stops monitoring files for changes. """ raise NotImplementedError @abc.abstractmethod def add_change_subscription(self, callback: typing.Callable[[ChangeEvent], typing.NoReturn]) -> uuid.uuid4: """ Creates a subscription for file changes in location managed by delegate. """ raise NotImplementedError @abc.abstractmethod def remove_change_subscription(self, subscription_id: uuid.uuid4) -> None: """ Removes the subscription for file changes in location managed by delegate. """ raise NotImplementedError
4,024
Python
34.307017
111
0.657306
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/core/service/resources/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import os import shutil import json import inspect from ...data import FileUtility, Target, ConversionGraph, ConversionManifest def __copy(source_path: str, destination_path: str) -> None: try: shutil.copy(source_path, destination_path) except Exception as error: print('Error installing UMM data. Unable to copy source "{0}" to destination "{1}".\n Details: {2}'.format(source_path, destination_path, error)) raise error def __install_library(source_root: str, destination_root: str) -> None: source_root = source_root.replace('\\', '/') destination_root = destination_root.replace('\\', '/') for directory, sub_directories, filenames in os.walk(source_root): directory = directory.replace('\\', '/') destination_directory = directory.replace(source_root, destination_root) destination_directory_created = os.path.exists(destination_directory) for filename in filenames: if not filename.lower().endswith('.json'): continue source_path = '{0}/{1}'.format(directory, filename) destination_path = '{0}/{1}'.format(destination_directory, filename) if not destination_directory_created: try: os.makedirs(destination_directory) destination_directory_created = True except Exception as error: print('Universal Material Map error installing data. Unable to create directory "{0}".\n Details: {1}'.format(destination_directory, error)) raise error if not os.path.exists(destination_path): __copy(source_path=source_path, destination_path=destination_path) print('Universal Material Map installed "{0}".'.format(destination_path)) continue try: with open(source_path, 'r') as fp: source = FileUtility.FromData(data=json.load(fp)).content except Exception as error: print('Universal Material Map error installing data. Unable to read source "{0}". \n Details: {1}'.format(source_path, error)) raise error try: with open(destination_path, 'r') as fp: destination = FileUtility.FromData(data=json.load(fp)).content except Exception as error: print('Warning: Universal Material Map error installing data. Unable to read destination "{0}". It is assumed that the installed version is more recent than the one attempted to be installed.\n Details: {1}'.format(destination_path, error)) continue if isinstance(source, Target) and isinstance(destination, Target): if source.revision > destination.revision: __copy(source_path=source_path, destination_path=destination_path) print('Universal Material Map installed the more recent revision #{0} of "{1}".'.format(source.revision, destination_path)) continue if isinstance(source, ConversionGraph) and isinstance(destination, ConversionGraph): if source.revision > destination.revision: __copy(source_path=source_path, destination_path=destination_path) print('Universal Material Map installed the more recent revision #{0} of "{1}".'.format(source.revision, destination_path)) continue if isinstance(source, ConversionManifest) and isinstance(destination, ConversionManifest): if source.version_major < destination.version_major: continue if source.version_minor <= destination.version_minor: continue __copy(source_path=source_path, destination_path=destination_path) print('Universal Material Map installed the more recent revision #{0}.{1} of "{2}".'.format(source.version_major, source.version_minor, destination_path)) continue def install() -> None: current_path = inspect.getfile(inspect.currentframe()).replace('\\', '/') current_path = current_path[:current_path.rfind('/')] library_names = [] for o in os.listdir(current_path): path = '{0}/{1}'.format(current_path, o) if os.path.isdir(path) and not o == '__pycache__': library_names.append(o) libraries_directory = os.path.expanduser('~').replace('\\', '/') if not libraries_directory.endswith('/Documents'): # os.path.expanduser() has different behaviour between 2.7 and 3 libraries_directory = '{0}/Documents'.format(libraries_directory) libraries_directory = '{0}/Omniverse'.format(libraries_directory) for library_name in library_names: source_root = '{0}/{1}/UMMLibrary'.format(current_path, library_name) destination_root = '{0}/{1}/UMMLibrary'.format(libraries_directory, library_name) __install_library(source_root=source_root, destination_root=destination_root)
5,935
Python
49.735042
256
0.643134
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/blender/converter.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import sys import traceback import os import re import json import math import bpy import bpy_types from . import get_library, get_value, CORE_MATERIAL_PROPERTIES, create_template, developer_mode, get_template_data_by_shader_node, get_template_data_by_class_name, create_from_template from ..core.converter.core import ICoreConverter, IObjectConverter, IDataConverter from ..core.converter import util from ..core.service import store from ..core.data import Plug, ConversionManifest, DagNode, ConversionGraph, TargetInstance __initialized: bool = False __manifest: ConversionManifest = None def _get_manifest() -> ConversionManifest: if not getattr(sys.modules[__name__], '__manifest'): setattr(sys.modules[__name__], '__manifest', store.get_conversion_manifest(library=get_library())) if developer_mode: manifest: ConversionManifest = getattr(sys.modules[__name__], '__manifest') print('UMM DEBUG: blender.converter._get_manifest(): num entries = "{0}"'.format(len(manifest.conversion_maps))) for conversion_map in manifest.conversion_maps: print('UMM DEBUG: blender.converter._get_manifest(): Entry: graph_id = "{0}", render_context = "{1}"'.format(conversion_map.conversion_graph_id, conversion_map.render_context)) return getattr(sys.modules[__name__], '__manifest') def _get_conversion_graph_impl(source_class: str, render_context: str) -> typing.Union[ConversionGraph, typing.NoReturn]: if developer_mode: print('UMM DEBUG: blender.converter._get_conversion_graph_impl(source_class="{0}", render_context="{1}")'.format(source_class, render_context)) for conversion_map in _get_manifest().conversion_maps: if not conversion_map.render_context == render_context: if developer_mode: print('UMM DEBUG: blender.converter._get_conversion_graph_impl: conversion_map.render_context "{0}" != "{1}")'.format(conversion_map.render_context, render_context)) continue if not conversion_map.conversion_graph: if developer_mode: print('UMM DEBUG: blender.converter._get_conversion_graph_impl: conversion_map.conversion_graph "{0}")'.format(conversion_map.conversion_graph)) continue if not conversion_map.conversion_graph.source_node: if developer_mode: print('UMM DEBUG: blender.converter._get_conversion_graph_impl: conversion_map.source_node "{0}")'.format(conversion_map.conversion_graph.source_node)) continue if not conversion_map.conversion_graph.source_node.target.root_node.class_name == source_class: if developer_mode: print('UMM DEBUG: blender.converter._get_conversion_graph_impl: conversion_map.conversion_graph.source_node.target.root_node.class_name "{0}" != "{1}")'.format(conversion_map.conversion_graph.source_node.target.root_node.class_name, source_class)) continue if developer_mode: print('UMM DEBUG: blender.converter._get_conversion_graph_impl: found match "{0}")'.format(conversion_map.conversion_graph.filename)) return conversion_map.conversion_graph if developer_mode: print('UMM DEBUG: blender.converter._get_conversion_graph_impl: found no match!)') return None def _instance_to_output_entity(graph: ConversionGraph, instance: object) -> TargetInstance: if developer_mode: print('_instance_to_output_entity') for output in graph.source_node.outputs: if output.name == 'node_id_output': continue if util.can_set_plug_value(instance=instance, plug=output): util.set_plug_value(instance=instance, plug=output) else: print('UMM Warning: Unable to set output plug "{0}"... using default value of "{1}"'.format(output.name, output.default_value)) output.value = output.default_value return graph.get_output_entity() def _data_to_output_entity(graph: ConversionGraph, data: typing.List[typing.Tuple[str, typing.Any]]) -> TargetInstance: for output in graph.source_node.outputs: if output.name == 'node_id_output': continue o = [o for o in data if o[0] == output.name] if len(o): output.value = o[0][1] else: output.value = output.default_value return graph.get_output_entity() def _instance_to_data(instance: object, graph: ConversionGraph) -> typing.List[typing.Tuple[str, typing.Any]]: target_instance = _instance_to_output_entity(graph=graph, instance=instance) if developer_mode: print('_instance_to_data') print('\ttarget_instance.target.store_id', target_instance.target.store_id) # Compute target attribute values attribute_data = [(util.TARGET_CLASS_IDENTIFIER, target_instance.target.root_node.class_name)] for plug in target_instance.inputs: if not plug.input: continue if developer_mode: print('\t{} is invalid: {}'.format(plug.name, plug.is_invalid)) if plug.is_invalid and isinstance(plug.parent, DagNode): plug.parent.compute() if developer_mode: print('\t{} computed value = {}'.format(plug.name, plug.computed_value)) attribute_data.append((plug.name, plug.computed_value)) return attribute_data def _to_convertible_instance(instance: object, material: bpy.types.Material = None) -> object: if developer_mode: print('_to_convertible_instance', type(instance)) if material is None: if isinstance(instance, bpy.types.Material): material = instance else: for m in bpy.data.materials: if not m.use_nodes: continue if not len([o for o in m.node_tree.nodes if o == instance]): continue material = m break if material is None: return instance if not material.use_nodes: return material if instance == material: # Find the Surface Shader. for link in material.node_tree.links: if not isinstance(link, bpy.types.NodeLink): continue if not isinstance(link.to_node, bpy.types.ShaderNodeOutputMaterial): continue if not link.to_socket.name == 'Surface': continue result = _to_convertible_instance(instance=link.from_node, material=material) if result is not None: return result # No surface shader found - return instance return instance if isinstance(instance, bpy.types.ShaderNodeAddShader): for link in material.node_tree.links: if not isinstance(link, bpy.types.NodeLink): continue if not link.to_node == instance: continue # if not link.to_socket.name == 'Shader': # continue result = _to_convertible_instance(instance=link.from_node, material=material) if result is not None: return result # if isinstance(instance, bpy.types.ShaderNodeBsdfGlass): # return instance # if isinstance(instance, bpy.types.ShaderNodeBsdfGlossy): # return instance if isinstance(instance, bpy.types.ShaderNodeBsdfPrincipled): return instance # if isinstance(instance, bpy.types.ShaderNodeBsdfRefraction): # return instance # if isinstance(instance, bpy.types.ShaderNodeBsdfTranslucent): # return instance # if isinstance(instance, bpy.types.ShaderNodeBsdfTransparent): # return instance # if isinstance(instance, bpy.types.ShaderNodeEeveeSpecular): # return instance # if isinstance(instance, bpy.types.ShaderNodeEmission): # return instance # if isinstance(instance, bpy.types.ShaderNodeSubsurfaceScattering): # return instance return None class CoreConverter(ICoreConverter): def __init__(self): super(CoreConverter, self).__init__() def get_conversion_manifest(self) -> typing.List[typing.Tuple[str, str]]: """ Returns data indicating what source class can be converted to a render context. Example: [('lambert', 'MDL'), ('blinn', 'MDL'),] """ output = [] for conversion_map in _get_manifest().conversion_maps: if not conversion_map.render_context: continue if not conversion_map.conversion_graph: continue if not conversion_map.conversion_graph.source_node: continue output.append((conversion_map.conversion_graph.source_node.target.root_node.class_name, conversion_map.render_context)) return output class ObjectConverter(CoreConverter, IObjectConverter): """ """ MATERIAL_CLASS = 'bpy.types.Material' SHADER_NODES = [ 'bpy.types.ShaderNodeBsdfGlass', 'bpy.types.ShaderNodeBsdfGlossy', 'bpy.types.ShaderNodeBsdfPrincipled', 'bpy.types.ShaderNodeBsdfRefraction', 'bpy.types.ShaderNodeBsdfTranslucent', 'bpy.types.ShaderNodeBsdfTransparent', 'bpy.types.ShaderNodeEeveeSpecular', 'bpy.types.ShaderNodeEmission', 'bpy.types.ShaderNodeSubsurfaceScattering', ] def can_create_instance(self, class_name: str) -> bool: """ Returns true if worker can generate an object of the given class name. """ if class_name == ObjectConverter.MATERIAL_CLASS: return True return class_name in ObjectConverter.SHADER_NODES def create_instance(self, class_name: str, name: str = 'material') -> object: """ Creates an object of the given class name. """ material = bpy.data.materials.new(name=name) if class_name in ObjectConverter.SHADER_NODES: material.use_nodes = True return material def can_set_plug_value(self, instance: object, plug: Plug) -> bool: """ Returns true if worker can set the plug's value given the instance and its attributes. """ if plug.input: return False if isinstance(instance, bpy.types.Material): for o in CORE_MATERIAL_PROPERTIES: if o[0] == plug.name: return hasattr(instance, plug.name) return False if isinstance(instance, bpy_types.ShaderNode): return len([o for o in instance.inputs if o.name == plug.name]) == 1 return False def set_plug_value(self, instance: object, plug: Plug) -> typing.NoReturn: """ Sets the plug's value given the value of the instance's attribute named the same as the plug. """ if isinstance(instance, bpy.types.Material): plug.value = getattr(instance, plug.name) if developer_mode: print('set_plug_value') print('\tinstance', type(instance)) print('\tname', plug.name) print('\tvalue', plug.value) return inputs = [o for o in instance.inputs if o.name == plug.name] if not len(inputs) == 1: return plug.value = get_value(socket=inputs[0]) if developer_mode: # print('set_plug_value') # print('\tinstance', type(instance)) # print('\tname', plug.name) # print('\tvalue', plug.value) print('\tset_plug_value: {} = {}'.format(plug.name, plug.value)) def can_set_instance_attribute(self, instance: object, name: str): """ Resolves if worker can set an attribute by the given name on the instance. """ return False def set_instance_attribute(self, instance: object, name: str, value: typing.Any) -> typing.NoReturn: """ Sets the named attribute on the instance to the value. """ raise NotImplementedError() def can_convert_instance(self, instance: object, render_context: str) -> bool: """ Resolves if worker can convert the instance to another object given the render_context. """ return False def convert_instance_to_instance(self, instance: object, render_context: str) -> typing.Any: """ Converts the instance to another object given the render_context. """ raise NotImplementedError() def can_convert_instance_to_data(self, instance: object, render_context: str) -> bool: """ Resolves if worker can convert the instance to another object given the render_context. """ node = _to_convertible_instance(instance=instance) if node is not None and not node == instance: if developer_mode: print('Found graph node to use instead of bpy.types.Material: {0}'.format(type(node))) instance = node template, template_map, template_shader_name, material = get_template_data_by_shader_node(shader_node=instance) if template is None: class_name = '{0}.{1}'.format(instance.__class__.__module__, instance.__class__.__name__) conversion_graph = _get_conversion_graph_impl(source_class=class_name, render_context=render_context) if not conversion_graph: return False try: destination_target_instance = _instance_to_output_entity(graph=conversion_graph, instance=instance) except Exception as error: print('Warning: Unable to get destination assembly using document "{0}".\nDetails: {1}'.format(conversion_graph.filename, error)) return False return destination_target_instance is not None else: conversion_graph = _get_conversion_graph_impl(source_class=template_shader_name, render_context=render_context) return conversion_graph is not None def convert_instance_to_data(self, instance: object, render_context: str) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ node = _to_convertible_instance(instance=instance) if node is not None and not node == instance: if developer_mode: print('Found graph node to use instead of bpy.types.Material: {0}'.format(type(node))) instance = node template, template_map, template_shader_name, material = get_template_data_by_shader_node(shader_node=instance) if template is None: class_name = '{0}.{1}'.format(instance.__class__.__module__, instance.__class__.__name__) conversion_graph = _get_conversion_graph_impl(source_class=class_name, render_context=render_context) return _instance_to_data(instance=instance, graph=conversion_graph) else: conversion_graph = _get_conversion_graph_impl(source_class=template_shader_name, render_context=render_context) if developer_mode: print('conversion_graph', conversion_graph.filename) # set plug values on conversion_graph.source_node.outputs for output in conversion_graph.source_node.outputs: if output.name == 'node_id_output': continue if developer_mode: print('output', output.name) internal_node = None for a in conversion_graph.source_node.target.nodes: for b in a.outputs: if output.id == b.id: internal_node = a break if internal_node is not None: break if internal_node is None: raise NotImplementedError(f"No internal node found for {output.name}") map_definition = None for o in template_map['maps']: if o['blender_node'] == internal_node.id and o['blender_socket'] == output.name: map_definition = o break if map_definition is None: raise NotImplementedError(f"No map definition found for {output.name}") if developer_mode: print('map_definition', map_definition['blender_node']) if map_definition['blender_node'] == '': output.value = output.default_value if developer_mode: print('output.value', output.value) continue for shader_node in material.node_tree.nodes: if not shader_node.name == map_definition['blender_node']: continue if isinstance(shader_node, bpy.types.ShaderNodeTexImage): if map_definition['blender_socket'] == 'image': if shader_node.image and (shader_node.image.source == 'FILE' or shader_node.image.source == 'TILED'): print(f'UMM: image.filepath: "{shader_node.image.filepath}"') print(f'UMM: image.source: "{shader_node.image.source}"') print(f'UMM: image.file_format: "{shader_node.image.file_format}"') value = shader_node.image.filepath if (shader_node.image.source == 'TILED'): # Find all numbers in the path. numbers = re.findall('[0-9]+', value) if (len(numbers) > 0): # Get the string representation of the last number. num_str = str(numbers[-1]) # Replace the number substring with '<UDIM>'. split_items = value.rsplit(num_str, 1) if (len(split_items) == 2): value = split_items[0] + '<UDIM>' + split_items[1] try: if value is None or value == '': file_format = shader_node.image.file_format if file_format.lower() == 'open_exr': file_format = 'exr' value = f'{shader_node.image.name}.{file_format}' output.value = [value, shader_node.image.colorspace_settings.name] else: output.value = [os.path.abspath(bpy.path.abspath(value)), shader_node.image.colorspace_settings.name] except Exception as error: print('Warning: Universal Material Map: Unable to evaluate absolute file path of texture "{0}". Detail: {1}'.format(shader_node.image.filepath, error)) output.value = ['', 'raw'] print(f'UMM: output.value: "{output.value}"') else: if developer_mode: print('setting default value for output.value') if not shader_node.image: print('\tshader_node.image == None') else: print('\tshader_node.image.source == {}'.format(shader_node.image.source)) output.value = ['', 'raw'] if developer_mode: print('output.value', output.value) break raise NotImplementedError(f"No support for bpy.types.ShaderNodeTexImage {map_definition['blender_socket']}") if isinstance(shader_node, bpy.types.ShaderNodeBsdfPrincipled): socket: bpy.types.NodeSocketStandard = shader_node.inputs[map_definition['blender_socket']] output.value = socket.default_value if developer_mode: print('output.value', output.value) break if isinstance(shader_node, bpy.types.ShaderNodeGroup): if map_definition['blender_socket'] not in shader_node.inputs.keys(): if developer_mode: print(f'{map_definition["blender_socket"]} not in shader_node.inputs.keys()') break socket: bpy.types.NodeSocketStandard = shader_node.inputs[map_definition['blender_socket']] output.value = socket.default_value if developer_mode: print('output.value', output.value) break if isinstance(shader_node, bpy.types.ShaderNodeMapping): socket: bpy.types.NodeSocketStandard = shader_node.inputs[map_definition['blender_socket']] value = socket.default_value if output.name == 'Rotation': value = [ math.degrees(value[0]), math.degrees(value[1]), math.degrees(value[2]) ] output.value = value if developer_mode: print('output.value', output.value) break # compute to target_instance for output target_instance = conversion_graph.get_output_entity() if developer_mode: print('_instance_to_data') print('\ttarget_instance.target.store_id', target_instance.target.store_id) # Compute target attribute values attribute_data = [(util.TARGET_CLASS_IDENTIFIER, target_instance.target.root_node.class_name)] for plug in target_instance.inputs: if not plug.input: continue if developer_mode: print('\t{} is invalid: {}'.format(plug.name, plug.is_invalid)) if plug.is_invalid and isinstance(plug.parent, DagNode): plug.parent.compute() if developer_mode: print('\t{} computed value = {}'.format(plug.name, plug.computed_value)) value = plug.computed_value if plug.internal_value_type == 'bool': value = True if value else False attribute_data.append((plug.name, value)) return attribute_data def can_convert_attribute_values(self, instance: object, render_context: str, destination: object) -> bool: """ Resolves if the instance's attribute values can be converted and set on the destination object's attributes. """ raise NotImplementedError() def convert_attribute_values(self, instance: object, render_context: str, destination: object) -> typing.NoReturn: """ Attribute values are converted and set on the destination object's attributes. """ raise NotImplementedError() def can_apply_data_to_instance(self, source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> bool: """ Resolves if worker can convert the instance to another object given the render_context. """ if developer_mode: print('can_apply_data_to_instance()') if not isinstance(instance, bpy.types.Material): if developer_mode: print('can_apply_data_to_instance: FALSE - instance not bpy.types.Material') return False if not render_context == 'Blender': if developer_mode: print('can_apply_data_to_instance: FALSE - render_context not "Blender"') return False conversion_graph = _get_conversion_graph_impl(source_class=source_class_name, render_context=render_context) if not conversion_graph: if developer_mode: print('can_apply_data_to_instance: FALSE - conversion_graph is None') return False if developer_mode: print(f'conversion_graph {conversion_graph.filename}') try: destination_target_instance = _data_to_output_entity(graph=conversion_graph, data=source_data) except Exception as error: print('Warning: Unable to get destination assembly using document "{0}".\nDetails: {1}'.format(conversion_graph.filename, error)) return False if developer_mode: if destination_target_instance is None: print('destination_target_instance is None') elif destination_target_instance is None: print('destination_target_instance.target is None') else: print('destination_target_instance.target is not None') if destination_target_instance is None or destination_target_instance.target is None: return False if developer_mode: print(f'num destination_target_instance.target.nodes: {len(destination_target_instance.target.nodes)}') if len(destination_target_instance.target.nodes) < 2: return True template, template_map = get_template_data_by_class_name(class_name=destination_target_instance.target.root_node.class_name) if developer_mode: print(f'return {template is not None}') return template is not None def apply_data_to_instance(self, source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> None: """ Implementation requires that `instance` is type `bpy.types.Material`. """ if developer_mode: print('apply_data_to_instance()') if not isinstance(instance, bpy.types.Material): raise Exception('instance type not supported', type(instance)) if not render_context == 'Blender': raise Exception('render_context not supported', render_context) conversion_graph = _get_conversion_graph_impl(source_class=source_class_name, render_context=render_context) # This only works for Blender import of MDL/USDPreview. Blender export would need to use convert_instance_to_data(). destination_target_instance = _data_to_output_entity(graph=conversion_graph, data=source_data) material: bpy.types.Material = instance # Make sure we're using nodes material.use_nodes = True # Remove existing nodes - we're starting from scratch - assuming Blender import to_delete = [o for o in material.node_tree.nodes] while len(to_delete): material.node_tree.nodes.remove(to_delete.pop()) if len(destination_target_instance.target.nodes) < 2: # Create base graph output_node = material.node_tree.nodes.new('ShaderNodeOutputMaterial') output_node.location = [300.0, 300.0] bsdf_node = material.node_tree.nodes.new('ShaderNodeBsdfPrincipled') bsdf_node.location = [0.0, 300.0] material.node_tree.links.new(bsdf_node.outputs[0], output_node.inputs[0]) node_cache = dict() node_location = [-500, 300] # Create graph if texture value for plug in destination_target_instance.inputs: if not plug.input: continue if isinstance(plug.computed_value, list) or isinstance(plug.computed_value, tuple): if len(plug.computed_value) == 2 and isinstance(plug.computed_value[0], str) and isinstance(plug.computed_value[1], str): key = '{0}|{1}'.format(plug.computed_value[0], plug.computed_value[1]) if key in node_cache.keys(): node = node_cache[key] else: try: path = plug.computed_value[0] if not path == '': node = material.node_tree.nodes.new('ShaderNodeTexImage') path = plug.computed_value[0] if '<UDIM>' in path: pattern = path.replace('\\', '/') pattern = pattern.replace('<UDIM>', '[0-9][0-9][0-9][0-9]') directory = pattern[:pattern.rfind('/') + 1] pattern = pattern.replace(directory, '') image_set = False for item in os.listdir(directory): if re.match(pattern, item): tile_path = '{}{}'.format(directory, item) if not os.path.isfile(tile_path): continue if not image_set: node.image = bpy.data.images.load(tile_path) node.image.source = 'TILED' image_set = True continue tile_indexes = re.findall('[0-9][0-9][0-9][0-9]', item) node.image.tiles.new(int(tile_indexes[-1])) else: node.image = bpy.data.images.load(path) node.image.colorspace_settings.name = plug.computed_value[1] else: continue except Exception as error: print('Warning: UMM failed to properly setup a ShaderNodeTexImage. Details: {0}\n{1}'.format(error, traceback.format_exc())) continue node_cache[key] = node node.location = node_location node_location[1] -= 300 bsdf_input = [o for o in bsdf_node.inputs if o.name == plug.name][0] if plug.name == 'Metallic': separate_node = None for link in material.node_tree.links: if link.from_node == node and link.to_node.__class__.__name__ == 'ShaderNodeSeparateRGB': separate_node = link.to_node break if separate_node is None: separate_node = material.node_tree.nodes.new('ShaderNodeSeparateRGB') separate_node.location = [node.location[0] + 250, node.location[1]] material.node_tree.links.new(node.outputs[0], separate_node.inputs[0]) material.node_tree.links.new(separate_node.outputs[2], bsdf_input) elif plug.name == 'Roughness': separate_node = None for link in material.node_tree.links: if link.from_node == node and link.to_node.__class__.__name__ == 'ShaderNodeSeparateRGB': separate_node = link.to_node break if separate_node is None: separate_node = material.node_tree.nodes.new('ShaderNodeSeparateRGB') separate_node.location = [node.location[0] + 250, node.location[1]] material.node_tree.links.new(node.outputs[0], separate_node.inputs[0]) material.node_tree.links.new(separate_node.outputs[1], bsdf_input) elif plug.name == 'Normal': normal_node = None for link in material.node_tree.links: if link.from_node == node and link.to_node.__class__.__name__ == 'ShaderNodeNormalMap': normal_node = link.to_node break if normal_node is None: normal_node = material.node_tree.nodes.new('ShaderNodeNormalMap') normal_node.location = [node.location[0] + 250, node.location[1]] material.node_tree.links.new(node.outputs[0], normal_node.inputs[1]) material.node_tree.links.new(normal_node.outputs[0], bsdf_input) else: material.node_tree.links.new(node.outputs[0], bsdf_input) continue # Set Value blender_inputs = [o for o in bsdf_node.inputs if o.name == plug.name] if len(blender_inputs) == 0: for property_name, property_object in bsdf_node.rna_type.properties.items(): if not property_name == plug.name: continue if property_object.is_readonly: break try: setattr(bsdf_node, property_name, plug.computed_value) except Exception as error: print('Warning: Universal Material Map: Unexpected error when setting property "{0}" to value "{1}": "{2}"'.format(property_name, plug.computed_value, error)) else: if isinstance(blender_inputs[0], bpy.types.NodeSocketShader): continue try: blender_inputs[0].default_value = plug.computed_value except Exception as error: print('Warning: Universal Material Map: Unexpected error when setting input "{0}" to value "{1}": "{2}"'.format(plug.name, plug.computed_value, error)) return if developer_mode: print(f'TEMPLATE CREATION BASED ON {destination_target_instance.target.root_node.class_name}') # find template to use template, template_map = get_template_data_by_class_name(class_name=destination_target_instance.target.root_node.class_name) if developer_mode: print(f"TEMPLATE NAME {template['name']}") # create graph create_from_template(material=material, template=template) # set attributes use_albedo_map = False use_normal_map = False use_detail_normal_map = False use_emission_map = False for input_plug in destination_target_instance.inputs: # if developer_mode: # print('input_plug', input_plug.name) internal_node = None for a in destination_target_instance.target.nodes: for b in a.inputs: if input_plug.id == b.id: internal_node = a break if internal_node is not None: break if internal_node is None: raise NotImplementedError(f"No internal node found for {input_plug.name}") map_definition = None for o in template_map['maps']: if o['blender_node'] == internal_node.id and o['blender_socket'] == input_plug.name: map_definition = o break if map_definition is None: raise NotImplementedError(f"No map definition found for {internal_node.id} {input_plug.name}") for shader_node in material.node_tree.nodes: if not shader_node.name == map_definition['blender_node']: continue # if developer_mode: # print(f'node: {shader_node.name}') if isinstance(shader_node, bpy.types.ShaderNodeTexImage): if map_definition['blender_socket'] == 'image': # if developer_mode: # print(f'\tbpy.types.ShaderNodeTexImage: path: {input_plug.computed_value[0]}') # print(f'\tbpy.types.ShaderNodeTexImage: colorspace: {input_plug.computed_value[1]}') path = input_plug.computed_value[0] if not path == '': if '<UDIM>' in path: pattern = path.replace('\\', '/') pattern = pattern.replace('<UDIM>', '[0-9][0-9][0-9][0-9]') directory = pattern[:pattern.rfind('/') + 1] pattern = pattern.replace(directory, '') image_set = False for item in os.listdir(directory): if re.match(pattern, item): tile_path = '{}{}'.format(directory, item) if not os.path.isfile(tile_path): continue if not image_set: shader_node.image = bpy.data.images.load(tile_path) shader_node.image.source = 'TILED' image_set = True continue tile_indexes = re.findall('[0-9][0-9][0-9][0-9]', item) shader_node.image.tiles.new(int(tile_indexes[-1])) else: shader_node.image = bpy.data.images.load(path) if map_definition['blender_node'] == 'Albedo Map': use_albedo_map = True if map_definition['blender_node'] == 'Normal Map': use_normal_map = True if map_definition['blender_node'] == 'Detail Normal Map': use_detail_normal_map = True if map_definition['blender_node'] == 'Emissive Map': use_emission_map = True shader_node.image.colorspace_settings.name = input_plug.computed_value[1] continue raise NotImplementedError( f"No support for bpy.types.ShaderNodeTexImage {map_definition['blender_socket']}") if isinstance(shader_node, bpy.types.ShaderNodeBsdfPrincipled): blender_inputs = [o for o in shader_node.inputs if o.name == input_plug.name] if len(blender_inputs) == 0: for property_name, property_object in shader_node.rna_type.properties.items(): if not property_name == input_plug.name: continue if property_object.is_readonly: break try: setattr(shader_node, property_name, input_plug.computed_value) except Exception as error: print('Warning: Universal Material Map: Unexpected error when setting property "{0}" to value "{1}": "{2}"'.format(property_name, input_plug.computed_value, error)) else: if isinstance(blender_inputs[0], bpy.types.NodeSocketShader): continue try: blender_inputs[0].default_value = input_plug.computed_value except Exception as error: print('Warning: Universal Material Map: Unexpected error when setting input "{0}" to value "{1}": "{2}"'.format(input_plug.name, input_plug.computed_value, error)) continue if isinstance(shader_node, bpy.types.ShaderNodeGroup): blender_inputs = [o for o in shader_node.inputs if o.name == input_plug.name] if len(blender_inputs) == 0: for property_name, property_object in shader_node.rna_type.properties.items(): if not property_name == input_plug.name: continue if property_object.is_readonly: break try: setattr(shader_node, property_name, input_plug.computed_value) except Exception as error: print('Warning: Universal Material Map: Unexpected error when setting property "{0}" to value "{1}": "{2}"'.format(property_name, input_plug.computed_value, error)) else: if isinstance(blender_inputs[0], bpy.types.NodeSocketShader): continue try: blender_inputs[0].default_value = input_plug.computed_value except Exception as error: print('Warning: Universal Material Map: Unexpected error when setting input "{0}" to value "{1}": "{2}"'.format(input_plug.name, input_plug.computed_value, error)) continue if isinstance(shader_node, bpy.types.ShaderNodeMapping): blender_inputs = [o for o in shader_node.inputs if o.name == input_plug.name] value = input_plug.computed_value if input_plug.name == 'Rotation': value[0] = math.radians(value[0]) value[1] = math.radians(value[1]) value[2] = math.radians(value[2]) if len(blender_inputs) == 0: for property_name, property_object in shader_node.rna_type.properties.items(): if not property_name == input_plug.name: continue if property_object.is_readonly: break try: setattr(shader_node, property_name, value) except Exception as error: print('Warning: Universal Material Map: Unexpected error when setting property "{0}" to value "{1}": "{2}"'.format(property_name, input_plug.computed_value, error)) else: if isinstance(blender_inputs[0], bpy.types.NodeSocketShader): continue try: blender_inputs[0].default_value = value except Exception as error: print('Warning: Universal Material Map: Unexpected error when setting input "{0}" to value "{1}": "{2}"'.format(input_plug.name, input_plug.computed_value, error)) continue # UX assist with special attributes for shader_node in material.node_tree.nodes: if shader_node.name == 'OmniPBR Compute' and isinstance(shader_node, bpy.types.ShaderNodeGroup): shader_node.inputs['Use Albedo Map'].default_value = 1 if use_albedo_map else 0 shader_node.inputs['Use Normal Map'].default_value = 1 if use_normal_map else 0 shader_node.inputs['Use Detail Normal Map'].default_value = 1 if use_detail_normal_map else 0 shader_node.inputs['Use Emission Map'].default_value = 1 if use_emission_map else 0 break class DataConverter(CoreConverter, IDataConverter): """ """ def can_convert_data_to_data(self, class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> bool: """ Resolves if worker can convert the given class and source_data to another class and target data. """ conversion_graph = _get_conversion_graph_impl(source_class=class_name, render_context=render_context) if not conversion_graph: return False try: destination_target_instance = _data_to_output_entity(graph=conversion_graph, data=source_data) except Exception as error: print('Warning: Unable to get destination assembly using document "{0}".\nDetails: {1}'.format(conversion_graph.filename, error)) return False return destination_target_instance is not None def convert_data_to_data(self, class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ if developer_mode: print('UMM DEBUG: DataConverter.convert_data_to_data()') print('\tclass_name="{0}"'.format(class_name)) print('\trender_context="{0}"'.format(render_context)) print('\tsource_data=[') for o in source_data: if o[1] == '': print('\t\t("{0}", ""),'.format(o[0])) continue print('\t\t("{0}", {1}),'.format(o[0], o[1])) print('\t]') conversion_graph = _get_conversion_graph_impl(source_class=class_name, render_context=render_context) destination_target_instance = _data_to_output_entity(graph=conversion_graph, data=source_data) attribute_data = [(util.TARGET_CLASS_IDENTIFIER, destination_target_instance.target.root_node.class_name)] for plug in destination_target_instance.inputs: if not plug.input: continue if plug.is_invalid and isinstance(plug.parent, DagNode): plug.parent.compute() attribute_data.append((plug.name, plug.computed_value)) return attribute_data class OT_InstanceToDataConverter(bpy.types.Operator): bl_idname = 'universalmaterialmap.instance_to_data_converter' bl_label = 'Universal Material Map Converter Operator' bl_description = 'Universal Material Map Converter' def execute(self, context): print('Conversion Operator: execute') # Get object by name: bpy.data.objects['Cube'] # Get material by name: bpy.data.materials['MyMaterial'] # node = [o for o in bpy.context.active_object.active_material.node_tree.nodes if o.select][0] print('selected_node', bpy.context.active_object, type(bpy.context.active_object)) # print('\n'.join(dir(bpy.context.active_object))) material_slot: bpy.types.MaterialSlot # https://docs.blender.org/api/current/bpy.types.MaterialSlot.html?highlight=materialslot#bpy.types.MaterialSlot for material_slot in bpy.context.active_object.material_slots: material: bpy.types.Material = material_slot.material if material.node_tree: for node in material.node_tree.nodes: if isinstance(node, bpy.types.ShaderNodeOutputMaterial): for input in node.inputs: if not input.type == 'SHADER': continue if not input.is_linked: continue for link in input.links: if not isinstance(link, bpy.types.NodeLink): continue if not link.is_valid: continue instance = link.from_node for render_context in ['MDL', 'USDPreview']: if util.can_convert_instance_to_data(instance=instance, render_context=render_context): util.convert_instance_to_data(instance=instance, render_context=render_context) else: print('Information: Universal Material Map: Not able to convert instance "{0}" to data with render context "{1}"'.format(instance, render_context)) else: instance = material for render_context in ['MDL', 'USDPreview']: if util.can_convert_instance_to_data(instance=instance, render_context=render_context): util.convert_instance_to_data(instance=instance, render_context=render_context) else: print('Information: Universal Material Map: Not able to convert instance "{0}" to data with render context "{1}"'.format(instance, render_context)) return {'FINISHED'} class OT_DataToInstanceConverter(bpy.types.Operator): bl_idname = 'universalmaterialmap.data_to_instance_converter' bl_label = 'Universal Material Map Converter Operator' bl_description = 'Universal Material Map Converter' def execute(self, context): render_context = 'Blender' source_class = 'OmniPBR.mdl|OmniPBR' sample_data = [ ('diffuse_color_constant', (0.800000011920929, 0.800000011920929, 0.800000011920929)), ('diffuse_texture', ''), ('reflection_roughness_constant', 0.4000000059604645), ('reflectionroughness_texture', ''), ('metallic_constant', 0.0), ('metallic_texture', ''), ('specular_level', 0.5), ('enable_emission', True), ('emissive_color', (0.0, 0.0, 0.0)), ('emissive_color_texture', ''), ('emissive_intensity', 1.0), ('normalmap_texture', ''), ('enable_opacity', True), ('opacity_constant', 1.0), ] if util.can_convert_data_to_data(class_name=source_class, render_context=render_context, source_data=sample_data): converted_data = util.convert_data_to_data(class_name=source_class, render_context=render_context, source_data=sample_data) destination_class = converted_data[0][1] if util.can_create_instance(class_name=destination_class): instance = util.create_instance(class_name=destination_class) print('instance "{0}".'.format(instance)) temp = converted_data[:] while len(temp): item = temp.pop(0) property_name = item[0] property_value = item[1] if util.can_set_instance_attribute(instance=instance, name=property_name): util.set_instance_attribute(instance=instance, name=property_name, value=property_value) else: print('Cannot create instance from "{0}".'.format(source_class)) return {'FINISHED'} class OT_DataToDataConverter(bpy.types.Operator): bl_idname = 'universalmaterialmap.data_to_data_converter' bl_label = 'Universal Material Map Converter Operator' bl_description = 'Universal Material Map Converter' def execute(self, context): render_context = 'Blender' source_class = 'OmniPBR.mdl|OmniPBR' sample_data = [ ('diffuse_color_constant', (0.800000011920929, 0.800000011920929, 0.800000011920929)), ('diffuse_texture', ''), ('reflection_roughness_constant', 0.4000000059604645), ('reflectionroughness_texture', ''), ('metallic_constant', 0.0), ('metallic_texture', ''), ('specular_level', 0.5), ('enable_emission', True), ('emissive_color', (0.0, 0.0, 0.0)), ('emissive_color_texture', ''), ('emissive_intensity', 1.0), ('normalmap_texture', ''), ('enable_opacity', True), ('opacity_constant', 1.0), ] if util.can_convert_data_to_data(class_name=source_class, render_context=render_context, source_data=sample_data): converted_data = util.convert_data_to_data(class_name=source_class, render_context=render_context, source_data=sample_data) print('converted_data:', converted_data) else: print('UMM Failed to convert data. util.can_convert_data_to_data() returned False') return {'FINISHED'} class OT_ApplyDataToInstance(bpy.types.Operator): bl_idname = 'universalmaterialmap.apply_data_to_instance' bl_label = 'Universal Material Map Apply Data To Instance Operator' bl_description = 'Universal Material Map Converter' def execute(self, context): if not bpy.context: return {'FINISHED'} if not bpy.context.active_object: return {'FINISHED'} if not bpy.context.active_object.active_material: return {'FINISHED'} instance = bpy.context.active_object.active_material render_context = 'Blender' source_class = 'OmniPBR.mdl|OmniPBR' sample_data = [ ('albedo_add', 0.02), # Adds a constant value to the diffuse color ('albedo_desaturation', 0.19999999), # Desaturates the diffuse color ('ao_texture', ('', 'raw')), ('ao_to_diffuse', 1), # Controls the amount of ambient occlusion multiplied into the diffuse color channel ('bump_factor', 10), # Strength of normal map ('diffuse_color_constant', (0.800000011920929, 0.800000011920929, 0.800000011920929)), ('diffuse_texture', ('D:/Blender_GTC_2021/Marbles/assets/standalone/A_bumper/textures/play_bumper/blue/play_bumperw_albedo.png', 'sRGB')), ('diffuse_tint', (0.96202534, 0.8118357, 0.8118357)), # When enabled, this color value is multiplied over the final albedo color ('enable_emission', 0), ('enable_ORM_texture', 1), ('metallic_constant', 1), ('metallic_texture', ('', 'raw')), ('metallic_texture_influence', 1), ('normalmap_texture', ('D:/Blender_GTC_2021/Marbles/assets/standalone/A_bumper/textures/play_bumper/blue/play_bumperw_normal.png', 'raw')), ('ORM_texture', ('D:/Blender_GTC_2021/Marbles/assets/standalone/A_bumper/textures/play_bumper/blue/play_bumperw_orm.png', 'raw')), ('reflection_roughness_constant', 1), # Higher roughness values lead to more blurry reflections ('reflection_roughness_texture_influence', 1), # Blends between the constant value and the lookup of the roughness texture ('reflectionroughness_texture', ('', 'raw')), ('texture_rotate', 45), ('texture_scale', (2, 2)), ('texture_translate', (0.1, 0.9)), ] if util.can_apply_data_to_instance(source_class_name=source_class, render_context=render_context, source_data=sample_data, instance=instance): util.apply_data_to_instance(source_class_name=source_class, render_context=render_context, source_data=sample_data, instance=instance) else: print('UMM Failed to convert data. util.can_convert_data_to_data() returned False') return {'FINISHED'} class OT_CreateTemplateOmniPBR(bpy.types.Operator): bl_idname = 'universalmaterialmap.create_template_omnipbr' bl_label = 'Convert to OmniPBR Graph' bl_description = 'Universal Material Map Converter' def execute(self, context): if not bpy.context: return {'FINISHED'} if not bpy.context.active_object: return {'FINISHED'} if not bpy.context.active_object.active_material: return {'FINISHED'} create_template(source_class='OmniPBR', material=bpy.context.active_object.active_material) return {'FINISHED'} class OT_CreateTemplateOmniGlass(bpy.types.Operator): bl_idname = 'universalmaterialmap.create_template_omniglass' bl_label = 'Convert to OmniGlass Graph' bl_description = 'Universal Material Map Converter' def execute(self, context): if not bpy.context: return {'FINISHED'} if not bpy.context.active_object: return {'FINISHED'} if not bpy.context.active_object.active_material: return {'FINISHED'} create_template(source_class='OmniGlass', material=bpy.context.active_object.active_material) return {'FINISHED'} class OT_DescribeShaderGraph(bpy.types.Operator): bl_idname = 'universalmaterialmap.describe_shader_graph' bl_label = 'Universal Material Map Describe Shader Graph Operator' bl_description = 'Universal Material Map' @staticmethod def describe_node(node) -> dict: node_definition = dict() node_definition['name'] = node.name node_definition['label'] = node.label node_definition['location'] = [node.location[0], node.location[1]] node_definition['width'] = node.width node_definition['height'] = node.height node_definition['parent'] = node.parent.name if node.parent else None node_definition['class'] = type(node).__name__ node_definition['inputs'] = [] node_definition['outputs'] = [] node_definition['nodes'] = [] node_definition['links'] = [] node_definition['properties'] = [] node_definition['texts'] = [] if node_definition['class'] == 'NodeFrame': node_definition['properties'].append( { 'name': 'use_custom_color', 'value': node.use_custom_color, } ) node_definition['properties'].append( { 'name': 'color', 'value': [node.color[0], node.color[1], node.color[2]], } ) node_definition['properties'].append( { 'name': 'shrink', 'value': node.shrink, } ) if node.text is not None: text_definition = dict() text_definition['name'] = node.text.name text_definition['contents'] = node.text.as_string() node_definition['texts'].append(text_definition) elif node_definition['class'] == 'ShaderNodeRGB': for index, output in enumerate(node.outputs): definition = dict() definition['index'] = index definition['name'] = output.name definition['class'] = type(output).__name__ if definition['class'] == 'NodeSocketColor': default_value = output.default_value definition['default_value'] = [default_value[0], default_value[1], default_value[2], default_value[3]] else: raise NotImplementedError() node_definition['outputs'].append(definition) elif node_definition['class'] == 'ShaderNodeMixRGB': node_definition['properties'].append( { 'name': 'blend_type', 'value': node.blend_type, } ) node_definition['properties'].append( { 'name': 'use_clamp', 'value': node.use_clamp, } ) for index, input in enumerate(node.inputs): definition = dict() definition['index'] = index definition['name'] = input.name definition['class'] = type(input).__name__ if definition['class'] == 'NodeSocketFloatFactor': definition['default_value'] = node.inputs[input.name].default_value elif definition['class'] == 'NodeSocketColor': default_value = node.inputs[input.name].default_value definition['default_value'] = [default_value[0], default_value[1], default_value[2], default_value[3]] else: raise NotImplementedError() node_definition['inputs'].append(definition) elif node_definition['class'] == 'ShaderNodeGroup': for index, input in enumerate(node.inputs): definition = dict() definition['index'] = index definition['name'] = input.name definition['class'] = type(input).__name__ if definition['class'] == 'NodeSocketFloatFactor': definition['min_value'] = node.node_tree.inputs[input.name].min_value definition['max_value'] = node.node_tree.inputs[input.name].max_value definition['default_value'] = node.inputs[input.name].default_value elif definition['class'] == 'NodeSocketIntFactor': definition['min_value'] = node.node_tree.inputs[input.name].min_value definition['max_value'] = node.node_tree.inputs[input.name].max_value definition['default_value'] = node.inputs[input.name].default_value elif definition['class'] == 'NodeSocketColor': default_value = node.inputs[input.name].default_value definition['default_value'] = [default_value[0], default_value[1], default_value[2], default_value[3]] else: raise NotImplementedError() node_definition['inputs'].append(definition) for index, output in enumerate(node.outputs): definition = dict() definition['index'] = index definition['name'] = output.name definition['class'] = type(output).__name__ node_definition['outputs'].append(definition) for child in node.node_tree.nodes: node_definition['nodes'].append(OT_DescribeShaderGraph.describe_node(child)) for link in node.node_tree.links: if not isinstance(link, bpy.types.NodeLink): continue if not link.is_valid: continue link_definition = dict() link_definition['from_node'] = link.from_node.name link_definition['from_socket'] = link.from_socket.name link_definition['to_node'] = link.to_node.name link_definition['to_socket'] = link.to_socket.name node_definition['links'].append(link_definition) elif node_definition['class'] == 'ShaderNodeUVMap': pass elif node_definition['class'] == 'ShaderNodeTexImage': pass elif node_definition['class'] == 'ShaderNodeOutputMaterial': pass elif node_definition['class'] == 'ShaderNodeBsdfPrincipled': pass elif node_definition['class'] == 'ShaderNodeMapping': pass elif node_definition['class'] == 'ShaderNodeNormalMap': pass elif node_definition['class'] == 'ShaderNodeHueSaturation': pass elif node_definition['class'] == 'ShaderNodeSeparateRGB': pass elif node_definition['class'] == 'NodeGroupInput': pass elif node_definition['class'] == 'NodeGroupOutput': pass elif node_definition['class'] == 'ShaderNodeMath': node_definition['properties'].append( { 'name': 'operation', 'value': node.operation, } ) node_definition['properties'].append( { 'name': 'use_clamp', 'value': node.use_clamp, } ) elif node_definition['class'] == 'ShaderNodeVectorMath': node_definition['properties'].append( { 'name': 'operation', 'value': node.operation, } ) else: raise NotImplementedError(node_definition['class']) return node_definition def execute(self, context): material = bpy.context.active_object.active_material output = dict() output['name'] = 'Principled Omni Glass' output['nodes'] = [] output['links'] = [] for node in material.node_tree.nodes: output['nodes'].append(OT_DescribeShaderGraph.describe_node(node)) for link in material.node_tree.links: if not isinstance(link, bpy.types.NodeLink): continue if not link.is_valid: continue link_definition = dict() link_definition['from_node'] = link.from_node.name link_definition['from_socket'] = link.from_socket.name link_definition['to_node'] = link.to_node.name link_definition['to_socket'] = link.to_socket.name output['links'].append(link_definition) print(json.dumps(output, indent=4)) return {'FINISHED'} def initialize(): if getattr(sys.modules[__name__], '__initialized'): return setattr(sys.modules[__name__], '__initialized', True) util.register(converter=DataConverter()) util.register(converter=ObjectConverter()) print('Universal Material Map: Registered Converter classes.') initialize()
67,551
Python
49.676669
263
0.552101
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/blender/material.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import traceback import bpy from ..core.converter import util def apply_data_to_instance(instance_name: str, source_class: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> dict: try: for material in bpy.data.materials: if not isinstance(material, bpy.types.Material): continue if material.name == instance_name: if util.can_apply_data_to_instance(source_class_name=source_class, render_context=render_context, source_data=source_data, instance=material): return util.apply_data_to_instance(source_class_name=source_class, render_context=render_context, source_data=source_data, instance=material) print(f'Omniverse UMM: Unable to apply data at import for material "{instance_name}". This is not an error - just means that conversion data does not support the material.') result = dict() result['umm_notification'] = 'incomplete_process' result['message'] = 'Not able to convert type "{0}" for render context "{1}" because there is no Conversion Graph for that scenario. No changes were applied to "{2}".'.format(source_class, render_context, instance_name) return result except Exception as error: print('Warning: Universal Material Map: function "apply_data_to_instance": Unexpected error:') print('\targument "instance_name" = "{0}"'.format(instance_name)) print('\targument "source_class" = "{0}"'.format(source_class)) print('\targument "render_context" = "{0}"'.format(render_context)) print('\targument "source_data" = "{0}"'.format(source_data)) print('\terror: {0}'.format(error)) print('\tcallstack: {0}'.format(traceback.format_exc())) result = dict() result['umm_notification'] = 'unexpected_error' result['message'] = 'Not able to convert type "{0}" for render context "{1}" because there was an unexpected error. Some changes may have been applied to "{2}". Details: {3}'.format(source_class, render_context, instance_name, error) return result def convert_instance_to_data(instance_name: str, render_context: str) -> typing.List[typing.Tuple[str, typing.Any]]: try: for material in bpy.data.materials: if not isinstance(material, bpy.types.Material): continue if material.name == instance_name: if util.can_convert_instance_to_data(instance=material, render_context=render_context): return util.convert_instance_to_data(instance=material, render_context=render_context) result = dict() result['umm_notification'] = 'incomplete_process' result['message'] = 'Not able to convert material "{0}" for render context "{1}" because there is no Conversion Graph for that scenario.'.format(instance_name, render_context) return result except Exception as error: print('Warning: Universal Material Map: function "convert_instance_to_data": Unexpected error:') print('\targument "instance_name" = "{0}"'.format(instance_name)) print('\targument "render_context" = "{0}"'.format(render_context)) print('\terror: {0}'.format(error)) print('\tcallstack: {0}'.format(traceback.format_exc())) result = dict() result['umm_notification'] = 'unexpected_error' result['message'] = 'Not able to convert material "{0}" for render context "{1}" there was an unexpected error. Details: {2}'.format(instance_name, render_context, error) return result result = dict() result['umm_notification'] = 'incomplete_process' result['message'] = 'Not able to convert material "{0}" for render context "{1}" because there is no Conversion Graph for that scenario.'.format(instance_name, render_context) return result
4,820
Python
57.084337
241
0.66805
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/blender/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import os import re import sys import json import bpy from ..core.data import Library from ..core.feature import POLLING from ..core.service import store from ..core.service import delegate LIBRARY_ID = '195c69e1-7765-4a16-bb3a-ecaa222876d9' __initialized = False developer_mode: bool = False CORE_MATERIAL_PROPERTIES = [ ('diffuse_color', 'RGBA'), ('metallic', 'VALUE'), ('specular_color', 'STRING'), ('roughness', 'VALUE'), ('use_backface_culling', 'BOOLEAN'), ('blend_method', 'STRING'), ('shadow_method', 'STRING'), ('alpha_threshold', 'VALUE'), ('use_screen_refraction', 'BOOLEAN'), ('refraction_depth', 'VALUE'), ('use_sss_translucency', 'BOOLEAN'), ('pass_index', 'INT'), ] def show_message(message: str = '', title: str = 'Message Box', icon: str = 'INFO'): try: def draw(self, context): self.layout.label(text=message) bpy.context.window_manager.popup_menu(draw, title=title, icon=icon) except: print('{0}\n{1}'.format(title, message)) def initialize(): if getattr(sys.modules[__name__], '__initialized'): return setattr(sys.modules[__name__], '__initialized', True) directory = os.path.expanduser('~').replace('\\', '/') if not directory.endswith('/Documents'): directory = '{0}/Documents'.format(directory) directory = '{0}/Omniverse/Blender/UMMLibrary'.format(directory) library = Library.Create( library_id=LIBRARY_ID, name='Blender', manifest=delegate.FilesystemManifest(root_directory='{0}'.format(directory)), conversion_graph=delegate.Filesystem(root_directory='{0}/ConversionGraph'.format(directory)), target=delegate.Filesystem(root_directory='{0}/Target'.format(directory)), ) store.register_library(library=library) from ..blender import converter converter.initialize() from ..blender import generator generator.initialize() if POLLING: # TODO: On application exit > un_initialize() pass def un_initialize(): if POLLING: store.on_shutdown() def get_library(): """ :return: omni.universalmaterialmap.core.data.Library """ initialize() return store.get_library(library_id=LIBRARY_ID) def __get_value_impl(socket: bpy.types.NodeSocketStandard, depth=0, max_depth=100) -> typing.Any: # Local utility function which returns a file extension # corresponding to the given image file format string. # This mimics similar logic used in the Blender USD IO # C++ implementation. def get_extension_from_image_file_format(format): format = format.lower() if format == 'open_exr': format = 'exr' elif format == 'jpeg': format = 'jpg' return format debug = False if debug: print('__get_value_impl: depth={0}'.format(depth)) if depth > max_depth: if debug: print('\t reached max_depth ({0}). terminating recursion'.format(max_depth)) return None if debug: print('\tsocket.is_linked'.format(socket.is_linked)) if socket.is_linked: for link in socket.links: if not isinstance(link, bpy.types.NodeLink): if debug: print('\t\tlink is not bpy.types.NodeLink: {0}'.format(type(link))) continue if not link.is_valid: if debug: print('\t\tlink is not valid') continue instance = link.from_node if debug: print('\t\tlink.from_node: {0}'.format(type(instance))) if isinstance(instance, bpy.types.ShaderNodeTexImage): print(f'UMM: image.filepath: "{instance.image.filepath}"') print(f'UMM: image.source: "{instance.image.source}"') print(f'UMM: image.file_format: "{instance.image.file_format}"') if debug: print('\t\tinstance.image: {0}'.format(instance.image)) if instance.image: print('\t\tinstance.image.source: {0}'.format(instance.image.source)) if instance.image and (instance.image.source == 'FILE' or instance.image.source == 'TILED'): value = instance.image.filepath if (instance.image.source == 'TILED'): # Find all numbers in the path. numbers = re.findall('[0-9]+', value) if (len(numbers) > 0): # Get the string representation of the last number. num_str = str(numbers[-1]) # Replace the number substring with '<UDIM>'. split_items = value.rsplit(num_str, 1) if (len(split_items)==2): value = split_items[0] + '<UDIM>' + split_items[1] if debug: print('\t\tinstance.image.filepath: {0}'.format(value)) try: if value and instance.image.packed_file: # The image is packed, so ignore the filepath, which is likely # invalid, and return just the base name. value = bpy.path.basename(value) # Make sure the file has a valid extension for # the expected format. file_format = instance.image.file_format file_format = get_extension_from_image_file_format(file_format) value = bpy.path.ensure_ext(value, '.' + file_format) print(f'UMM: packed image data: "{[value, instance.image.colorspace_settings.name]}"') return [value, instance.image.colorspace_settings.name] if value is None or value == '': file_format = instance.image.file_format file_format = get_extension_from_image_file_format(file_format) value = f'{instance.image.name}.{file_format}' if debug: print(f'\t\tvalue: {value}') print(f'UMM: image data: "{[value, instance.image.colorspace_settings.name]}"') return [value, instance.image.colorspace_settings.name] return [os.path.abspath(bpy.path.abspath(value)), instance.image.colorspace_settings.name] except Exception as error: print('Warning: Universal Material Map: Unable to evaluate absolute file path of texture "{0}". Detail: {1}'.format(instance.image.filepath, error)) return None if isinstance(instance, bpy.types.ShaderNodeNormalMap): for o in instance.inputs: if o.name == 'Color': value = __get_value_impl(socket=o, depth=depth + 1, max_depth=max_depth) if value: return value for o in instance.inputs: value = __get_value_impl(socket=o, depth=depth + 1, max_depth=max_depth) if debug: print('\t\tre-entrant: input="{0}", value="{1}"'.format(o.name, value)) if value: return value return None def get_value(socket: bpy.types.NodeSocketStandard) -> typing.Any: debug = False value = __get_value_impl(socket=socket) if debug: print('get_value', value, socket.default_value) return socket.default_value if not value else value def _create_node_from_template(node_tree: bpy.types.NodeTree, node_definition: dict, parent: object = None) -> object: node = node_tree.nodes.new(node_definition['class']) if parent: node.parent = parent node.name = node_definition['name'] node.label = node_definition['label'] node.location = node_definition['location'] if node_definition['class'] == 'NodeFrame': node.width = node_definition['width'] node.height = node_definition['height'] for o in node_definition['properties']: setattr(node, o['name'], o['value']) if node_definition['class'] == 'NodeFrame': for text_definition in node_definition['texts']: existing = None for o in bpy.data.texts: if o.name == text_definition['name']: existing = o break if existing is None: existing = bpy.data.texts.new(text_definition['name']) existing.write(text_definition['contents']) node.text = existing node.location = node_definition['location'] elif node_definition['class'] == 'ShaderNodeGroup': node.node_tree = bpy.data.node_groups.new('node tree', 'ShaderNodeTree') child_cache = dict() for child_definition in node_definition['nodes']: child_cache[child_definition['name']] = _create_node_from_template(node_tree=node.node_tree, node_definition=child_definition) for input_definition in node_definition['inputs']: node.inputs.new(input_definition['class'], input_definition['name']) if input_definition['class'] == 'NodeSocketFloatFactor': node.node_tree.inputs[input_definition['name']].min_value = input_definition['min_value'] node.node_tree.inputs[input_definition['name']].max_value = input_definition['max_value'] node.node_tree.inputs[input_definition['name']].default_value = input_definition['default_value'] node.inputs[input_definition['name']].default_value = input_definition['default_value'] if input_definition['class'] == 'NodeSocketIntFactor': node.node_tree.inputs[input_definition['name']].min_value = input_definition['min_value'] node.node_tree.inputs[input_definition['name']].max_value = input_definition['max_value'] node.node_tree.inputs[input_definition['name']].default_value = input_definition['default_value'] node.inputs[input_definition['name']].default_value = input_definition['default_value'] if input_definition['class'] == 'NodeSocketColor': node.node_tree.inputs[input_definition['name']].default_value = input_definition['default_value'] node.inputs[input_definition['name']].default_value = input_definition['default_value'] for output_definition in node_definition['outputs']: node.outputs.new(output_definition['class'], output_definition['name']) for link_definition in node_definition['links']: from_node = child_cache[link_definition['from_node']] from_socket = [o for o in from_node.outputs if o.name == link_definition['from_socket']][0] to_node = child_cache[link_definition['to_node']] to_socket = [o for o in to_node.inputs if o.name == link_definition['to_socket']][0] node.node_tree.links.new(from_socket, to_socket) node.width = node_definition['width'] node.height = node_definition['height'] node.location = node_definition['location'] elif node_definition['class'] == 'ShaderNodeMixRGB': for input_definition in node_definition['inputs']: if input_definition['class'] == 'NodeSocketFloatFactor': node.inputs[input_definition['name']].default_value = input_definition['default_value'] if input_definition['class'] == 'NodeSocketColor': node.inputs[input_definition['name']].default_value = input_definition['default_value'] elif node_definition['class'] == 'ShaderNodeRGB': for output_definition in node_definition['outputs']: if output_definition['class'] == 'NodeSocketColor': node.outputs[output_definition['name']].default_value = output_definition['default_value'] return node def create_template(source_class: str, material: bpy.types.Material) -> None: template_filepath = '{}'.format(__file__).replace('\\', '/') template_filepath = template_filepath[:template_filepath.rfind('/')] template_filepath = '{}/template/{}.json'.format(template_filepath, source_class.lower()) if not os.path.exists(template_filepath): return with open(template_filepath, 'r') as template_file: template = json.load(template_file) # Make sure we're using nodes. material.use_nodes = True # Remove existing nodes - we're starting from scratch. to_delete = [o for o in material.node_tree.nodes] while len(to_delete): material.node_tree.nodes.remove(to_delete.pop()) # Create nodes according to template. child_cache = dict() for node_definition in template['nodes']: if node_definition['parent'] is None: node = _create_node_from_template(node_tree=material.node_tree, node_definition=node_definition) child_cache[node_definition['name']] = node for node_definition in template['nodes']: if node_definition['parent'] is not None: parent = child_cache[node_definition['parent']] node = _create_node_from_template(node_tree=material.node_tree, node_definition=node_definition, parent=parent) child_cache[node_definition['name']] = node for link_definition in template['links']: from_node = child_cache[link_definition['from_node']] from_socket = [o for o in from_node.outputs if o.name == link_definition['from_socket']][0] to_node = child_cache[link_definition['to_node']] to_socket = [o for o in to_node.inputs if o.name == link_definition['to_socket']][0] material.node_tree.links.new(from_socket, to_socket) def create_from_template(material: bpy.types.Material, template: dict) -> None: # Make sure we're using nodes. material.use_nodes = True # Create nodes according to template. child_cache = dict() for node_definition in template['nodes']: if node_definition['parent'] is None: node = _create_node_from_template(node_tree=material.node_tree, node_definition=node_definition) child_cache[node_definition['name']] = node for node_definition in template['nodes']: if node_definition['parent'] is not None: parent = child_cache[node_definition['parent']] node = _create_node_from_template(node_tree=material.node_tree, node_definition=node_definition, parent=parent) child_cache[node_definition['name']] = node for link_definition in template['links']: from_node = child_cache[link_definition['from_node']] from_socket = [o for o in from_node.outputs if o.name == link_definition['from_socket']][0] to_node = child_cache[link_definition['to_node']] to_socket = [o for o in to_node.inputs if o.name == link_definition['to_socket']][0] material.node_tree.links.new(from_socket, to_socket) def get_parent_material(shader_node: object) -> bpy.types.Material: for material in bpy.data.materials: if shader_node == material: return material if not material.use_nodes: continue if not material.node_tree or not material.node_tree.nodes: continue for node in material.node_tree.nodes: if shader_node == node: return material return None def get_template_data_by_shader_node(shader_node: object) -> typing.Tuple[typing.Dict, typing.Dict, str, bpy.types.Material]: material: bpy.types.Material = get_parent_material(shader_node=shader_node) if material and material.use_nodes and material.node_tree and material.node_tree.nodes: template_directory = '{}'.format(__file__).replace('\\', '/') template_directory = template_directory[:template_directory.rfind('/')] template_directory = f'{template_directory}/template' for item in os.listdir(template_directory): if item.lower().endswith('_map.json'): continue if not item.lower().endswith('.json'): continue template_filepath = f'{template_directory}/{item}' with open(template_filepath, 'r') as template_file: template = json.load(template_file) material_has_all_template_nodes = True for node_definition in template['nodes']: found_node = False for node in material.node_tree.nodes: if node.name == node_definition['name']: found_node = True break if not found_node: material_has_all_template_nodes = False break if not material_has_all_template_nodes: continue template_has_all_material_nodes = True for node in material.node_tree.nodes: found_template = False for node_definition in template['nodes']: if node.name == node_definition['name']: found_template = True break if not found_template: template_has_all_material_nodes = False break if not template_has_all_material_nodes: continue template_shader_name = template['name'] map_filename = '{}_map.json'.format(item[:item.rfind('.')]) template_map_filepath = f'{template_directory}/{map_filename}' with open(template_map_filepath, 'r') as template_map_file: template_map = json.load(template_map_file) return template, template_map, template_shader_name, material return None, None, None, None def get_template_data_by_class_name(class_name: str) -> typing.Tuple[typing.Dict, typing.Dict]: template_directory = '{}'.format(__file__).replace('\\', '/') template_directory = template_directory[:template_directory.rfind('/')] template_directory = f'{template_directory}/template' for item in os.listdir(template_directory): if item.lower().endswith('_map.json'): continue if not item.lower().endswith('.json'): continue template_filepath = f'{template_directory}/{item}' with open(template_filepath, 'r') as template_file: template = json.load(template_file) if not template['name'] == class_name: continue map_filename = '{}_map.json'.format(item[:item.rfind('.')]) template_map_filepath = f'{template_directory}/{map_filename}' with open(template_map_filepath, 'r') as template_map_file: template_map = json.load(template_map_file) return template, template_map return None, None
20,047
Python
43.353982
172
0.597446
NVIDIA-Omniverse/Blender-Addon-UMM/omni/universalmaterialmap/blender/menu.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy from . import developer_mode class UniversalMaterialMapMenu(bpy.types.Menu): bl_label = "Omniverse" bl_idname = "OBJECT_MT_umm_node_menu" def draw(self, context): layout = self.layout layout.operator('universalmaterialmap.create_template_omnipbr', text='Replace with OmniPBR graph template') layout.operator('universalmaterialmap.create_template_omniglass', text='Replace with OmniGlass graph template') if developer_mode: layout.operator('universalmaterialmap.generator', text='DEV: Generate Targets') layout.operator('universalmaterialmap.instance_to_data_converter', text='DEV: Convert Instance to Data') layout.operator('universalmaterialmap.data_to_instance_converter', text='DEV: Convert Data to Instance') layout.operator('universalmaterialmap.data_to_data_converter', text='DEV: Convert Data to Data') layout.operator('universalmaterialmap.apply_data_to_instance', text='DEV: Apply Data to Instance') layout.operator('universalmaterialmap.describe_shader_graph', text='DEV: Describe Shader Graph')
1,999
Python
45.511627
119
0.724362
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/README.md
# AI Room Generator Extension Sample ![Extension Preview](exts/omni.example.airoomgenerator/data/preview.png) ### About This extension allows user's to generate 3D content using Generative AI, ChatGPT. Providing an area in the stage and a prompt the user can generate a room configuration designed by ChatGPT. This in turn can help end users automatically generate and place objects within their scene, saving hours of time that would typically be required to create a complex scene. ### [README](exts/omni.example.airoomgenerator) See the [README for this extension](exts/omni.example.airoomgenerator) to learn more about it including how to use it. > This sample is for educational purposes. For production please consider best security practices and scalability. ## Adding This Extension This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths. Link might look like this: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-airoomgenerator?branch=main&dir=exts` Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual. To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path ## Linking with an Omniverse app If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
2,140
Markdown
40.173076
363
0.775701
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") 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 install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "DeepSearch Swap" description="The simplest python extension example. Use it as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.ngsearch" = {} # Main python module this extension provides, it will be publicly available as "import company.hello.world". [[python.module]] name = "omni.sample.deepsearchpicker" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,095
TOML
25.731707
108
0.73516
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/style.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui from pathlib import Path icons_path = Path(__file__).parent.parent.parent.parent / "icons" gen_ai_style = { "HStack": { "margin": 3 }, "Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976} }
946
Python
32.821427
98
0.726216
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/extension.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ext from .window import DeepSearchPickerWindow # 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 MyExtension(omni.ext.IExt): # 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): self._window = DeepSearchPickerWindow("DeepSearch Swap", width=300, height=300) def on_shutdown(self): self._window.destroy() self._window = None
1,423
Python
44.935482
119
0.747013
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/__init__.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .extension import *
705
Python
40.529409
98
0.770213
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/deep_search.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from omni.kit.ngsearch.client import NGSearchClient import carb import asyncio class deep_search(): async def query_items(queries, url: str, paths): result = list(tuple()) for query in queries: query_result = await deep_search._query_first(query, url, paths) if query_result is not None: result.append(query_result) return result async def _query_first(query: str, url: str, paths): filtered_query = "ext:usd,usdz,usda path:" for path in paths: filtered_query = filtered_query + "\"" + str(path) + "\"," filtered_query = filtered_query[:-1] filtered_query = filtered_query + " " filtered_query = filtered_query + query SearchResult = await NGSearchClient.get_instance().find2( query=filtered_query, url=url) if len(SearchResult.paths) > 0: return (query, SearchResult.paths[0].uri) else: return None async def query_all(query: str, url: str, paths): filtered_query = "ext:usd,usdz,usda path:" for path in paths: filtered_query = filtered_query + "\"" + str(path) + "\"," filtered_query = filtered_query[:-1] filtered_query = filtered_query + " " filtered_query = filtered_query + query return await NGSearchClient.get_instance().find2(query=filtered_query, url=url)
2,185
Python
32.121212
98
0.632494
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/window.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui import omni.usd import carb from .style import gen_ai_style from .deep_search import deep_search import asyncio from pxr import UsdGeom, Usd, Sdf, Gf class DeepSearchPickerWindow(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) # Models self.frame.set_build_fn(self._build_fn) self._index = 0 self._query_results = None self._selected_prim = None self._prim_path_model = ui.SimpleStringModel() def _build_fn(self): async def replace_prim(): self._index = 0 ctx = omni.usd.get_context() prim_paths = ctx.get_selection().get_selected_prim_paths() if len(prim_paths) != 1: carb.log_warn("You must select one and only one prim") return prim_path = prim_paths[0] stage = ctx.get_stage() self._selected_prim = stage.GetPrimAtPath(prim_path) query = self._selected_prim.GetAttribute("DeepSearch:Query").Get() prop_paths = ["/Projects/simready_content/common_assets/props/", "/NVIDIA/Assets/Isaac/2022.2.1/Isaac/Robots/", "/NVIDIA/Assets/Isaac/2022.1/NVIDIA/Assets/ArchVis/Residential/Furniture/"] self._query_results = await deep_search.query_all(query, "omniverse://ov-simready/", paths=prop_paths) self._prim_path_model.set_value(prim_path) def increment_prim_index(): if self._query_results is None: return self._index = self._index + 1 if self._index >= len(self._query_results.paths): self._index = 0 self.replace_reference() def decrement_prim_index(): if self._query_results is None: return self._index = self._index - 1 if self._index <= 0: self._index = len(self._query_results.paths) - 1 self.replace_reference() with self.frame: with ui.VStack(style=gen_ai_style): with ui.HStack(height=0): ui.Spacer() ui.StringField(model=self._prim_path_model, width=365, height=30) ui.Button(name="create", width=30, height=30, clicked_fn=lambda: asyncio.ensure_future(replace_prim())) ui.Spacer() with ui.HStack(height=0): ui.Spacer() ui.Button("<", width=200, clicked_fn=lambda: decrement_prim_index()) ui.Button(">", width=200, clicked_fn=lambda: increment_prim_index()) ui.Spacer() def replace_reference(self): references: Usd.references = self._selected_prim.GetReferences() references.ClearReferences() references.AddReference( assetPath="omniverse://ov-simready" + self._query_results.paths[self._index].uri) carb.log_info("Got it?") def destroy(self): super().destroy()
3,815
Python
36.048543
123
0.589253
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194