file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/change_management.py
from ..._impl.omnigraph_node_description_editor.change_management import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_list_manager.py
from ..._impl.omnigraph_node_description_editor.attribute_list_manager import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/memory_type_manager.py
from ..._impl.omnigraph_node_description_editor.memory_type_manager import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/node_language_manager.py
from ..._impl.omnigraph_node_description_editor.node_language_manager import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_model.py
from ..._impl.omnigraph_node_description_editor.main_model import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/tests_data_manager.py
from ..._impl.omnigraph_node_description_editor.tests_data_manager import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/node_properties.py
from ..._impl.omnigraph_node_description_editor.node_properties import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_properties.py
from ..._impl.omnigraph_node_description_editor.attribute_properties import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_union_type_adder_manager.py
from ..._impl.omnigraph_node_description_editor.attribute_union_type_adder_manager import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/extension_info_manager.py
from ..._impl.omnigraph_node_description_editor.extension_info_manager import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_editor.py
from ..._impl.omnigraph_node_description_editor.main_editor import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/test_configurations.py
from ..._impl.omnigraph_node_description_editor.test_configurations import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_generator.py
from ..._impl.omnigraph_node_description_editor.main_generator import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_base_type_manager.py
from ..._impl.omnigraph_node_description_editor.attribute_base_type_manager import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_tuple_count_manager.py
from ..._impl.omnigraph_node_description_editor.attribute_tuple_count_manager import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/file_manager.py
from ..._impl.omnigraph_node_description_editor.file_manager import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/ogn_editor_utils.py
from ..._impl.omnigraph_node_description_editor.ogn_editor_utils import * # noqa
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_extension_shutdown.py
"""Test cases for extension shutdown""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit # ====================================================================== class TestExtensionShutdown(ogts.OmniGraphTestCase): """Testing for extension shutdown""" # ---------------------------------------------------------------------- async def test_om_43835(self): """Verify safe ordering of node state release on extension shutdown. The test had to be put into this extension so that it could shut down the extension where the test node lives without unloading the test itself. """ manager = omni.kit.app.get_app_interface().get_extension_manager() test_nodes_extension = "omni.graph.test" test_node_type = f"{test_nodes_extension}.TestGracefulShutdown" was_extension_enabled = manager.is_extension_enabled(test_nodes_extension) try: manager.set_extension_enabled_immediate(test_nodes_extension, True) self.assertTrue(manager.is_extension_enabled(test_nodes_extension)) # Make sure that a dependency hasn't been inadvertently been added from the test extension to this one ext_id = manager.get_enabled_extension_id(test_nodes_extension) dependencies = manager.get_extension_dict(ext_id).get_dict()["dependencies"] self.assertTrue("omni.graph.ui" not in dependencies) # Creating a node is all that it takes to set up the state information required by the test controller = og.Controller() (graph, _, _, _) = controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: ("TestNode", test_node_type), }, ) await controller.evaluate(graph) # Unloading the extension triggers the state release, which will test the necessary conditions manager.set_extension_enabled_immediate(test_nodes_extension, False) self.assertEqual(0, og.test_failure_count(), "Test failure was reported by the node state") finally: manager.set_extension_enabled_immediate(test_nodes_extension, was_extension_enabled)
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.ui as ogu from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphUiApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests", "omni"] async def test_api(self): _check_module_api_consistency(ogu, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(ogu.tests, is_test_module=True) # noqa: PLW0212 async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents( # noqa: PLW0212 ogu, [ "add_create_menu_type", "build_port_type_convert_menu", "ComputeNodeWidget", "find_prop", "GraphVariableCustomLayout", "OmniGraphAttributeModel", "OmniGraphTfTokenAttributeModel", "OmniGraphBase", "OmniGraphPropertiesWidgetBuilder", "PrimAttributeCustomLayoutBase", "PrimPathCustomLayoutBase", "RandomNodeCustomLayoutBase", "ReadPrimsCustomLayoutBase", "remove_create_menu_type", "SETTING_PAGE_NAME", ], self._UNPUBLISHED, only_expected_allowed=True, ) _check_public_api_contents(ogu.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/__init__.py
"""There is no public API to this module.""" __all__ = [] scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_view.py
""" * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. """ import omni.kit.test class OmniGraphViewTest(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello(self): self.assertEqual(10, 10)
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_widgets.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import pathlib from typing import List import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui from omni.kit import ui_test from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading from omni.ui.tests.test_base import OmniUiTest class TestOmniWidgets(OmniUiTest): """ Test class for testing omnigraph related widgets """ async def setUp(self): await super().setUp() usd_path = pathlib.Path(get_test_data_path(__name__)) self._golden_img_dir = usd_path.absolute().joinpath("golden_img").absolute() self._usd_path = usd_path.absolute() import omni.kit.window.property as p self._w = p.get_window() async def tearDown(self): await super().tearDown() async def __widget_image_test( self, file_path: str, prims_to_select: List[str], golden_img_name: str, width=450, height=500, ): """Helper to do generate a widget comparison test on a property panel""" usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, # noqa: PLE0211,PLW0212 width=width, height=height, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) test_file_path = self._usd_path.joinpath(file_path).absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(prims_to_select, True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name, threshold=0.15) # Close the stage to avoid dangling references to the graph. (OM-84680) await omni.usd.get_context().close_stage_async() async def test_compound_node_type_widget_ui(self): """Tests the compound node type property pane matches the expected image""" await self.__widget_image_test( file_path="compound_node_test.usda", prims_to_select=["/World/Compounds/TestCompound"], golden_img_name="test_compound_widget.png", height=600, ) async def test_graph_with_variables_widget(self): """Tests the variable property pane on a graph prim""" await self.__widget_image_test( file_path="test_variables.usda", prims_to_select=["/World/ActionGraph"], golden_img_name="test_graph_variables.png", height=300, ) async def test_instance_with_variables_widget(self): """Tests the variable property pane on an instance prim""" await self.__widget_image_test( file_path="test_variables.usda", prims_to_select=["/World/Instance"], golden_img_name="test_instance_variables.png", height=450, )
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_property_widget.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import tempfile from pathlib import Path import omni.graph.core as og import omni.graph.tools.ogn as ogn import omni.graph.ui._impl.omnigraph_attribute_base as ogab import omni.graph.ui._impl.omnigraph_attribute_models as ogam import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd from omni.kit import ui_test from omni.ui.tests.test_base import OmniUiTest from pxr import Sdf, Usd _MATRIX_DIMENSIONS = {4: 2, 9: 3, 16: 4} # ---------------------------------------------------------------------- class TestOmniGraphWidget(OmniUiTest): """ Tests for OmniGraphBase and associated models in this module, the custom widget for the kit property panel uses these models which are customized for OmniGraphNode prims. """ TEST_GRAPH_PATH = "/World/TestGraph" # Before running each test async def setUp(self): await super().setUp() # Ensure we have a clean stage for the test await omni.usd.get_context().new_stage_async() # Give OG a chance to set up on the first stage update await omni.kit.app.get_app().next_update_async() og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) extension_root_folder = Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) self._golden_img_dir = extension_root_folder.joinpath("data/tests/golden_img") import omni.kit.window.property as p self._w = p.get_window() # After running each test async def tearDown(self): # Close the stage to avoid dangling references to the graph. (OM-84680) await omni.usd.get_context().close_stage_async() await super().tearDown() def __attribute_type_to_name(self, attribute_type: og.Type) -> str: """Converts an attribute type into the canonical attribute name used by the test nodes. The rules are: - prefix of a_ - followed by name of attribute base type - followed by optional _N if the component count N is > 1 - followed by optional '_array' if the type is an array Args: type: OGN attribute type to deconstruct Returns: Canonical attribute name for the attribute with the given type """ attribute_name = f"a_{og.Type(attribute_type.base_type, 1, 0, attribute_type.role).get_ogn_type_name()}" attribute_name = attribute_name.replace("prim", "bundle") if attribute_type.tuple_count > 1: if attribute_type.role in [og.AttributeRole.TRANSFORM, og.AttributeRole.FRAME, og.AttributeRole.MATRIX]: attribute_name += f"_{_MATRIX_DIMENSIONS[attribute_type.tuple_count]}" else: attribute_name += f"_{attribute_type.tuple_count}" array_depth = attribute_type.array_depth while array_depth > 0 and attribute_type.role not in [og.AttributeRole.TEXT, og.AttributeRole.PATH]: attribute_name += "_array" array_depth -= 1 return attribute_name async def test_target_attribute(self): """ Exercise the target-attribute customizations for Property Panel. The related code is in omnigraph_attribute_builder.py and targets.py """ usd_context = omni.usd.get_context() keys = og.Controller.Keys controller = og.Controller() (_, (get_parent_prims,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("GetParentPrims", "omni.graph.nodes.GetParentPrims"), ], }, ) # The OG attribute-base UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # Select the node. usd_context.get_selection().set_selected_prim_paths([get_parent_prims.get_prim_path()], True) # Wait for property panel to converge await ui_test.human_delay(5) # Click the Add-Relationship button attr_name = "inputs:prims" await ui_test.find( f"Property//Frame/**/Button[*].identifier=='sdf_relationship_array_{attr_name}.add_relationships'" ).click() # Wait for dialog to show up await ui_test.human_delay(5) # push the select-graph-target button and wait for dialog to close await ui_test.find("Select Targets//Frame/**/Button[*].identifier=='select_graph_target'").click() await ui_test.human_delay(5) # Resize to fit the property panel, and take a snapshot await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) await ui_test.human_delay(5) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute.png") # ---------------------------------------------------------------------- async def test_target_attribute_browse(self): """ Test the changing an existing selection via the dialog works """ usd_context = omni.usd.get_context() keys = og.Controller.Keys controller = og.Controller() prim_paths = ["/World/Prim"] (_, (read_prims_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadPrims", "omni.graph.nodes.ReadPrimsV2"), ], keys.CREATE_PRIMS: [(prim_path, {}) for prim_path in prim_paths], }, ) attr_name = "inputs:prims" usd_context.get_stage().GetPrimAtPath(read_prims_node.get_prim_path()).GetRelationship(attr_name).AddTarget( prim_paths[0] ) # The OG attribute-base UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # Select the node. usd_context.get_selection().set_selected_prim_paths([read_prims_node.get_prim_path()], True) # Wait for property panel to converge await ui_test.human_delay(5) # Click the Browse button model_index = 0 await ui_test.find( f"Property//Frame/**/Button[*].identifier=='sdf_browse_relationship_{attr_name}[{model_index}]'" ).click() # Wait for dialog to show up await ui_test.human_delay(5) # push the select-graph-target button and wait for dialog to close await ui_test.find("Select Targets//Frame/**/Button[*].identifier=='select_graph_target'").click() await ui_test.human_delay(5) # Resize to fit the property panel, and take a snapshot await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) await ui_test.human_delay(5) try: await self.capture_and_compare( golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute_browse.png" ) # Now edit the path to verify it displays as expected test_path = f"{og.INSTANCING_GRAPH_TARGET_PATH}/foo" # FIXME: This input call doesn't work - set with USD instead # await ui_test.find( # f"Property//Frame/**/StringField[*].identifier=='sdf_relationship_{attr_name}[{model_index}]'" # ).input(test_path) usd_context.get_stage().GetPrimAtPath(read_prims_node.get_prim_path()).GetRelationship( attr_name ).SetTargets([Sdf.Path(f"{read_prims_node.get_prim_path()}/{test_path}")]) await ui_test.human_delay(5) # Check the USD path has the token after the prim path, before the relative path self.assertEqual( usd_context.get_stage() .GetPrimAtPath(read_prims_node.get_prim_path()) .GetRelationship(attr_name) .GetTargets()[0], Sdf.Path(f"{read_prims_node.get_prim_path()}/{test_path}"), ) # Check that the composed path from OG is relative to the graph path self.assertEqual( str(og.Controller.get(f"{read_prims_node.get_prim_path()}.{attr_name}")[0]), f"{self.TEST_GRAPH_PATH}/foo", ) # Verify the widget display await self.capture_and_compare( golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute_edit.png" ) finally: await self.finalize_test_no_image() # ---------------------------------------------------------------------- async def test_prim_node_template(self): """ Tests the prim node template under different variations of selected prims to validate the the user does not get into a state where the attribute name cannot be edited """ usd_context = omni.usd.get_context() keys = og.Controller.Keys controller = og.Controller() (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadPrim_Path_ValidTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Path_InvalidTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Path_Connected", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Prim_ValidTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Prim_InvalidTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Prim_Connected", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrim_Prim_OGTarget", "omni.graph.nodes.ReadPrimAttribute"), ("ConstPrims", "omni.graph.nodes.ConstantPrims"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ], keys.CONNECT: [ ("ConstToken.inputs:value", "ReadPrim_Path_Connected.inputs:primPath"), ("ConstPrims.inputs:value", "ReadPrim_Prim_Connected.inputs:prim"), ], keys.SET_VALUES: [ ("ConstToken.inputs:value", "/World/Target"), ("ReadPrim_Path_ValidTarget.inputs:usePath", True), ("ReadPrim_Path_ValidTarget.inputs:primPath", "/World/Target"), ("ReadPrim_Path_ValidTarget.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Path_InvalidTarget.inputs:usePath", True), ("ReadPrim_Path_InvalidTarget.inputs:primPath", "/World/MissingTarget"), ("ReadPrim_Path_InvalidTarget.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Path_Connected.inputs:usePath", True), ("ReadPrim_Path_Connected.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Prim_ValidTarget.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Prim_InvalidTarget.inputs:name", "xformOp:rotateXYZ"), ("ReadPrim_Prim_Connected.inputs:name", "size"), ("ReadPrim_Prim_OGTarget.inputs:name", "fileFormatVersion"), ], keys.CREATE_PRIMS: [ ("/World/Target", "Xform"), ("/World/Cube", "Cube"), ("/World/MissingTarget", "Xform"), ], }, ) # Change the pipeline stage to On demand to prevent the graph from running and producing errors og.cmds.ChangePipelineStage(graph=graph, new_pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND) # The OG attribute-base UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # add relationships to all graph_path = self.TEST_GRAPH_PATH stage = omni.usd.get_context().get_stage() rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_ValidTarget.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Target") rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_OGTarget.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=og.INSTANCING_GRAPH_TARGET_PATH) rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_InvalidTarget.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/MissingTarget") rel = stage.GetPropertyAtPath(f"{graph_path}/ConstPrims.inputs:value") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Target") # avoids an error by removing the invalid prim after the graph is created omni.kit.commands.execute("DeletePrims", paths=["/World/MissingTarget"]) # Go through all the ReadPrim variations and validate that the image is expected. # In the case of a valid target the widget for the attribute should be a dropdown # Otherwise it should be a text field for node in nodes: node_name = node.get_prim_path().split("/")[-1] if not node_name.startswith("ReadPrim"): continue with self.subTest(node_name=node_name): test_img_name = f"test_{node_name.lower()}.png" # Select the node. usd_context.get_selection().set_selected_prim_paths([node.get_prim_path()], True) # Wait for property panel to converge await ui_test.human_delay(5) # Resize to fit the property panel, and take a snapshot await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=test_img_name) # ---------------------------------------------------------------------- async def test_extended_attributes(self): """ Exercise the OG properties widget with extended attributes """ usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) keys = og.Controller.Keys controller = og.Controller() # OGN Types that we will test resolving the inputs:value to supported_types = [ "half", "timecode", "half[]", "timecode[]", "double[2]", "double[3]", "double[4]", "double[2][]", "double[3][]", "double[4][]", "float[2]", "float[3]", "float[4]", "float[2][]", "float[3][]", "float[4][]", "half[2]", "half[3]", "half[4]", "half[2][]", "half[3][]", "half[4][]", "int[2]", "int[3]", "int[4]", "int[2][]", "int[3][]", "int[4][]", "matrixd[2]", "matrixd[3]", "matrixd[4]", "matrixd[2][]", "matrixd[3][]", "matrixd[4][]", "double", "double[]", "frame[4]", "frame[4][]", "quatd[4]", "quatf[4]", "quath[4]", "quatd[4][]", "quatf[4][]", "quath[4][]", "colord[3]", "colord[3][]", "colorf[3]", "colorf[3][]", "colorh[3]", "colorh[3][]", "colord[4]", "colord[4][]", "colorf[4]", "colorf[4][]", "colorh[4]", "colorh[4][]", "normald[3]", "normald[3][]", "normalf[3]", "normalf[3][]", "normalh[3]", "normalh[3][]", "pointd[3]", "pointd[3][]", "pointf[3]", "pointf[3][]", "pointh[3]", "pointh[3][]", "vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]", "texcoordd[2]", "texcoordd[2][]", "texcoordf[2]", "texcoordf[2][]", "texcoordh[2]", "texcoordh[2][]", "texcoordd[3]", "texcoordd[3][]", "texcoordf[3]", "texcoordf[3][]", "texcoordh[3]", "texcoordh[3][]", "string", "token[]", "token", ] attribute_names = [ self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name)) for type_name in supported_types ] expected_values = [ ogn.get_attribute_manager_type(type_name).sample_values()[0:2] for type_name in supported_types ] (graph, (_, write_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_PRIMS: [ ( "/World/Prim", { attrib_name: (usd_type, expected_value[0]) for attrib_name, usd_type, expected_value in zip( attribute_names, supported_types, expected_values ) }, ) ], keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Write", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Write.inputs:execIn"), ], keys.SET_VALUES: [ ("Write.inputs:name", "acc"), ("Write.inputs:primPath", "/World/Prim"), ("Write.inputs:usePath", True), ], }, ) await controller.evaluate(graph) # Select the prim. usd_context.get_selection().set_selected_prim_paths([write_node.get_prim_path()], True) # The UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # Test for attrib types that use OmniGraphAttributeValueModel async def test_numeric(name, value1, value2): controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]}) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(2) for base in ogab.OmniGraphBase._instances: # noqa: PLW0212 if base._object_paths[0].name == "inputs:value" and ( # noqa: PLW0212 isinstance(base, (ogam.OmniGraphGfVecAttributeSingleChannelModel, ogam.OmniGraphAttributeModel)) ): base.begin_edit() base.set_value(value1) await ui_test.human_delay(1) base.set_value(value2) await ui_test.human_delay(1) base.end_edit() await ui_test.human_delay(1) break # Test for attrib types that use ui.AbstractItemModel async def test_item(name, value1, value2): controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]}) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(2) for base in ogab.OmniGraphBase._instances: # noqa: PLW0212 if base._object_paths[0].name == "inputs:value": # noqa: PLW0212 base.begin_edit() base.set_value(value1) await ui_test.human_delay(1) base.set_value(value2) await ui_test.human_delay(1) base.end_edit() await ui_test.human_delay(1) break # Test for read-only array value - just run the code, no need to verify anything async def test_array(name, val): controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]}) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(2) for attrib_name, test_values in zip(attribute_names, expected_values): if attrib_name.endswith("_array"): await test_array(attrib_name, test_values[1]) elif attrib_name in ("string", "token"): await test_item(attrib_name, test_values[1], test_values[0]) else: # The set_value for some types take a component, others take the whole vector/matrix if isinstance(test_values[0], tuple) and not ( attrib_name.startswith("a_matrix") or attrib_name.startswith("a_frame") or attrib_name.startswith("a_quat") ): await test_numeric(attrib_name, test_values[1][0], test_values[0][0]) else: await test_numeric(attrib_name, test_values[1], test_values[0]) # Sanity check the final widget state display await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_extended_attributes.png") async def test_extended_output_attributes(self): """ Exercise the OG properties widget with extended attributes on read nodes """ usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) keys = og.Controller.Keys controller = og.Controller() (graph, (_, read_node, _,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_PRIMS: [(("/World/Prim", {"a_token": ("token", "Ahsoka")}))], keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Read", "omni.graph.nodes.ReadPrimAttribute"), ("Write", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Write.inputs:execIn"), ("Read.outputs:value", "Write.inputs:value"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("Read.inputs:name", "a_token"), ("Read.inputs:primPath", "/World/Prim"), ("Read.inputs:usePath", True), ("Write.inputs:name", "a_token"), ("Write.inputs:primPath", "/World/Prim"), ("Write.inputs:usePath", True), ], }, ) await controller.evaluate(graph) # Select the prim. usd_context.get_selection().set_selected_prim_paths([read_node.get_prim_path()], True) await ui_test.human_delay(5) # The UI should refreshes every frame ogab.AUTO_REFRESH_PERIOD = 0 # Sanity check the final widget state display await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="test_extended_output_attributes.png" ) async def test_layer_identifier_resolver(self): """ Test layer identifier resolver using WritePrimsV2 node /root.usda /sub/sublayer.usda (as a sublayer of root.usda) The OG graph will be created on /sub/sublayer.usda with layer identifier set to "./sublayer.usda" Then open /root.usda to test the relative path is successfully resolved relative to root.usda instead """ with tempfile.TemporaryDirectory() as tmpdirname: usd_context = omni.usd.get_context() controller = og.Controller() keys = og.Controller.Keys await self.docked_test_window( window=self._w._window, # noqa: PLW0212 width=450, height=500, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) sub_dir = os.path.join(tmpdirname, "sub") sublayer_fn = os.path.join(sub_dir, "sublayer.usda") sublayer = Sdf.Layer.CreateNew(sublayer_fn) sublayer.Save() root_fn = os.path.join(tmpdirname, "root.usda") root_layer = Sdf.Layer.CreateNew(root_fn) root_layer.subLayerPaths.append("./sub/sublayer.usda") root_layer.Save() success, error = await usd_context.open_stage_async(str(root_fn)) self.assertTrue(success, error) stage = usd_context.get_stage() # put the graph on sublayer # only need WritePrimsV2 node for UI tests with Usd.EditContext(stage, sublayer): (_, [write_prims_node], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Write.inputs:layerIdentifier", "./sublayer.usda"), ], }, ) # exit the "with" and switch edit target back to root layer usd_context.get_selection().set_selected_prim_paths([write_prims_node.get_prim_path()], True) await ui_test.human_delay(5) # Check the final widget state display # The "Layer Identifier" section should show "./sub/sublayer.usda" without any "<Invalid Layer>"" tag await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="test_layer_identifier_resolver.png" )
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_action.py
""" Tests that verify action UI-dependent nodes """ import unittest import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from omni.kit.test.teamcity import is_running_in_teamcity from omni.kit.viewport.utility import get_active_viewport from omni.kit.viewport.utility.camera_state import ViewportCameraState from pxr import Gf # ====================================================================== class TestOmniGraphAction(ogts.OmniGraphTestCase): """Encapsulate simple sanity tests""" # ---------------------------------------------------------------------- @unittest.skipIf(is_running_in_teamcity(), "Crashes on TC / Linux") async def test_camera_nodes(self): """Test camera-related node basic functionality""" keys = og.Controller.Keys controller = og.Controller() viewport_api = get_active_viewport() active_cam = viewport_api.camera_path persp_cam = "/OmniverseKit_Persp" self.assertEqual(active_cam.pathString, persp_cam) (graph, _, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("SetCam", "omni.graph.ui.SetActiveViewportCamera"), ], keys.SET_VALUES: [ ("SetCam.inputs:primPath", "/OmniverseKit_Top"), ], keys.CONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")], }, ) await controller.evaluate() active_cam = viewport_api.camera_path self.assertEqual(active_cam.pathString, "/OmniverseKit_Top") # be nice - set it back viewport_api.camera_path = persp_cam # Tests moving the camera and camera target controller.edit( graph, { keys.DISCONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")], }, ) await controller.evaluate() (graph, (_, _, get_pos, get_target), _, _) = controller.edit( graph, { keys.CREATE_NODES: [ ("SetPos", "omni.graph.ui.SetCameraPosition"), ("SetTarget", "omni.graph.ui.SetCameraTarget"), ("GetPos", "omni.graph.ui.GetCameraPosition"), ("GetTarget", "omni.graph.ui.GetCameraTarget"), ], keys.SET_VALUES: [ ("SetPos.inputs:primPath", persp_cam), ("SetPos.inputs:position", Gf.Vec3d(1.0, 2.0, 3.0)), # Target should be different than position ("SetTarget.inputs:target", Gf.Vec3d(-1.0, -2.0, -3.0)), ("SetTarget.inputs:primPath", persp_cam), ("GetPos.inputs:primPath", persp_cam), ("GetTarget.inputs:primPath", persp_cam), ], keys.CONNECT: [ ("OnTick.outputs:tick", "SetPos.inputs:execIn"), ("SetPos.outputs:execOut", "SetTarget.inputs:execIn"), ], }, ) await controller.evaluate() # XXX: May need to force these calls through legacy_viewport as C++ nodes call through to that interface. camera_state = ViewportCameraState(persp_cam) # , viewport=viewport_api, force_legacy_api=True) x, y, z = camera_state.position_world for a, b in zip([x, y, z], [1.0, 2.0, 3.0]): self.assertAlmostEqual(a, b, places=5) x, y, z = camera_state.target_world for a, b in zip([x, y, z], [-1.0, -2.0, -3.0]): self.assertAlmostEqual(a, b, places=5) # evaluate again, because push-evaluator may not have scheduled the getters after the setters await controller.evaluate() get_pos = og.Controller.get(controller.attribute(("outputs:position", get_pos))) for a, b in zip(get_pos, [1.0, 2.0, 3.0]): self.assertAlmostEqual(a, b, places=5) get_target = og.Controller.get(controller.attribute(("outputs:target", get_target))) for a, b in zip(get_target, [-1.0, -2.0, -3.0]): self.assertAlmostEqual(a, b, places=5) # ---------------------------------------------------------------------- @unittest.skipIf(is_running_in_teamcity(), "Flaky - needs investigation") async def test_on_new_frame(self): """Test OnNewFrame node""" keys = og.Controller.Keys controller = og.Controller() # Check that the NewFrame node is getting updated when frames are being generated (_, (new_frame_node,), _, _) = controller.edit( "/TestGraph", {keys.CREATE_NODES: [("NewFrame", "omni.graph.ui.OnNewFrame")]} ) attr = controller.attribute(("outputs:frameNumber", new_frame_node)) await og.Controller.evaluate() frame_num = og.Controller.get(attr) # Need to tick Kit before evaluation in order to update for _ in range(5): await omni.kit.app.get_app().next_update_async() await og.Controller.evaluate() self.assertLess(frame_num, og.Controller.get(attr))
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_ui_sanity.py
""" Tests that do basic sanity checks on the OmniGraph UI """ import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools as ogt import omni.kit.test import omni.usd from carb import log_warn from .._impl.menu import MENU_WINDOWS, Menu from .._impl.omnigraph_node_description_editor.main_editor import Editor # Data-driven information to allow creation of all windows without specifics. # This assumes every class has a static get_name() method so that prior existence can be checked, # and a show_window() or show() method which displays the window. # # Dictionary key is the attribute name in the test class under which this window is stored. # Value is a list of [class, args] where: # ui_class: Class type that instantiates the window # args: Arguments to be passed to the window's constructor # ALL_WINDOW_INFO = {"_ogn_editor_window": [Editor, []]} # ====================================================================== class TestOmniGraphUiSanity(ogts.OmniGraphTestCase): """Encapsulate simple sanity tests""" # ---------------------------------------------------------------------- async def test_open_and_close_all_omnigraph_ui(self): """Open and close all of the OmniGraph UI windows as a basic sanity check In order for this test to work all of the UI management classes must support these methods: show(): Build and display the window contents destroy(): Close the window and destroy the window elements And the classes must derive from (metaclass=Singleton) to avoid multiple instantiations """ class AllWindows: """Encapsulate all of the windows to be tested in an object for easier destruction""" def __init__(self): """Open and remember all of the windows (closing first if they were already open)""" # The graph window needs to be passed a graph. graph_path = "/World/TestGraph" og.Controller.edit({"graph_path": graph_path, "evaluator_name": "push"}) for (member, (ui_class, args)) in ALL_WINDOW_INFO.items(): setattr(self, member, ui_class(*args)) async def show_all(self): """Find all of the OmniGraph UI windows and show them""" for (member, (ui_class, _)) in ALL_WINDOW_INFO.items(): window = getattr(self, member) show_fn = getattr(window, "show_window", getattr(window, "show", None)) if show_fn: show_fn() # Wait for an update to ensure the window has been opened await omni.kit.app.get_app().next_update_async() else: log_warn(f"Not testing type {ui_class.__name__} - no show_window() or show() method") def destroy(self): """Destroy the members, which cleanly destroys the windows""" for member in ALL_WINDOW_INFO: ogt.destroy_property(self, member) all_windows = AllWindows() await all_windows.show_all() await omni.kit.app.get_app().next_update_async() all_windows.destroy() all_windows = None # ---------------------------------------------------------------------- async def test_omnigraph_ui_menu(self): """Verify that the menu operations all work""" menu = Menu() for menu_path in MENU_WINDOWS: menu.set_window_state(menu_path, True) await omni.kit.app.get_app().next_update_async() menu.set_window_state(menu_path, False) async def test_omnigraph_ui_node_creation(self): """Check that all of the registered omni.graph.ui nodes can be created without error.""" graph_path = "/World/TestGraph" (graph, *_) = og.Controller.edit({"graph_path": graph_path, "evaluator_name": "push"}) # Add one of every type of omni.graph.ui node to the graph. node_types = [t for t in og.get_registered_nodes() if t.startswith("omni.graph.ui")] prefix_len = len("omni.graph.ui_nodes.") node_names = [name[prefix_len:] for name in node_types] (_, nodes, _, _) = og.Controller.edit( graph, {og.Controller.Keys.CREATE_NODES: list(zip(node_names, node_types))} ) self.assertEqual(len(nodes), len(node_types), "Check that all nodes were created.") for i, node in enumerate(nodes): self.assertEqual( node.get_prim_path(), graph_path + "/" + node_names[i], f"Check node type '{node_types[i]}'" )
omniverse-code/kit/exts/omni.graph.ui/docs/prettycons-LICENSE.md
# prettycons License Icons made by prettycons from "https://www.flaticon.com/"
omniverse-code/kit/exts/omni.graph.ui/docs/Pixel_perfect-LICENSE.md
# PixelPerfect License Icons made by Pixel perfect from "https://www.flaticon.com/"
omniverse-code/kit/exts/omni.graph.ui/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.24.2] - 2023-02-06 - Fix for test failure ## [1.24.1] - 2022-12-08 ### Fixed - Make sure variable colour widgets use AbstractItemModel - Fixed tab not working on variable vector fields - Fixed UI update issues with graph variable widgets ## [1.24.0] - 2022-11-10 ### Added - Display initial and runtime values of graph variables ## [1.23.1] - 2022-10-28 ### Fixed - Undo on node attributes ## [1.23.0] - 2022-09-29 ### Changed - Added OmniGraphAttributeModel to public API ## [1.22.0] - 2022-09-27 ### Added - Widget for reporting timing information related to extension processing by OmniGraph ## [1.21.4] - 2022-09-14 ### Added - Instance variable properties remove underlying attribute when reset to default ## [1.21.3] - 2022-09-10 ### Added - Use id paramteter for Viewport picking request so a node will only generate request. ## [1.21.2] - 2022-08-25 ### Fixed - Modified the import path acceptance pattern to adhere to PEP8 guidelines - Fixed hot reload for the editors by correctly destroying menu items - Added FIXME comments recommended in a prior review ### Added - Button for Save-As to support being able to add multiple nodes in a single session ## [1.21.1] - 2022-08-25 ### Changed - Refactored scene frame to be widget-based instead of monolithic ## [1.21.0] - 2022-08-25 ### Added - UI for controlling new setting that turns deprecations into errors ## [1.20.0] - 2022-08-17 ### Added - Toolkit button for dumping out the extension information for OmniGraph users ### Removed - Obsolete migration buttons ### Changed - Refactored toolkit inspection frame to be widget-based instead of monolithic ## [1.19.0] - 2022-08-11 ### Added - ReadWindowSize node - 'widgetPath' inputs to ReadWidgetProperty, WriteWidgetProperty and WriteWidgetStyle nodes. ### Changed - WriteWidgetStyle now reports the full details of style sytax errors. ## [1.18.1] - 2022-08-10 ### Fixed - Applied formatting to all of the Python files ## [1.18.0] - 2022-08-09 ### Changed - Removed unused graph editor modules - Removed omni.kit.widget.graph and omni.kit.widget.fast_search dependencies ## [1.17.1] - 2022-08-06 ### Changed - OmniGraph(API) references changed to 'Visual Scripting' ## [1.17.0] - 2022-08-05 ### Added - Mouse press gestures to picking nodes ## [1.16.4] - 2022-08-05 ### Changed - Fixed bug related to parameter-tagged properties ## [1.16.3] - 2022-08-03 ### Fixed - All of the lint errors reported on the Python files in this extension ## [1.16.2] - 2022-07-28 ### Fixed - Spurious error messages about 'Node compute request is ignored because XXX is not request-driven' ## [1.16.1] - 2022-07-28 ### Changed - Fixes for OG property panel - compute_node_widget no longer flushes prim to FC ## [1.16.0] - 2022-07-25 ### Added - Viewport mouse event nodes for click, press/release, hover, and scroll ### Changed - Behavior of drag and picking nodes to be consistent ## [1.15.3] - 2022-07-22 ### Changed - Moving where custom metadata is set on the usd property so custom templates have access to it ## [1.15.2] - 2022-07-15 ### Added - test_omnigraph_ui_node_creation() ### Fixed - Missing graph context in test_open_and_close_all_omnigraph_ui() ### Changed - Set all of the old Action Graph Window code to be omitted from pyCoverage ## [1.15.1] - 2022-07-13 - OM-55771: File browser button ## [1.15.0] - 2022-07-12 ### Added - OnViewportDragged and ReadViewportDragState nodes ### Changed - OnPicked and ReadPickState, most importantly how OnPicked handles an empty picking event ## [1.14.0] - 2022-07-08 ### Fixed - ReadMouseState not working with display scaling or multiple workspace windows ### Changed - Added 'useRelativeCoordinates' input and 'window' output to ReadMouseState ## [1.13.0] - 2022-07-08 ### Changed - Refactored imports from omni.graph.tools to get the new locations ### Added - Added test for public API consistency ## [1.12.0] - 2022-07-07 ### Changed - Overhaul of SetViewportMode - Changed default viewport for OnPicked/ReadPickState to 'Viewport' - Allow templates in omni.graph.ui to be loaded ## [1.11.0] - 2022-07-04 ### Added - OgnSetViewportMode.widgetPath attribute ### Changed - OgnSetViewportMode does not enable execOut if there's an error ## [1.10.1] - 2022-06-28 ### Changed - Change default viewport for SetViewportMode/OnPicked/ReadPickState to 'Viewport Next' ## [1.10.0] - 2022-06-27 ### Changed - Move ReadMouseState into omni.graph.ui - Make ReadMouseState coords output window-relative ## [1.9.0] - 2022-06-24 ### Added - Added PickingManipulator for prim picking nodes controlled from SetViewportMode - Added OnPicked and ReadPickState nodes for prim picking ## [1.8.5] - 2022-06-17 ### Added - Added instancing ui elements ## [1.8.4] - 2022-06-07 ### Changed - Updated imports to remove explicit imports - Added explicit generator settings ## [1.8.3] - 2022-05-24 ### Added - Remove dependency on Viewport for Camera Get/Set operations - Run tests with omni.hydra.pxr/Storm instead of RTX ## [1.8.2] - 2022-05-23 ### Added - Use omni.kit.viewport.utility for Viewport nodes and testing. ## [1.8.1] - 2022-05-20 ### Fixed - Change cls.default_model_table to correctly set model_cls in _create_color_or_drag_per_channel for vec2d, vec2f, vec2h, and vec2i omnigraph attributes - Infer default values from type for OG attributes when not provided in metadata ## [1.8.0] - 2022-05-05 ### Added - Support for enableLegacyPrimConnections setting, used by DS but deprecated ### Fixed - Tooltips and descriptions for settings that are interdependent ## [1.7.1] - 2022-04-29 ### Changed - Made tests derive from OmniGraphTestCase ## [1.7.0] - 2022-04-26 ### Added - GraphVariableCustomLayout property panel widget moved from omni.graph.instancing ## [1.6.1] - 2022-04-21 ### Fixed - Some broken and out of date tests. ## [1.6.0] - 2022-04-18 ### Changed - Property Panel widget for OG nodes now reads attribute values from Fabric backing instead of USD. ## [1.5.0] - 2022-03-17 ### Added - Added _add\_create\_menu\_type_ and _remove\_create\_menu\_type_ functions to allow kit-graph extensions to add their corresponding create graph menu item ### Changed - _Menu.create\_graph_ now return the wrapper node, and will no longer pops up windows - _Menu_ no longer creates the three menu items _Create\Visual Sciprting\Action Graph_, _Create\Visual Sciprting\Push Graph_, _Create\Visual Sciprting\Lazy Graph_ at extension start up - Creating a graph now will directly create a graph with default title and open it ## [1.4.4] - 2022-03-11 ### Added - Added glyph icons for menu items _Create/Visual Scripting/_ and items under this submenu - Added Create Graph context menu for viewport and stage windows. ## [1.4.3] - 2022-03-11 ### Fixed - Node is written to backing store when the custom widget is reset to ensure that view is up to date with FC. ## [1.4.2] - 2022-03-07 ### Changed - Add spliter for items in submenu _Window/Visual Scripting_ - Renamed menu item _Create/Graph_ to _Create/Visual Scripting_ - Changed glyph icon for _Create/Visual Scripting_ and added glyph icons for all sub menu items under ## [1.4.1] - 2022-02-22 ### Changed - Change _Window/Utilities/Attribute Connection_, _Window/Visual Scripting/Node Description Editor_ and _Window/Visual Scripting/Toolkit_ into toggle buttons - Added OmniGraph.svg glyph for _Create/Graph_ ## [1.4.0] - 2022-02-16 ### Changes - Decompose the original OmniGraph menu in toolbar into several small menu items under correct categories ## [1.3.0] - 2022-02-10 ### Added - Toolkit access to the setting that uses schema prims in graphs, and a migration tool for same ## [1.2.2] - 2022-01-28 ### Fixed - Potential crash when handling menu or stage changes ## [1.2.1] - 2022-01-21 ### Fixed - ReadPrimAttribute/WritePrimAttribute property panel when usePath is true ## [1.2.0] - 2022-01-06 ### Fixed - Property window was generating exceptions when a property is added to an OG prim. ## [1.1.0] - 2021-12-02 ### Changes - Fixed compute node widget bug with duplicate graphs ## [1.0.2] - 2021-11-24 ### Changes - Fixed compute node widget to work with scoped graphs ## [1.0.1] - 2021-02-10 ### Changes - Updated StyleUI handling ## [1.0.0] - 2021-02-01 ### Initial Version - Started changelog with initial released version of the OmniGraph core
omniverse-code/kit/exts/omni.graph.ui/docs/OmniGraphSettingsEditor.rst
.. _omnigraph_settings_editor: OmniGraph Settings Editor ========================= The settings editor provides a method of modifying settings which affect the OmniGraph appearance and evaluation.
omniverse-code/kit/exts/omni.graph.ui/docs/README.md
# OmniGraph UI [omni.graph.ui] OmniGraph is a graph system that provides a compute framework for Omniverse through the use of nodes and graphs. This extension contains some supporting UI-related components and nodes for OmniGraph.
omniverse-code/kit/exts/omni.graph.ui/docs/index.rst
OmniGraph User Interfaces ######################### .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension**: omni.graph.ui,**Documentation Generated**: |today| While other UI elements allow indirect interaction with the OmniGraph, the ones listed here provide direct manipulation of OmniGraph nodes, attributes, and connections. .. toctree:: :maxdepth: 1 :glob: *
omniverse-code/kit/exts/omni.graph.ui/docs/OmniGraphNodeDescriptionEditor.rst
.. _omnigraph_node_description_editor: OmniGraph Node Description Editor ================================= The node description editor is the user interface to create and edit the code that implements OmniGraph Nodes, as well as providing a method for creating a minimal extension that can be used to bring them into Kit. Follow along with the tutorials `here <https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.graph.core/docs/nodes.html>` to see how this editor can be used to create an OmniGraph node in Python.
omniverse-code/kit/exts/omni.graph.ui/docs/Overview.md
# OmniGraph User Interfaces ```{csv-table} **Extension**: omni.graph.ui,**Documentation Generated**: {sub-ref}`today` ``` While other UI elements allow indirect interaction with the OmniGraph, the ones listed here provide direct manipulation of OmniGraph nodes, attributes, and connections.
omniverse-code/kit/exts/omni.graph.ui/data/tests/test_variables.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (500, 500, 500) double3 target = (-0.0000039780385918675165, 0.00000795607684267452, -0.000003978038364493841) } dictionary Right = { double3 position = (-50000, 0, 0) double radius = 500 } dictionary Top = { double3 position = (0, 50000, 0) double radius = 500 } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { float3 "rtx:debugView:pixelDebug:textColor" = (0, 1e18, 0) float3 "rtx:dynamicDiffuseGI:probeCounts" = (6, 6, 6) float3 "rtx:dynamicDiffuseGI:probeGridOrigin" = (-210, -250, -10) float3 "rtx:dynamicDiffuseGI:volumeSize" = (600, 440, 300) float3 "rtx:fog:fogColor" = (0.75, 0.75, 0.75) float3 "rtx:lightspeed:material:overrideAlbedo" = (0.5, 0.5, 0.5) float3 "rtx:lightspeed:material:overrideEmissiveColor" = (0.5, 0.5, 0.5) float3 "rtx:post:backgroundZeroAlpha:backgroundDefaultColor" = (0, 0, 0) float3 "rtx:post:colorcorr:contrast" = (1, 1, 1) float3 "rtx:post:colorcorr:gain" = (1, 1, 1) float3 "rtx:post:colorcorr:gamma" = (1, 1, 1) float3 "rtx:post:colorcorr:offset" = (0, 0, 0) float3 "rtx:post:colorcorr:saturation" = (1, 1, 1) float3 "rtx:post:colorgrad:blackpoint" = (0, 0, 0) float3 "rtx:post:colorgrad:contrast" = (1, 1, 1) float3 "rtx:post:colorgrad:gain" = (1, 1, 1) float3 "rtx:post:colorgrad:gamma" = (1, 1, 1) float3 "rtx:post:colorgrad:lift" = (0, 0, 0) float3 "rtx:post:colorgrad:multiply" = (1, 1, 1) float3 "rtx:post:colorgrad:offset" = (0, 0, 0) float3 "rtx:post:colorgrad:whitepoint" = (1, 1, 1) float3 "rtx:post:lensDistortion:lensFocalLengthArray" = (10, 30, 50) float3 "rtx:post:lensFlares:anisoFlareFalloffX" = (450, 475, 500) float3 "rtx:post:lensFlares:anisoFlareFalloffY" = (10, 10, 10) float3 "rtx:post:lensFlares:cutoffPoint" = (2, 2, 2) float3 "rtx:post:lensFlares:haloFlareFalloff" = (10, 10, 10) float3 "rtx:post:lensFlares:haloFlareRadius" = (75, 75, 75) float3 "rtx:post:lensFlares:isotropicFlareFalloff" = (50, 50, 50) float3 "rtx:post:tonemap:whitepoint" = (1, 1, 1) float3 "rtx:raytracing:inscattering:singleScatteringAlbedo" = (0.9, 0.9, 0.9) float3 "rtx:raytracing:inscattering:transmittanceColor" = (0.5, 0.5, 0.5) float3 "rtx:sceneDb:ambientLightColor" = (0.1, 0.1, 0.1) } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def OmniGraph "ActionGraph" { token evaluationMode = "Automatic" token evaluator:type = "execution" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 5) custom float[] graph:variable:arrayvar ( customData = { token scope = "private" } displayName = "arrayvar" ) custom bool graph:variable:boolvar ( customData = { token scope = "private" } displayName = "boolvar" ) custom float3 graph:variable:float3var ( customData = { token scope = "private" } displayName = "float3var" ) custom float graph:variable:floatvar ( customData = { token scope = "private" } displayName = "floatvar" ) custom string graph:variable:stringvar = "default" ( customData = { token scope = "private" } displayName = "stringvar" ) custom token graph:variable:tokenvar = "default" ( customData = { token scope = "private" } displayName = "tokenvar" ) token pipelineStage = "pipelineStageSimulation" } def Scope "Instance" ( prepend apiSchemas = ["OmniGraphAPI"] ) { rel omniGraphs = </World/ActionGraph> } }
omniverse-code/kit/exts/omni.graph.ui/data/tests/compound_node_test.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (500, 500, 500) double3 target = (-0.0000039780385918675165, 0.00000795607684267452, -0.000003978038364493841) } dictionary Right = { double3 position = (-50000, 0, 0) double radius = 500 } dictionary Top = { double3 position = (0, 50000, 0) double radius = 500 } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { float3 "rtx:debugView:pixelDebug:textColor" = (0, 1e18, 0) float3 "rtx:dynamicDiffuseGI:probeCounts" = (6, 6, 6) float3 "rtx:dynamicDiffuseGI:probeGridOrigin" = (-210, -250, -10) float3 "rtx:dynamicDiffuseGI:volumeSize" = (600, 440, 300) float3 "rtx:fog:fogColor" = (0.75, 0.75, 0.75) float3 "rtx:lightspeed:material:overrideAlbedo" = (0.5, 0.5, 0.5) float3 "rtx:lightspeed:material:overrideEmissiveColor" = (0.5, 0.5, 0.5) float3 "rtx:post:backgroundZeroAlpha:backgroundDefaultColor" = (0, 0, 0) float3 "rtx:post:colorcorr:contrast" = (1, 1, 1) float3 "rtx:post:colorcorr:gain" = (1, 1, 1) float3 "rtx:post:colorcorr:gamma" = (1, 1, 1) float3 "rtx:post:colorcorr:offset" = (0, 0, 0) float3 "rtx:post:colorcorr:saturation" = (1, 1, 1) float3 "rtx:post:colorgrad:blackpoint" = (0, 0, 0) float3 "rtx:post:colorgrad:contrast" = (1, 1, 1) float3 "rtx:post:colorgrad:gain" = (1, 1, 1) float3 "rtx:post:colorgrad:gamma" = (1, 1, 1) float3 "rtx:post:colorgrad:lift" = (0, 0, 0) float3 "rtx:post:colorgrad:multiply" = (1, 1, 1) float3 "rtx:post:colorgrad:offset" = (0, 0, 0) float3 "rtx:post:colorgrad:whitepoint" = (1, 1, 1) float3 "rtx:post:lensDistortion:lensFocalLengthArray" = (10, 30, 50) float3 "rtx:post:lensFlares:anisoFlareFalloffX" = (450, 475, 500) float3 "rtx:post:lensFlares:anisoFlareFalloffY" = (10, 10, 10) float3 "rtx:post:lensFlares:cutoffPoint" = (2, 2, 2) float3 "rtx:post:lensFlares:haloFlareFalloff" = (10, 10, 10) float3 "rtx:post:lensFlares:haloFlareRadius" = (75, 75, 75) float3 "rtx:post:lensFlares:isotropicFlareFalloff" = (50, 50, 50) float3 "rtx:post:tonemap:whitepoint" = (1, 1, 1) float3 "rtx:raytracing:inscattering:singleScatteringAlbedo" = (0.9, 0.9, 0.9) float3 "rtx:raytracing:inscattering:transmittanceColor" = (0.5, 0.5, 0.5) float3 "rtx:sceneDb:ambientLightColor" = (0.1, 0.1, 0.1) } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def Scope "Compounds" { def OmniGraphCompoundNodeType "TestCompound" { prepend rel omni:graph:asset = </World/Compounds/TestCompound/Graph> token[] omni:graph:categories = ["Compounds", "debug", "other"] string omni:graph:description = "This is a description" custom rel omni:graph:input:input = </World/Compounds/TestCompound/Graph/magnitude.inputs:input> custom rel omni:graph:input:input_01 = </World/Compounds/TestCompound/Graph/magnitude_01.inputs:input> token omni:graph:namespace = "local.nodes" custom rel omni:graph:output:sum = </World/Compounds/TestCompound/Graph/add.outputs:sum> custom rel omni:graph:output:sum_01 = </World/Compounds/TestCompound/Graph/add_02.outputs:sum> token[] omni:graph:tags = ["taga", "tagb"] string omni:graph:uiName = "Test Compound" def OmniGraph "Graph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 5) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "add" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:a prepend token inputs:a.connect = </World/Compounds/TestCompound/Graph/magnitude_01.outputs:magnitude> custom token inputs:b prepend token inputs:b.connect = </World/Compounds/TestCompound/Graph/magnitude_01.outputs:magnitude> token node:type = "omni.graph.nodes.Add" int node:typeVersion = 1 custom token outputs:sum uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (562, 15) } def OmniGraphNode "add_02" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:a prepend token inputs:a.connect = </World/Compounds/TestCompound/Graph/magnitude.outputs:magnitude> custom token inputs:b prepend token inputs:b.connect = </World/Compounds/TestCompound/Graph/magnitude.outputs:magnitude> token node:type = "omni.graph.nodes.Add" int node:typeVersion = 1 custom token outputs:sum uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (560, 167) } def OmniGraphNode "magnitude" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:input token node:type = "omni.graph.nodes.Magnitude" int node:typeVersion = 1 custom token outputs:magnitude uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (288, 153) } def OmniGraphNode "magnitude_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:input token node:type = "omni.graph.nodes.Magnitude" int node:typeVersion = 1 custom token outputs:magnitude uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (290, -10) } } } } }
omniverse-code/kit/exts/omni.kit.menu.aov/PACKAGE-LICENSES/omni.kit.menu.aov-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.menu.aov/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.1.3" category = "Internal" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "AOV Menu" description="Implementation of AOV Menu." # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "ui", "menu", "aov"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" [dependencies] "omni.usd" = {} "omni.kit.menu.utils" = {} "omni.kit.context_menu" = {} "omni.kit.commands" = {} "omni.kit.widget.layers" = {} "omni.kit.actions.core" = {} [[python.module]] name = "omni.kit.menu.aov" [setting] exts."omni.kit.menu.create".original_svg_color = false [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/file/ignoreUnsavedStage=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window", ] dependencies = [ "omni.hydra.pxr", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.ui_test", ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop "*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available ]
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/__init__.py
from .scripts import *
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/aov_actions.py
import omni.kit.actions.core def register_actions(extension_id, cls): action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "AOV Menu Actions" # actions action_registry.register_action( "omni.kit.menu.aov", "create_single_aov", cls._on_create_single_aov, display_name="Create->AOV", description="Create AOV", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/aov.py
import omni.ext import omni.kit.menu.utils import omni.kit.context_menu import omni.kit.commands from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder from pxr import Sdf, Usd, UsdUtils, Gf from .aov_actions import register_actions, deregister_actions class AOVMenuExtension(omni.ext.IExt): def __init__(self): self._aov_menu_list = [] def on_startup(self, ext_id): self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name, AOVMenuExtension) self._register_menu() self._register_context_menu() def on_shutdown(self): deregister_actions(self._ext_name) omni.kit.menu.utils.remove_menu_items(self._aov_menu_list, "Create") self._aov_menu_list = None self._context_menu = None def _register_menu(self): self._aov_menu_list = [ MenuItemDescription(name="AOV", glyph="AOV_dark.svg", appear_after=[MenuItemOrder.LAST], onclick_action=("omni.kit.menu.aov", "create_single_aov")) ] omni.kit.menu.utils.add_menu_items(self._aov_menu_list, "Create") def _register_context_menu(self): menu_dict = { 'glyph': "AOV_dark.svg", 'name': 'AOV', 'show_fn': [], 'onclick_fn': AOVMenuExtension._on_create_single_aov } self._context_menu = omni.kit.context_menu.add_menu(menu_dict, "CREATE") @staticmethod def _create_render_prim(prim_type, prim_path): import omni.usd from omni.kit.widget.layers import LayerUtils stage = omni.usd.get_context().get_stage() session_layer = stage.GetSessionLayer() current_edit_layer = Sdf.Find(LayerUtils.get_edit_target(stage)) swap_edit_targets = current_edit_layer != session_layer rendervar_list = [ ("ldrColor", {"sourceName": "LdrColor"}), ("hdrColor", {"sourceName": "HdrColor"}), ("PtDirectIllumation", {"sourceName": "PtDirectIllumation"}), ("PtGlobalIllumination", {"sourceName": "PtGlobalIllumination"}), ("PtReflections", {"sourceName": "PtReflections"}), ("PtRefractions", {"sourceName": "PtRefractions"}), ("PtSelfIllumination", {"sourceName": "PtSelfIllumination"}), ("PtBackground", {"sourceName": "PtBackground"}), ("PtWorldNormal", {"sourceName": "PtWorldNormal"}), ("PtWorldPos", {"sourceName": "PtWorldPos"}), ("PtZDepth", {"sourceName": "PtZDepth"}), ("PtVolumes", {"sourceName": "PtVolumes"}), ("PtMultiMatte0", {"sourceName": "PtMultiMatte0"}), ("PtMultiMatte1", {"sourceName": "PtMultiMatte1"}), ("PtMultiMatte2", {"sourceName": "PtMultiMatte2"}), ("PtMultiMatte3", {"sourceName": "PtMultiMatte3"}), ("PtMultiMatte4", {"sourceName": "PtMultiMatte4"}), ("PtMultiMatte5", {"sourceName": "PtMultiMatte5"}), ("PtMultiMatte6", {"sourceName": "PtMultiMatte6"}), ("PtMultiMatte7", {"sourceName": "PtMultiMatte7"}), ] ## create prim. /Render is on session layer but need new prims in currrent layer try: if not current_edit_layer.GetPrimAtPath('/Render'): omni.kit.commands.execute("CreatePrim", prim_path="/Render", prim_type="Scope", attributes={}, select_new_prim=False) if not current_edit_layer.GetPrimAtPath('/Render/Vars'): omni.kit.commands.execute("CreatePrim", prim_path="/Render/Vars", prim_type="Scope", attributes={}, select_new_prim=False) omni.kit.commands.execute("CreatePrim", prim_path=prim_path, prim_type="RenderProduct", attributes={}, select_new_prim=False) for var_name, attributes in rendervar_list: if not current_edit_layer.GetPrimAtPath(f"/Render/Vars/{var_name}"): omni.kit.commands.execute("CreatePrim", prim_path=f"/Render/Vars/{var_name}", prim_type="RenderVar", attributes=attributes, select_new_prim=False) if swap_edit_targets: LayerUtils.set_edit_target(stage, session_layer.identifier) # set /Render visible & non-deletable in stage window... render_prim = stage.GetPrimAtPath("/Render") omni.usd.editor.set_hide_in_stage_window(render_prim, False) omni.usd.editor.set_no_delete(render_prim, True) # set /Render/Vars visible & non-deletable in stage window... vars_prim = stage.GetPrimAtPath("/Render/Vars") omni.usd.editor.set_hide_in_stage_window(vars_prim, False) omni.usd.editor.set_no_delete(vars_prim, True) finally: if swap_edit_targets: LayerUtils.set_edit_target(stage, current_edit_layer.identifier) prim = stage.GetPrimAtPath(prim_path) if prim: for var_name, attributes in rendervar_list: omni.kit.commands.execute("AddRelationshipTarget", relationship=prim.GetRelationship('orderedVars'), target=f"/Render/Vars/{var_name}") prim.CreateAttribute("resolution", Sdf.ValueTypeNames.Int2, False).Set(Gf.Vec2i(1280, 720)) @staticmethod def _on_create_single_aov(objects=None): with omni.kit.undo.group(): stage = omni.usd.get_context().get_stage() prim_path = Sdf.Path(omni.usd.get_stage_next_free_path(stage, "/Render/RenderView", False)) AOVMenuExtension._create_render_prim("RenderProduct", prim_path)
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/__init__.py
from .aov import *
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/tests/aov_tests.py
import sys import re import asyncio import unittest import carb import omni.kit.test import omni.ui as ui from omni.kit import ui_test class WindowStub(): """stub window class for use with WidgetRef & """ def undock(_): pass def focus(_): pass window_stub = WindowStub() class TestMenuAOVs(omni.kit.test.AsyncTestCase): async def setUp(self): import omni.kit.material.library # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() await ui_test.human_delay() async def tearDown(self): pass def get_menubar(self) -> ui_test.WidgetRef: from omni.kit.mainwindow import get_main_window window = get_main_window() return ui_test.WidgetRef(widget=window._ui_main_window.main_menu_bar, path="MainWindow//Frame/MenuBar") def find_menu(self, menubar: ui_test.WidgetRef, path: str) -> ui_test.WidgetRef: for widget in menubar.find_all("**/"): if isinstance(widget.widget, ui.Menu) or isinstance(widget.widget, ui.MenuItem): if widget.widget.text.encode('ascii', 'ignore').decode().strip() == path: return ui_test.WidgetRef(widget.widget, path="xxx", window=window_stub) return None async def test_aov_menus(self): from omni.kit.menu.aov import AOVMenuExtension # get root menu menubar = self.get_menubar() # new stage await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # verify one prim prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']] self.assertTrue(prim_list == ['/Sphere']) # use menu Create/AOV create_widget = self.find_menu(menubar, "Create") await create_widget.click(pos=create_widget.position+ui_test.Vec2(0, 5)) aov_widget = self.find_menu(create_widget, "AOV") await aov_widget.click(pos=aov_widget.position+ui_test.Vec2(50, 5)) # verify multiple prims prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']] self.assertFalse(prim_list == ['/Sphere']) # undo changes omni.kit.undo.undo() # verify one prim prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']] self.assertTrue(prim_list == ['/Sphere']) # new stage to prevent layout dialogs await omni.usd.get_context().new_stage_async()
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/tests/__init__.py
from .aov_tests import *
omniverse-code/kit/exts/omni.kit.usda_edit/PACKAGE-LICENSES/omni.kit.usda_edit-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.usda_edit/config/extension.toml
[package] title = "USDA Editor" description = "Context menu to edit USD layers as USDA files" authors = ["NVIDIA"] version = "1.1.10" changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" readme = "docs/README.md" icon = "data/icon.png" category = "Internal" feature = true [[python.module]] name = "omni.kit.usda_edit" [dependencies] "omni.kit.pip_archive" = {} "omni.ui" = {} "omni.usd" = {} "omni.usd.libs" = {} # Additional python module with tests, to make them discoverable by test system. [[python.module]] name = "omni.kit.usda_edit.tests"
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/content_browser_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.usd from . import editor from .layer_watch import LayerWatch from .usda_edit_utils import is_extension_loaded import os def content_browser_available() -> bool: """Returns True if the extension "omni.kit.widget.content_browser" is loaded""" return is_extension_loaded("omni.kit.window.content_browser") class ContentBrowserMenu: """ When this object is alive, Layers 2.0 has the additional context menu with the items that allow to edit the layer in the external editor. """ def __init__(self): import omni.kit.window.content_browser as content self._content_window = content.get_content_window() self.__start_name = self._content_window.add_context_menu( "Edit...", "menu_rename.svg", ContentBrowserMenu.start_editing, ContentBrowserMenu.is_not_editing ) self.__end_name = self._content_window.add_context_menu( "Finish editing", "menu_delete.svg", ContentBrowserMenu.stop_editing, ContentBrowserMenu.is_editing ) def destroy(self): """Stop all watchers and remove the menu from Layers 2.0""" if content_browser_available(): self._content_window.delete_context_menu(self.__start_name) self._content_window.delete_context_menu(self.__end_name) self.__start_name = None self.__end_name = None self._content_window = None LayerWatch().stop_all() @staticmethod def start_editing(menu: str, content_url: str): """Start watching for the layer and run the editor""" usda_filename = LayerWatch().start_watch(content_url) editor.run_editor(usda_filename) @staticmethod def stop_editing(menu: str, content_url: str): """Stop watching for the layer and remove the temporary files""" LayerWatch().stop_watch(content_url) @staticmethod def is_editing(content_url: str) -> bool: """Returns true if the layer is already watched""" return LayerWatch().has_watch(content_url) @staticmethod def is_not_editing(content_url: str) -> bool: """Returns true if the layer is not watched""" return omni.usd.is_usd_writable_filetype(content_url) and not ContentBrowserMenu.is_editing(content_url)
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/extension_usda.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .layers_menu import layers_available from .layers_menu import LayersMenu from .content_menu import ContentMenu from .content_browser_menu import content_browser_available from .content_browser_menu import ContentBrowserMenu import omni.ext import omni.kit.app class UsdaEditExtension(omni.ext.IExt): def on_startup(self, ext_id): # Setup a callback for the event app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() self.__extensions_subscription = ext_manager.get_change_event_stream().create_subscription_to_pop( self._on_event, name="omni.kit.usda_edit" ) self.__layers_menu = None self.__content_menu = None self.__content_browser_menu = None self._on_event(None) # When kit exits we won't get a change event for content_browser unloading so we need to resort to # an explicit subscription to its enable/disable events. # # If content_browser is already enabled then we will immediately get a callback for it, so we want # to do this last. self.__content_browser_hook = ext_manager.subscribe_to_extension_enable( self._on_browser_enabled, self._on_browser_disabled, 'omni.kit.window.content_browser') def _on_browser_enabled(self, ext_id: str): if not self.__content_browser_menu: self.__content_browser_menu = ContentBrowserMenu() def _on_browser_disabled(self, ext_id: str): if self.__content_browser_menu: self.__content_browser_menu.destroy() self.__content_browser_menu = None def _on_event(self, event): # Create/destroy the menu in the Layers window if self.__layers_menu: if not layers_available(): self.__layers_menu.destroy() self.__layers_menu = None else: if layers_available(): self.__layers_menu = LayersMenu() # TODO: Create/destroy the menu in the Content Browser if self.__content_menu: self.__content_menu.destroy() self.__content_menu = None def on_shutdown(self): self.__extensions_subscription = None self.__content_browser_hook = None if self.__layers_menu: self.__layers_menu.destroy() self.__layers_menu = None if self.__content_menu: self.__content_menu.destroy() self.__content_menu = None if self.__content_browser_menu: self.__content_browser_menu.destroy() self.__content_browser_menu = None
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/layer_watch.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from pathlib import Path from pxr import Sdf from pxr import Tf from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer import asyncio import carb import functools import omni.kit.app import os.path import random import string import tempfile import traceback def handle_exception(func): """ Decorator to print exception in async functions """ @functools.wraps(func) async def wrapper(*args, **kwargs): try: return await func(*args, **kwargs) except asyncio.CancelledError: # We always cancel the task. It's not a problem. pass except Exception as e: carb.log_error(f"Exception when async '{func}'") carb.log_error(f"{e}") carb.log_error(f"{traceback.format_exc()}") return wrapper def Singleton(class_): """ A singleton decorator. TODO: It's also available in omni.kit.widget.stage. We need a utility extension where we can put the utilities like this. """ instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @Singleton class LayerWatch: """ Singleton object that contains all the layer watchers. When the watcher is removed, the tmp file and directory are also removed. """ def __init__(self): self.__items = {} def start_watch(self, identifier): """ Create a temporary usda file and watch it. When this file is changed, the layer with the given identifier will be updated. """ watch_item = self.__items.get(identifier, None) if not watch_item: watch_item = LayerWatchItem(identifier) self.__items[identifier] = watch_item return watch_item.file_name def stop_watch(self, identifier): """ Stop watching to the temporary file created to the layer with the given identifier. It will remove the temporary file. """ if identifier in self.__items: self.__items[identifier].destroy() del self.__items[identifier] def has_watch(self, identifier): """ Return true if the layer with the given identifier is watched. """ return identifier in self.__items def stop_all(self): """ Stop watching for all the layers. """ for _, watch in self.__items.items(): watch.destroy() self.__items = {} @handle_exception async def wait_import_async(self, identifier): """ Wait for the importing of the layer. It happens when the layer is changed. """ if identifier in self.__items: await self.__items[identifier].wait_import_async() class LayerWatchItem(FileSystemEventHandler): def __init__(self, identifier): super().__init__() # SdfLayer self.__layer = Sdf.Layer.FindOrOpen(identifier) # Generate random name for temp directory while True: letters = string.ascii_lowercase dir_name = "kit_usda_" + "".join(random.choice(letters) for i in range(8)) tmp_path = Path(tempfile.gettempdir()).joinpath(dir_name) if not tmp_path.exists(): break # Create temporary directory tmp_path.mkdir() # Create temporary usda file tmp_file_path = tmp_path.joinpath(Tf.MakeValidIdentifier(Path(identifier).stem) + ".usda") self.__file_name = tmp_file_path.resolve().__str__() self.__layer.Export(self.__file_name) # Save the timestamp self.__last_mtime = os.path.getmtime(self.__file_name) self.__build_task = None self.__loop = asyncio.get_event_loop() # Watch the file self.__observer = Observer() self.__observer.schedule(self, path=tmp_path, recursive=False) self.__observer.start() # This event is set when the layer is re-imported. self.__imported_event = asyncio.Event() @property def file_name(self): """Return the temporary file name""" return self.__file_name def on_modified(self, event): """Called by watchdog when the temporary file is changed""" # Check it's the file we are watching. if event.src_path != self.file_name: return # Check the modification time. mtime = os.path.getmtime(self.file_name) if self.__last_mtime == mtime: return self.__last_mtime = mtime # Watchdog calls callback from different thread and USD doesn't like # it. We need to import USDA from the main thread. if self.__build_task: self.__build_task.cancel() self.__build_task = asyncio.ensure_future(self.__import(), loop=self.__loop) @handle_exception async def __import(self): """Import temporary file to the USD layer""" # Wait one frame on the case there was multiple events at the same time await omni.kit.app.get_app().next_update_async() file_name = self.file_name # The file extension. For anonymous layers it's ".sdf" format_id = f".{self.__layer.GetFileFormat().formatId}" if format_id == ".omni_usd" or format_id == ".usd_omni_wrapper": # The layer is on the omni server # Import is not implemented in the Omniverse file format. So we # clear it and transfer the content to the layer on the server. usda = Sdf.Layer.FindOrOpen(file_name) self.__layer.Clear() self.__layer.TransferContent(usda) else: # USD can't do cross-format Import, but it can do cross-format # export. if Path(file_name).suffix != format_id: # Export usda to the format of the layer. usda = Sdf.Layer.FindOrOpen(file_name) file_name = file_name + format_id usda.Export(file_name) # Import self.__layer.Import(file_name) if not self.__layer.anonymous: # Save if it's not an anonymous layer. So the edit goes directly to # the server or to the filesystem. self.__layer.Save() self.__imported_event.set() self.__imported_event.clear() @handle_exception async def wait_import_async(self): """ Wait for the importing of the layer. It happens when the layer is changed. """ await self.__imported_event.wait() def destroy(self): """Stop watching. Delete the temporary file and the temporary directory.""" if self.__observer: self.__observer.stop() # Wait when it stops. # TODO: We need to stop all of them and then join all of them. self.__observer.join() self.__observer = None if self.__layer: self.__layer = None # Remove tmp file and tmp folder if os.path.exists(self.__file_name): tmp_path = Path(self.__file_name).parent for f in tmp_path.iterdir(): if f.is_file(): f.unlink() tmp_path.rmdir() self.__imported_event.set() def __del__(self): self.destroy()
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/__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_usda import UsdaEditExtension
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/layers_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from . import editor from .layer_watch import LayerWatch from .usda_edit_utils import is_extension_loaded def layers_available() -> bool: """Returns True if the extension "omni.kit.widget.layers" is loaded""" return is_extension_loaded("omni.kit.widget.layers") class LayersMenu: """ When this object is alive, Layers 2.0 has the additional context menu with the items that allow to edit the layer in the external editor. """ def __init__(self): import omni.kit.widget.layers as layers self.__menu_subscription = layers.ContextMenu.add_menu( [ {"name": ""}, { "name": "Edit...", "glyph": "menu_rename.svg", "show_fn": [ layers.ContextMenu.is_layer_item, layers.ContextMenu.is_not_missing_layer, layers.ContextMenu.is_layer_writable, layers.ContextMenu.is_layer_not_locked_by_other, layers.ContextMenu.is_layer_and_parent_unmuted, LayersMenu.is_not_editing, ], "onclick_fn": LayersMenu.start_editing, }, { "name": "Finish editing", "glyph": "menu_delete.svg", "show_fn": [layers.ContextMenu.is_layer_item, LayersMenu.is_editing], "onclick_fn": LayersMenu.stop_editing, }, ] ) def destroy(self): """Stop all watchers and remove the menu from Layers 2.0""" self.__menu_subscription = None LayerWatch().stop_all() @staticmethod def start_editing(objects): """Start watching for the layer and run the editor""" item = objects["item"] identifier = item().identifier usda_filename = LayerWatch().start_watch(identifier) editor.run_editor(usda_filename) @staticmethod def stop_editing(objects): """Stop watching for the layer and remove the temporary files""" item = objects["item"] identifier = item().identifier LayerWatch().stop_watch(identifier) @staticmethod def is_editing(objects): """Returns true if the layer is already watched""" item = objects["item"] identifier = item().identifier return LayerWatch().has_watch(identifier) @staticmethod def is_not_editing(objects): """Returns true if the layer is not watched""" return not LayersMenu.is_editing(objects)
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/usda_edit_utils.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.app def is_extension_loaded(extansion_name: str) -> bool: """ Returns True if the extension with the given name is loaded. """ def is_ext(id: str, extension_name: str) -> bool: id_name = id.split("-")[0] return id_name == extension_name app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() extensions = ext_manager.get_extensions() loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None) return not not loaded
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/editor.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Optional import carb.settings import os import shutil import subprocess def _is_exe(path): """Return true if the path is executable""" return os.path.isfile(path) and os.access(path, os.X_OK) def run_editor(usda_filename: str): """Open text editor with usda_filename in it""" settings = carb.settings.get_settings() # Find out which editor it's necessary to use # Check the settings editor: Optional[str] = settings.get("/app/editor") if not editor: # If settings doesn't have it, check the environment variable EDITOR. # It's the standard way to set the editor in Linux. editor = os.environ.get("EDITOR", None) if not editor: # VSCode is the default editor editor = "code" # Remove quotes because it's a common way for windows to specify paths if editor[0] == '"' and editor[-1] == '"': editor = editor[1:-1] if not _is_exe(editor): try: # Check if we can run the editor editor = shutil.which(editor) except shutil.Error: editor = None if not editor: if os.name == "nt": # All Windows have notepad editor = "notepad" else: # Most Linux systems have gedit editor = "gedit" if os.name == "nt": # Using cmd on the case the editor is bat or cmd file call_command = ["cmd", "/c"] else: call_command = [] call_command.append(editor) call_command.append(usda_filename) # Non blocking call subprocess.Popen(call_command)
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/content_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from . import editor from .layer_watch import LayerWatch from .usda_edit_utils import is_extension_loaded from omni.kit.ui import get_custom_glyph_code from pathlib import Path class ContentMenu: """ When this object is alive, Content Browser has the additional context menu with the items that allow to edit the USD files in the external editor. """ def __init__(self): import omni.kit.content as content self._content_window = content.get_content_window() edit_menu_name = f'{get_custom_glyph_code("${glyphs}/menu_rename.svg")} Edit...' self.__edit_menu_subscription = self._content_window.add_icon_menu( edit_menu_name, self._on_start_editing, self._is_edit_visible ) stop_menu_name = f'{get_custom_glyph_code("${glyphs}/menu_delete.svg")} Finish editing' self.__stop_menu_subscription = self._content_window.add_icon_menu( stop_menu_name, self._on_stop_editing, self._is_stop_visible ) def _is_edit_visible(self, content_url): '''True if we can show the menu item "Edit"''' for ext in ["usd", "usda", "usdc"]: if content_url.endswith(f".{ext}"): return not LayerWatch().has_watch(content_url) def _on_start_editing(self, menu, value): """Start watching for the layer and run the editor""" file_path = self._content_window.get_selected_icon_path() usda_filename = LayerWatch().start_watch(file_path) editor.run_editor(usda_filename) def _is_stop_visible(self, content_url): """Returns true if the layer is already watched""" return LayerWatch().has_watch(content_url) def _on_stop_editing(self, menu, value): """Stop watching for the layer and remove the temporary files""" file_path = self._content_window.get_selected_icon_path() LayerWatch().stop_watch(file_path) def destroy(self): """Stop all watchers and remove the menu from the content browser""" del self.__edit_menu_subscription self.__edit_menu_subscription = None del self.__stop_menu_subscription self.__stop_menu_subscription = None self._content_window = None LayerWatch().stop_all()
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/tests/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .usda_test import TestUsdaEdit
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/tests/usda_test.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from ..layer_watch import LayerWatch from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from pxr import Usd from pxr import UsdGeom import omni.client import omni.kit import omni.usd import os import time import unittest OMNI_SERVER = "omniverse://kit.nucleus.ov-ci.nvidia.com" OMNI_USER = "omniverse" OMNI_PASS = "omniverse" class TestUsdaEdit(OmniUiTest): def __set_omni_credentials(self): # Save the environment to be able to restore it self.__OMNI_USER = os.environ.get("OMNI_USER", None) self.__OMNI_PASS = os.environ.get("OMNI_PASS", None) # Set the credentials os.environ["OMNI_USER"] = OMNI_USER os.environ["OMNI_PASS"] = OMNI_PASS def __restore_omni_credentials(self): if self.__OMNI_USER is not None: os.environ["OMNI_USER"] = self.__OMNI_USER else: os.environ.pop("OMNI_USER") if self.__OMNI_PASS is not None: os.environ["OMNI_PASS"] = self.__OMNI_PASS else: os.environ.pop("OMNI_PASS") async def test_open_file(self): # New stage with a sphere await omni.usd.get_context().new_stage_async() omni.kit.commands.execute("CreatePrim", prim_path="/Sphere", prim_type="Sphere", select_new_prim=False) stage = omni.usd.get_context().get_stage() # Create USDA usda_filename = LayerWatch().start_watch(stage.GetRootLayer().identifier) # Check it's a valid stage duplicate = Usd.Stage.Open(usda_filename) self.assertTrue(duplicate) # Check it has the sphere sphere = duplicate.GetPrimAtPath("/Sphere") self.assertTrue(sphere) UsdGeom.Cylinder.Define(duplicate, '/Cylinder') duplicate.Save() await omni.kit.app.get_app().next_update_async() # Check cylinder is created cylinder = duplicate.GetPrimAtPath("/Cylinder") self.assertTrue(cylinder) # Remove USDA LayerWatch().stop_watch(stage.GetRootLayer().identifier) # Check the file is removed self.assertFalse(Path(usda_filename).exists()) await omni.kit.app.get_app().next_update_async() @unittest.skip("Works locally, but fails on TC for server connection in linux -> flaky") async def test_edit_file_on_nucleus(self): self.__set_omni_credentials() # Create a new stage on server temp_usd_folder = f"{OMNI_SERVER}/Users/test_usda_edit_{str(time.time())}" temp_usd_file_path = f"{temp_usd_folder}/test_edit_file_on_nucleus.usd" # cleanup first await omni.client.delete_async(temp_usd_folder) # create the folder result = await omni.client.create_folder_async(temp_usd_folder) self.assertEqual(result, omni.client.Result.OK) stage = Usd.Stage.CreateNew(temp_usd_file_path) await omni.kit.app.get_app().next_update_async() UsdGeom.Xform.Define(stage, '/xform') UsdGeom.Sphere.Define(stage, '/xform/sphere') await omni.kit.app.get_app().next_update_async() stage.Save() # Start watching and edit the temp stage usda_filename = LayerWatch().start_watch(stage.GetRootLayer().identifier) temp_stage = Usd.Stage.Open(usda_filename) # Create another sphere UsdGeom.Sphere.Define(temp_stage, '/xform/sphere1') # Save the stage temp_stage.Save() # UsdStage saves the temorary file and renames it to usda, so we need # to touch it to let LayerWatch know it's changed. Path(usda_filename).touch() # Small delay because watchdog in LayerWatch doesn't call the callback # right away. So we need to give it some time. await LayerWatch().wait_import_async(stage.GetRootLayer().identifier) # Remove USDA LayerWatch().stop_watch(stage.GetRootLayer().identifier) stage.Reload() # Check the second sphere is there sphere = stage.GetPrimAtPath("/xform/sphere1") self.assertTrue(sphere) # Remove the temp folder result = await omni.client.delete_async(temp_usd_folder) self.assertEqual(result, omni.client.Result.OK) self.__restore_omni_credentials()
omniverse-code/kit/exts/omni.kit.usda_edit/docs/CHANGELOG.md
# Changelog This document records all notable changes to ``omni.kit.usda_edit`` extension. ## [1.1.10] - 2022-02-02 ### Changed - Removed explicit pip dependency requirement on `watchdog`. It's now pre-bundled with Kit SDK. ## [1.1.9] - 2021-12-22 ### Fixed - content_browser context menu is now destroyed when content_browser unloaded first during kit exit ## [1.1.8] - 2021-02-23 ### Changed - The test waits for import instead of 15 frames ## [1.1.7] - 2021-02-17 ### Added - Support for the file format `usd_omni_wrapper` which is from Nucleus ### Changed - The call of the editor is not blocking ### Fixed - The path to editor can contain quotation marks ## [1.1.6] - 2020-12-08 ### Added - Preview image and description ## [1.1.5] - 2020-12-03 ### Added - Dependency on watchdog ## [1.1.4] - 2020-11-12 ### Changed - Fixed exception in Create ## [1.1.3] - 2020-11-11 ### Changed - Fixed the bug when the USD file destroyed when it's on the server and has the asset metadata ### Added - Menu to `omni.kit.window.content_browser` ## [1.1.2] - 2020-07-09 ### Changed - Join the observer before destroy it. It should fix the exception when exiting Kit. ## [1.1.1] - 2020-07-08 ### Added - Added dependency to `omni.kit.pipapi` ## [1.1.0] - 2020-07-06 ### Added - The editor executable is set using settings `/app/editor` or `EDITOR` environment variable. ## [1.0.0] - 2020-07-06 ### Added - CHANGELOG.rst - Added the context menu to Content Browser window to edit USDA files ## [0.1.0] - 2020-06-29 ### Added - Ability to edit USD layers as USDA files - Added the context menu to Layers window to edit USDA files
omniverse-code/kit/exts/omni.kit.usda_edit/docs/README.md
# USDA Editor [omni.kit.usda_edit] The tool to view end edit USD layers in a text editor. Convert a USD file to the USD ASCII format in a temporary location and run an editor on it. After saving the editor, the edited file will be converted back to the original format and reload the corresponding layer in Kit, invoking the stage's update. The context menu to edit layer appears in Layers and Content windows. The editor can be configured with a setting `/app/editor` or environment variable `EDITOR`. By default, the editor is either `code` or `notepad`/`gedit`, depending on the availability.
omniverse-code/kit/exts/omni.usd.config/omni/usd_config/extension.py
import os from glob import glob from pathlib import Path import carb import carb.dictionary import carb.settings import omni.ext import omni.kit.app from omni.mtlx import get_mtlx_stdlib_search_path ENABLE_NESTED_GPRIMS_SETTINGS_PATH = "/usd/enableNestedGprims" DISABLE_CAMERA_ADAPTER_SETTINGS_PATH = "/usd/disableCameraAdapter" MDL_SEARCH_PATHS_REQUIRED = "/renderer/mdl/searchPaths/required" MDL_SEARCH_PATHS_TEMPLATES = "/renderer/mdl/searchPaths/templates" class Extension(omni.ext.IExt): def __init__(self): super().__init__() pass def on_startup(self): self._app = omni.kit.app.get_app() self._settings = carb.settings.acquire_settings_interface() self._settings.set_default_bool(ENABLE_NESTED_GPRIMS_SETTINGS_PATH, True) self._usd_enable_nested_gprims = self._settings.get(ENABLE_NESTED_GPRIMS_SETTINGS_PATH) self._settings.set_default_bool(DISABLE_CAMERA_ADAPTER_SETTINGS_PATH, False) self._usd_disable_camera_adapter = self._settings.get(DISABLE_CAMERA_ADAPTER_SETTINGS_PATH) self._setup_usd_env_settings() self._setup_usd_material_env_settings() def on_shutdown(self): self._settings = None self._app = None # This must be invoked before USD's TfRegistry for env settings gets initialized. # See https://gitlab-master.nvidia.com/carbon/Graphene/merge_requests/3115#note_5019170 def _setup_usd_env_settings(self): is_release_build = not self._app.is_debug_build() if is_release_build: # Disable TfEnvSetting banners (alerting users to local environment overriding Usd defaults) in release builds. os.environ["TF_ENV_SETTING_ALERTS_ENABLED"] = "0" # Preferring translucent over additive shaders for opacity mapped preview shaders in HdStorm. os.environ["HDST_USE_TRANSLUCENT_MATERIAL_TAG"] = "1" if self._usd_disable_camera_adapter: # Disable UsdImaging camera support. os.environ["USDIMAGING_DISABLE_CAMERA_ADAPTER"] = "1" # Experiment with sparse light updates. # https://github.com/PixarAnimationStudios/USD/commit/1a82d34b1144caa85909b417d18148197fba551c # Remove this when nv-usd 20.11+ is enabled in the build. os.environ["USDIMAGING_ENABLE_SPARSE_LIGHT_UPDATES"] = "1" if self._usd_enable_nested_gprims: # Enable imaging refresh for nested gprims (needed for light gizmos). # https://nvidia-omniverse.atlassian.net/browse/OM-9446 os.environ["USDIMAGING_ENABLE_NESTED_GPRIMS"] = "1" # Enable support for querying doubles in XformCommonAPI::GetXformVectors os.environ["USDGEOM_XFORMCOMMONAPI_ALLOW_DOUBLES"] = "1" # Allow material networks to be defined under IDs which are not known to SdrRegistry until we have a registration # mechnism for mdl. os.environ["USDIMAGING_ALLOW_UNREGISTERED_SHADER_IDS"] = "1" # Continue supporting old mdl schema in UsdShade for now. os.environ["USDSHADE_OLD_MDL_SCHEMA_SUPPORT"] = "1" # Disable primvar invalidation in UsdImagingGprimAdapter so that Kit's scene delegate can perform its own primvar # analysis. os.environ["USDIMAGING_GPRIMADAPTER_PRIMVAR_INVALIDATION"] = "0" # OM-18759 # Disable auto-scaling of time samples from layers whose timeCodesPerSecond do not match that of # the stage's root layer. # Eventually Pixar will retire this runtime switch; we'll need tooling to find and fix all # non-compliant assets to maintain their original animated intent. # OM-28725 # Enable auto-scaling because more and more animation content, e.g. Machinima contents, need # this feature. Kit now has property window to adjust timeCodePerSecond for each layer so it won't # be a big issue if animator brings in two layers with different timeCodePerSecond. Need a validator # to notify the authors such info though. os.environ["PCP_DISABLE_TIME_SCALING_BY_LAYER_TCPS"] = "0" # OM-18814 # Temporarily disable notification when setting interpolation mode. # This needs to be investigated further after Ampere demos are delivered. os.environ["USDSTAGE_DISABLE_INTERP_NOTICE"] = "1" # Properties which are unknown to UsdImagingGprimAdapter do not invalidate the rprim (disabled for now- # see OM-9049. Use whitelist, blacklist, and carb logging in # omni::usd::hydra::SceneDelegate::ProcessNonAdapterBasedPropertyChange to help contribute to re-enabling it). # os.environ["USDIMAGING_UNKNOWN_PROPERTIES_ARE_CLEAN] = "1" # OM-38943 # Enable parallel sync for non-material sprims (i.e., lights). os.environ["HD_ENABLE_MULTITHREADED_NON_MATERIAL_SPRIM_SYNC"] = "1" # OM-39636 # Disable scene index emulation until we have integated it with our HdMaterialNode changes for MDL support. os.environ["HD_ENABLE_SCENE_INDEX_EMULATION"] = "0" # OM-47199 # Disable the MDL Builtin Bypass for omni_usd_resolver os.environ["OMNI_USD_RESOLVER_MDL_BUILTIN_BYPASS"] = "1" # OM-62080 # Use NV-specific maps for optimized Hydra change tracking os.environ["HD_CHANGETRACKER_USE_CONTIGUOUS_VALUES_MAP"] = "1" # OM-93197 # Suppress warning spew about material bindings until assets are addressed os.environ["USD_SHADE_MATERIAL_BINDING_API_CHECK"] = "allowMissingAPI" def _setup_usd_material_env_settings(self): def gather_mdl_modules(path, prefix=""): try: if not path.exists(): return except: return for child in path.iterdir(): if child.is_file() and (child.suffix == ".mdl"): mdl_modules.add(prefix + child.name) elif child.is_dir(): gather_mdl_modules(child, prefix + child.stem + "/") def process_mdl_search_path(settings_path): paths = self._settings.get(settings_path) if not paths: carb.log_warn(f"Unable to query '{settings_path}' from carb.settings.") return paths = [Path(p.strip()) for p in paths.split(";") if p.strip()] for p in paths: gather_mdl_modules(p) # use a set to avoid dupliate module names # if Neuray finds multiple modules with the same name only the first is loaded into the database mdl_modules = set() process_mdl_search_path(MDL_SEARCH_PATHS_REQUIRED) process_mdl_search_path(MDL_SEARCH_PATHS_TEMPLATES) os.environ["OMNI_USD_RESOLVER_MDL_BUILTIN_PATHS"] = ",".join(mdl_modules) # OM-19420, OM-88291 # Set the MaterialX library path in order to add mtlx nodes to the NDR mtlx_library_path = get_mtlx_stdlib_search_path() if "PXR_MTLX_STDLIB_SEARCH_PATHS" in os.environ: os.environ["PXR_MTLX_STDLIB_SEARCH_PATHS"] += os.pathsep + mtlx_library_path else: os.environ["PXR_MTLX_STDLIB_SEARCH_PATHS"] = mtlx_library_path
omniverse-code/kit/exts/omni.usd.config/omni/usd_config/__init__.py
from .extension import *
omniverse-code/kit/exts/omni.mdl.usd_converter/PACKAGE-LICENSES/omni.mdl.usd_converter-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.mdl.usd_converter/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "MDL to USD converter" description="MDL to USD converter extension." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Services" # Keywords for the extension keywords = ["kit", "mdl", "Python bindings"] # Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content # of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. # preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. # icon = "data/icon.png" # Dependencies for this extension: [dependencies] "omni.usd" = {} "omni.mdl.neuraylib" = {} "omni.mdl" = {} # Main python module this extension provides, it will be publicly available as "import omni.mdl.usd_converter". [[python.module]] name = "omni.mdl.usd_converter" # Extension test settings [[test]] args = [] dependencies = [] stdoutFailPatterns.include = [] stdoutFailPatterns.exclude = []
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/__init__.py
from .usd_converter import *
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/usd_converter.py
# ***************************************************************************** # Copyright 2021 NVIDIA Corporation. All rights reserved. # ***************************************************************************** import omni.ext import carb import os import shutil import tempfile import carb.settings from omni.mdl import pymdlsdk from omni.mdl import pymdl import omni.mdl.neuraylib from . import mdl_usd import asyncio from pxr import Usd from pxr import UsdShade MDL_AUTOGEN_PATH = "${data}/shadergraphs/mdl_usd" class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def add_search_path_to_system_path(searchPath: str): if not searchPath == None and not searchPath == "": MDL_SYSTEM_PATH = "/app/mdl/additionalSystemPaths" settings = carb.settings.get_settings() mdl_custom_paths: List[str] = settings.get(MDL_SYSTEM_PATH) or [] mdl_custom_paths.append(searchPath) mdl_custom_paths = list(set(mdl_custom_paths)) settings.set_string_array(MDL_SYSTEM_PATH, mdl_custom_paths) # Functions and vars are available to other extension as usual in python: `omni.mdl.usd_converter.mdl_to_usd(x)` # # mdl_to_usd(moduleName, targetFolder, targetFilename) # moduleName: module to convert (example: "nvidia/core_definitions.mdl") # searchPath: MDL search path to be able to load MDL modules referenced by moduleName # targetFolder: Destination folder for USD stage (default = "${data}/shadergraphs/mdl_usd") # targetFilename: Destination stage filename (default is module name, example: "core_definitions.usda") # output: What to output: # a shader: omni.mdl.usd_converter.mdl_usd.OutputType.SHADER # a material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL # geometry and material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY # nestedShaders: Do we want nested shaders or flat (default = False) # def mdl_to_usd( moduleName: str, searchPath: str = None, targetFolder: str = MDL_AUTOGEN_PATH, targetFilename: str = None, output: mdl_usd.OutputType = mdl_usd.OutputType.SHADER, nestedShaders: bool = False): print(f"[omni.mdl.usd_converter] mdl_to_usd was called with {moduleName}") # acquire neuray instance from OV ovNeurayLib = omni.mdl.neuraylib.get_neuraylib() ovNeurayLibHandle = ovNeurayLib.getNeurayAPI() # feed the neuray instance into the python binding neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle) neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status() print(f"Neuray Status: {neurayStatus}") # Set carb.settings with new MDL search path add_search_path_to_system_path(searchPath) # Select a view on the database used for the rtx renderer for. # It should be fine to use this one always. Hydra will deal with applying the changes to the # other renderer. It would be possible to use an own space entirely but this would double module loading. # In the long, we want to load modules only into one scope. dbScopeName = "rtx_scope" # we need to load modules to OV using the omni.mdl.neuraylib # on the c++ side this is async, here it is blocking! print(f"createMdlModule called with: {moduleName}") ovModule = ovNeurayLib.createMdlModule(moduleName) print(f"CoreDefinitions: {ovModule.valid()}") if ovModule.valid(): print(f" dbScopeName: {ovModule.dbScopeName}") print(f" dbName: {ovModule.dbName}") print(f" qualifiedName: {ovModule.qualifiedName}") else: print(f" createMdlModule failed : {moduleName}") # after the module is loaded we create a new transaction that can see the loaded module ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName) trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle) print(f"Transaction Open: {trans.is_open()}") # try out the high level binding module = pymdl.Module._fetchFromDb(trans, ovModule.dbName) if module: print(f"MDL Qualified Name: {module.mdlName}") print(f"MDL Simple Name: {module.mdlSimpleName}") print(f"MDL DB Name: {module.dbName}") print(f"MDL Module filename: {module.filename}") else: print("MDL Module: None") print(f"Failed to convert: {moduleName}") return False try: stage = mdl_usd.Usd.Stage.CreateInMemory() except: trans.abort() trans = None return False stage.SetMetadata('comment', 'MDL to USD conversion') # create context for the conversion of the scene context = mdl_usd.ConverterContext() context.set_neuray(neuray) context.set_transaction(trans) context.set_stage(stage) context.mdl_to_usd_output = output context.mdl_to_usd_output_material_nested_shaders = nestedShaders context.ov_neuray = ovNeurayLib mdl_usd.module_to_stage(context, module) # Workaround the issue creating stage under "${data}/shadergraphs/mdl_usd" # by creating the stage in a temp folder and copying it to dest folder with TemporaryDirectory() as temp_dir: unmangle_helper = mdl_usd.Unmangle(context) # Demangle instance name (unmangled_flag, simple_name) = unmangle_helper.unmangle_mdl_identifier(module.dbName) simple_name = simple_name.replace("::", "_") filename = os.path.join(temp_dir, simple_name + ".usda") if targetFilename is not None: if targetFilename[-4:] == ".usd" or targetFilename[-5:] == ".usda": filename = os.path.join(temp_dir, targetFilename) else: filename = os.path.join(temp_dir, targetFilename + ".usda") stage.GetRootLayer().Export(filename) # Copy file to destination folder path = targetFolder token = carb.tokens.get_tokens_interface() mdlUSDPath = token.resolve(path) dest = os.path.abspath(mdlUSDPath) # Create folder if it does not exist if not os.path.exists(dest): os.makedirs(dest) try: shutil.copy2(filename, dest) print(f"Stage saved as: {os.path.join(dest, os.path.basename(filename))}") except: print(f"Failed to save stage as: {os.path.join(dest, os.path.basename(filename))}") pass try: omni.kit.window.material_graph.GraphExtension.refresh_compounds() except: pass ovNeurayLib.destroyMdlModule(ovModule) # since we have been reading only, abort trans.abort() trans = None return True def test_mdl_prim_to_usd(primPath: str): stage = omni.usd.get_context().get_stage() if stage: prim = stage.GetPrimAtPath(primPath) if prim: mdl_prim_to_usd(stage, prim) def mdl_prim_to_usd(stage: Usd.Stage, prim: Usd.Prim): # Only handle material for the time beeing if not UsdShade.Material(prim): return # acquire neuray instance from OV ovNeurayLib = omni.mdl.neuraylib.get_neuraylib() ovNeurayLibHandle = ovNeurayLib.getNeurayAPI() # feed the neuray instance into the python binding neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle) neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status() print(f"Neuray Status: {neurayStatus}") # after the module is loaded we create a new transaction that can see the loaded module dbScopeName = "rtx_scope" ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName) trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle) print(f"Transaction Open: {trans.is_open()}") # create context for the conversion of the scene context = mdl_usd.ConverterContext() context.set_neuray(neuray) context.set_transaction(trans) context.set_stage(stage) context.mdl_to_usd_output = mdl_usd.OutputType = mdl_usd.OutputType.MATERIAL context.mdl_to_usd_output_material_nested_shaders = False context.ov_neuray = ovNeurayLib mdl_usd.mdl_prim_to_usd(context, stage, prim) # since we have been reading only, abort trans.abort() trans = None return True # usd_prim_to_mdl(usdStage, usdPrim, searchPath) # usdStage: Input stage containing the Prim to convert # usdPrim: Prim to convert (default = not set, use stage default Prim) # searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set) # forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False) # async def usd_prim_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None, forceNotOV: bool = False): print(f"[omni.mdl.usd_converter] usd_prim_to_mdl was called with {usdStage} / {usdPrim} / {searchPath} / {forceNotOV}") rtncode = True # acquire neuray instance from OV ovNeurayLib = omni.mdl.neuraylib.get_neuraylib() ovNeurayLibHandle = ovNeurayLib.getNeurayAPI() # feed the neuray instance into the python binding neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle) neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status() print(f"Neuray Status: {neurayStatus}") # Set carb.settings with new MDL search path add_search_path_to_system_path(searchPath) # Select a view on the database used for the rtx renderer for. # It should be fine to use this one always. Hydra will deal with applying the changes to the # other renderer. It would be possible to use an own space entirely but this would double module loading. # In the long, we want to load modules only into one scope. dbScopeName = "rtx_scope" # create a new transaction ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName) trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle) print(f"Transaction Open: {trans.is_open()}") try: stage = mdl_usd.Usd.Stage.Open(usdStage) except: rtncode = False if rtncode: if usdPrim == None: try: # Determine default Prim usdPrim = stage.GetDefaultPrim().GetPath() except: pass if usdPrim == None: print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage") rtncode = False if rtncode: # create context for the conversion of the scene context = mdl_usd.ConverterContext() context.set_neuray(neuray) context.set_transaction(trans) context.set_stage(stage) if not forceNotOV: context.ov_neuray = ovNeurayLib inst_name = await mdl_usd.convert_usd_to_mdl(context, usdPrim, None) rtncode = (inst_name is not None) # transaction might have changed internally trans = context.transaction if not rtncode: print(f"[omni.mdl.usd_converter] error: Conversion failure") trans.abort() trans = None return rtncode # test_export_to_mdl(usdStage, usdPrim, searchPath) # usdStage: Input stage containing the Prim to convert # usdPrim: Prim to convert (default = not set, use stage default Prim) # searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set) # async def test_export_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None): # pragma: no cover # Set carb.settings with new MDL search path add_search_path_to_system_path(searchPath) stage = None try: stage = mdl_usd.Usd.Stage.Open(usdStage) except: return False if usdPrim == None: try: # Determine default Prim usdPrim = stage.GetDefaultPrim().GetPath() except: pass if usdPrim == None: print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage") return False prim = stage.GetPrimAtPath(usdPrim) path = "c:/temp/new_module.mdl" return asyncio.ensure_future(export_to_mdl(path, prim)) # export_to_mdl(path, prim) # path: Output file name # prim: Prim to convert # # Note: The MDL modules referenced by the prim must be in the MDL searchPath # async def export_to_mdl(path: str, prim: mdl_usd.Usd.Prim, forceNotOV: bool = False): if prim == None: print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage") return False # acquire neuray instance from OV ovNeurayLib = omni.mdl.neuraylib.get_neuraylib() ovNeurayLibHandle = ovNeurayLib.getNeurayAPI() # feed the neuray instance into the python binding neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle) neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status() print(f"Neuray Status: {neurayStatus}") # Select a view on the database used for the rtx renderer for. # It should be fine to use this one always. Hydra will deal with applying the changes to the # other renderer. It would be possible to use an own space entirely but this would double module loading. # In the long, we want to load modules only into one scope. dbScopeName = "rtx_scope" # create a new transaction ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName) trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle) print(f"Transaction Open: {trans.is_open()}") stage = prim.GetStage() # create context for the conversion of the scene context = mdl_usd.ConverterContext() context.set_neuray(neuray) context.set_transaction(trans) context.set_stage(stage) if not forceNotOV: context.ov_neuray = ovNeurayLib usd_prim = prim.GetPath() inst_name = await mdl_usd.convert_usd_to_mdl(context, usd_prim, path) rtncode = (inst_name is not None) if rtncode: print(f"[omni.mdl.usd_converter] Export to MDL success") else: print(f"[omni.mdl.usd_converter] Error: Export to MDL failure") context.transaction.abort() context.set_transaction(None) return rtncode def find_tokens(lines, filter_import_lines = False): return mdl_usd.find_tokens(lines, filter_import_lines) # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class DiscoveryExtension(omni.ext.IExt): # pragma: no cover # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.mdl.usd_converter] MDL to USD converter startup") def on_shutdown(self): print("[omni.mdl.usd_converter] MDL to USD converter shutdown")
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/mdl_usd.py
#***************************************************************************** # Copyright 2022 NVIDIA Corporation. All rights reserved. #***************************************************************************** import sys import os import gc import platform import traceback from enum import Enum from pxr import Usd from pxr import Plug from pxr import Sdr from pxr import Sdf from pxr import Tf from pxr import UsdShade from pxr import Gf from pxr import UsdGeom from pxr import Kind from pxr import UsdUI import numpy # used to represent Vectors, Matrices, and Colors import re # For command line args from copy import deepcopy # Dictionary merging import tempfile # load the binding module print("MDL python binding about to load ...") #################### # Omniverse code from omni.mdl import pymdlsdk from omni.mdl import pymdl import omni.client async def copy_async(texture_path, dst_path): result = await omni.client.copy_async(texture_path, dst_path) return (result == omni.client.Result.OK) # Omniverse code #################### # TODO: loading fails for debug builds of the pymdlsdk.pyd (or pymdlsdk.so on unix) module print("MDL python binding loaded") def str2bool(v): return str(v).lower() in ("true", "1") def str2MDL_TO_USD_OUTPUT(v): if v == '1': return OutputType.SHADER if v == '2': return OutputType.MATERIAL if v == '3': return OutputType.MATERIAL_AND_GEOMETRY #-------------------------------------------------------------------------------------------------- # Command line arguments #-------------------------------------------------------------------------------------------------- class Args: # pragma: no cover display_usage = False options = dict() def __init__(self): self.options["SEARCH_PATH"] = get_examples_search_path() self.options["MODULE"] = "::nvidia::sdk_examples::tutorials" self.options["PRIM"] = "/example_material" # Used for USD to MDL conversion self.options["STAGE"] = "tutorials.usda" self.options["OUT"] = "tutorials.usda" # Set FOR_OV to False if a Material/Shader hierarchy is required in the output USD stage # SHADER = 1 # MATERIAL = 2 # MATERIAL_AND_GEOMETRY = 3 self.options["MDL_TO_USD_OUTPUT"] = 1 self.options["NESTED_SHADERS"] = False # See mdl_to_usd_output_material_nested_shaders self.options["MDL_TO_USD"] = True for a in sys.argv: if a == "-help" or a == "-h" or a == "-?": self.display_usage = True break match = re.search("(.+)=(.+)", a) if match: self.options[match.group(1)] = match.group(2) # Convert paths self.options["SEARCH_PATH"] = os.path.abspath(self.options["SEARCH_PATH"]) self.options["OUT"] = os.path.abspath(self.options["OUT"]) # Convert string args to bool self.options["MDL_TO_USD"] = str2bool(self.options["MDL_TO_USD"]) self.options["NESTED_SHADERS"] = str2bool(self.options["NESTED_SHADERS"]) # Convert string args to int self.options["MDL_TO_USD_OUTPUT"] = str2MDL_TO_USD_OUTPUT(self.options["MDL_TO_USD_OUTPUT"]) def usage(self): print("usage: " + os.path.basename(sys.argv[0]) + " [-help|-h|-?] [SEARCH_PATH=<path>] [MODULE=<string>] [PRIM=<string>] [STAGE=<string>] [OUT=<string>] [MDL_TO_USD_OUTPUT=<int>] [NESTED_SHADERS=<bool>] [MDL_TO_USD=<bool>]") print("\n") print(" -help|-h|-?:\t Display usage") print(" SEARCH_PATH:\t Use this as MDL search path (default: {})".format(self.options["SEARCH_PATH"])) print(" MODULE:\t Module to load (default: {})".format(self.options["MODULE"])) print(" PRIM:\t\t USD prim to convert to MDL (default: {})".format(self.options["PRIM"])) print(" STAGE:\t USD stage to load and convert (default: {})".format(self.options["STAGE"])) print(" OUT:\t\t Output file (default: {})".format(self.options["OUT"])) print(" MDL_TO_USD_OUTPUT:\t Output either a shader (1) or material (2) or material and geometry (3) (default: {})".format(self.options["MDL_TO_USD_OUTPUT"])) print(" NESTED_SHADERS:\t Output nested shader tree, vs. flat shader tree (default: {})".format(self.options["NESTED_SHADERS"])) print(" MDL_TO_USD:\t MDL to USD conversion ortherwise USD to MDL (default: {})".format(self.options["MDL_TO_USD"])) #-------------------------------------------------------------------------------------------------- # USD and misc utilities #-------------------------------------------------------------------------------------------------- MdlIValueKindToUSD = { pymdlsdk.IValue.Kind.VK_BOOL: Sdf.ValueTypeNames.Bool, pymdlsdk.IValue.Kind.VK_INT : Sdf.ValueTypeNames.Int, pymdlsdk.IValue.Kind.VK_ENUM : Sdf.ValueTypeNames.Int, pymdlsdk.IValue.Kind.VK_FLOAT : Sdf.ValueTypeNames.Float, pymdlsdk.IValue.Kind.VK_DOUBLE : Sdf.ValueTypeNames.Double, pymdlsdk.IValue.Kind.VK_STRING : Sdf.ValueTypeNames.String, pymdlsdk.IValue.Kind.VK_COLOR : Sdf.ValueTypeNames.Color3f, pymdlsdk.IValue.Kind.VK_STRUCT : Sdf.ValueTypeNames.Token, pymdlsdk.IValue.Kind.VK_TEXTURE : Sdf.ValueTypeNames.Asset, pymdlsdk.IValue.Kind.VK_LIGHT_PROFILE : Sdf.ValueTypeNames.Asset, pymdlsdk.IValue.Kind.VK_BSDF_MEASUREMENT : Sdf.ValueTypeNames.Asset } MdlITypeKindToUSD = { pymdlsdk.IType.Kind.TK_BOOL: Sdf.ValueTypeNames.Bool, pymdlsdk.IType.Kind.TK_INT : Sdf.ValueTypeNames.Int, pymdlsdk.IType.Kind.TK_ENUM : Sdf.ValueTypeNames.Int, pymdlsdk.IType.Kind.TK_FLOAT : Sdf.ValueTypeNames.Float, pymdlsdk.IType.Kind.TK_DOUBLE : Sdf.ValueTypeNames.Double, pymdlsdk.IType.Kind.TK_STRING : Sdf.ValueTypeNames.String, pymdlsdk.IType.Kind.TK_COLOR : Sdf.ValueTypeNames.Color3f, pymdlsdk.IType.Kind.TK_STRUCT : Sdf.ValueTypeNames.Token, pymdlsdk.IType.Kind.TK_TEXTURE : Sdf.ValueTypeNames.Asset, pymdlsdk.IType.Kind.TK_LIGHT_PROFILE : Sdf.ValueTypeNames.Asset, pymdlsdk.IType.Kind.TK_BSDF_MEASUREMENT : Sdf.ValueTypeNames.Asset } # TODO: # mi::neuraylib::IType::TK_BSDF # mi::neuraylib::IType::TK_EDF # mi::neuraylib::IType::TK_VDF def python_vector_to_usd_type(dtype, size): if dtype == numpy.int32 or dtype == bool: if size == 2: return Sdf.ValueTypeNames.Int2 elif size == 3: return Sdf.ValueTypeNames.Int3 elif size == 4: return Sdf.ValueTypeNames.Int4 elif dtype == numpy.float32: if size == 2: return Sdf.ValueTypeNames.Float2 elif size == 3: return Sdf.ValueTypeNames.Float3 elif size == 4: return Sdf.ValueTypeNames.Float4 elif dtype == numpy.float64: if size == 2: return Sdf.ValueTypeNames.Double2 elif size == 3: return Sdf.ValueTypeNames.Double3 elif size == 4: return Sdf.ValueTypeNames.Double4 return None def python_vector_to_usd_value(value): dtype = value.dtype size = value.size out = None if dtype == numpy.int32 or dtype == bool: if size == 2: out = Gf.Vec2i(0) elif size == 3: out = Gf.Vec3i(0) elif size == 4: out = Gf.Vec4i(0) if out != None: for i in range(size): out[i] = int(value[i][0]) elif dtype == numpy.float32: if size == 2: out = Gf.Vec2f(0) elif size == 3: out = Gf.Vec3f(0) elif size == 4: out = Gf.Vec4f(0) if out != None: for i in range(size): out[i] = float(value[i][0]) elif dtype == numpy.float64: if size == 2: out = Gf.Vec2d(0) elif size == 3: out = Gf.Vec3d(0) elif size == 4: out = Gf.Vec4d(0) if out != None: for i in range(size): out[i] = numpy.float64(value[i][0]) return out def custom_data_from_python_vector(value): dtype = value.dtype out = dict() if dtype == bool: size = value.size out = dict({"mdl":{"type" : "bool{}".format(size)}}) return out def python_matrix_to_usd_type(dtype, nrow, ncol): # numpyType Column Row OutType m = { 'float32' : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2d, 3 : Sdf.ValueTypeNames.Float3Array, 4 : Sdf.ValueTypeNames.Float4Array}, 3 : { 2 : Sdf.ValueTypeNames.Float2Array, 3 : Sdf.ValueTypeNames.Matrix3d, 4 : Sdf.ValueTypeNames.Float4Array}, 4 : { 2 : Sdf.ValueTypeNames.Float2Array, 3 : Sdf.ValueTypeNames.Float3Array, 4 : Sdf.ValueTypeNames.Matrix4d }}, 'float64' : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2d, 3 : Sdf.ValueTypeNames.Double3Array, 4 : Sdf.ValueTypeNames.Double4Array}, 3 : { 2 : Sdf.ValueTypeNames.Double2Array, 3 : Sdf.ValueTypeNames.Matrix3d, 4 : Sdf.ValueTypeNames.Double4Array}, 4 : { 2 : Sdf.ValueTypeNames.Double2Array, 3 : Sdf.ValueTypeNames.Double3Array, 4 : Sdf.ValueTypeNames.Matrix4d }}} return m[dtype.name][ncol][nrow] def python_matrix_to_usd_value(value): dtype = value.dtype nrow = value.shape[0] ncol = value.shape[1] out = None if dtype == numpy.float32: if ncol == 2: if nrow == 2: out = Gf.Matrix2d(0) out.SetColumn(0, Gf.Vec2d(float(value[0][0]), float(value[0][1]))) out.SetColumn(1, Gf.Vec2d(float(value[1][0]), float(value[1][1]))) elif nrow == 3: out = [Gf.Vec3f(float(value[0][0]), float(value[1][0]), float(value[2][0])), Gf.Vec3f(float(value[0][1]), float(value[1][1]), float(value[2][1]))] elif nrow == 4: out = [Gf.Vec4f(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])), Gf.Vec4f(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1]))] elif ncol == 3: if nrow == 2: out = [Gf.Vec2f(float(value[0][0]), float(value[1][0])), Gf.Vec2f(float(value[0][1]), float(value[1][1])), Gf.Vec2f(float(value[0][2]), float(value[1][2]))] elif nrow == 3: out = Gf.Matrix3d(0) out.SetColumn(0, Gf.Vec3d(float(value[0][0]), float(value[0][1]), float(value[0][2]))) out.SetColumn(1, Gf.Vec3d(float(value[1][0]), float(value[1][1]), float(value[1][2]))) out.SetColumn(2, Gf.Vec3d(float(value[2][0]), float(value[2][1]), float(value[2][2]))) elif nrow == 4: out = [Gf.Vec4f(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])), Gf.Vec4f(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1])), Gf.Vec4f(float(value[0][2]), float(value[1][2]), float(value[2][2]), float(value[3][2]))] elif ncol == 4: if nrow == 2: out = [Gf.Vec2f(float(value[0][0]), float(value[1][0])), Gf.Vec2f(float(value[0][1]), float(value[1][1])), Gf.Vec2f(float(value[0][2]), float(value[1][2])), Gf.Vec2f(float(value[0][3]), float(value[1][3]))] elif nrow == 3: out = [Gf.Vec3f(float(value[0][0]), float(value[1][0]), float(value[2][0])), Gf.Vec3f(float(value[0][1]), float(value[1][1]), float(value[2][1])), Gf.Vec3f(float(value[0][2]), float(value[1][2]), float(value[2][2])), Gf.Vec3f(float(value[0][3]), float(value[1][3]), float(value[2][3]))] elif nrow == 4: out = Gf.Matrix4d(0) out.SetColumn(0, Gf.Vec4d(float(value[0][0]), float(value[0][1]), float(value[0][2]), float(value[0][3]))) out.SetColumn(1, Gf.Vec4d(float(value[1][0]), float(value[1][1]), float(value[1][2]), float(value[1][3]))) out.SetColumn(2, Gf.Vec4d(float(value[2][0]), float(value[2][1]), float(value[2][2]), float(value[2][3]))) out.SetColumn(3, Gf.Vec4d(float(value[3][0]), float(value[3][1]), float(value[3][2]), float(value[3][3]))) elif dtype == numpy.float64: if ncol == 2: if nrow == 2: out = Gf.Matrix2d(0) out.SetColumn(0, Gf.Vec2d(float(value[0][0]), float(value[0][1]))) out.SetColumn(1, Gf.Vec2d(float(value[1][0]), float(value[1][1]))) elif nrow == 3: out = [Gf.Vec3d(float(value[0][0]), float(value[1][0]), float(value[2][0])), Gf.Vec3d(float(value[0][1]), float(value[1][1]), float(value[2][1]))] elif nrow == 4: out = [Gf.Vec4d(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])), Gf.Vec4d(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1]))] elif ncol == 3: if nrow == 2: out = [Gf.Vec2d(float(value[0][0]), float(value[1][0])), Gf.Vec2d(float(value[0][1]), float(value[1][1])), Gf.Vec2d(float(value[0][2]), float(value[1][2]))] elif nrow == 3: out = Gf.Matrix3d(0) out.SetColumn(0, Gf.Vec3d(float(value[0][0]), float(value[0][1]), float(value[0][2]))) out.SetColumn(1, Gf.Vec3d(float(value[1][0]), float(value[1][1]), float(value[1][2]))) out.SetColumn(2, Gf.Vec3d(float(value[2][0]), float(value[2][1]), float(value[2][2]))) elif nrow == 4: out = [Gf.Vec4d(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])), Gf.Vec4d(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1])), Gf.Vec4d(float(value[0][2]), float(value[1][2]), float(value[2][2]), float(value[3][2]))] elif ncol == 4: if nrow == 2: out = [Gf.Vec2d(float(value[0][0]), float(value[1][0])), Gf.Vec2d(float(value[0][1]), float(value[1][1])), Gf.Vec2d(float(value[0][2]), float(value[1][2])), Gf.Vec2d(float(value[0][3]), float(value[1][3]))] elif nrow == 3: out = [Gf.Vec3d(float(value[0][0]), float(value[1][0]), float(value[2][0])), Gf.Vec3d(float(value[0][1]), float(value[1][1]), float(value[2][1])), Gf.Vec3d(float(value[0][2]), float(value[1][2]), float(value[2][2])), Gf.Vec3d(float(value[0][3]), float(value[1][3]), float(value[2][3]))] elif nrow == 4: out = Gf.Matrix4d(0) out.SetColumn(0, Gf.Vec4d(float(value[0][0]), float(value[0][1]), float(value[0][2]), float(value[0][3]))) out.SetColumn(1, Gf.Vec4d(float(value[1][0]), float(value[1][1]), float(value[1][2]), float(value[1][3]))) out.SetColumn(2, Gf.Vec4d(float(value[2][0]), float(value[2][1]), float(value[2][2]), float(value[2][3]))) out.SetColumn(3, Gf.Vec4d(float(value[3][0]), float(value[3][1]), float(value[3][2]), float(value[3][3]))) return out def python_array_to_usd_type(value): array_simple_conversion = { bool : Sdf.ValueTypeNames.BoolArray, int : Sdf.ValueTypeNames.IntArray, # TODO: enum? # AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_ENUM, SdfValueTypeNames->IntArray); float : Sdf.ValueTypeNames.FloatArray, # TODO: double ? # AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_DOUBLE, SdfValueTypeNames->DoubleArray); str : Sdf.ValueTypeNames.StringArray, pymdlsdk.IType.Kind.TK_COLOR : Sdf.ValueTypeNames.Color3fArray # TODO: AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_STRUCT, SdfValueTypeNames->TokenArray); # TODO: AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_TEXTURE, SdfValueTypeNames->AssetArray); } array_of_vector_conversion = { numpy.bool_ : { 2 : Sdf.ValueTypeNames.Int2Array, 3 : Sdf.ValueTypeNames.Int3Array, 4 : Sdf.ValueTypeNames.Int4Array }, numpy.int32 : { 2 : Sdf.ValueTypeNames.Int2Array, 3 : Sdf.ValueTypeNames.Int3Array, 4 : Sdf.ValueTypeNames.Int4Array }, numpy.float32 : { 2 : Sdf.ValueTypeNames.Float2Array, 3 : Sdf.ValueTypeNames.Float3Array, 4 : Sdf.ValueTypeNames.Float4Array }, numpy.float64 : { 2 : Sdf.ValueTypeNames.Double2Array, 3 : Sdf.ValueTypeNames.Double3Array, 4 : Sdf.ValueTypeNames.Double4Array } } # // Array of matrix # numpyType Column Row OutType array_of_matrix = \ { numpy.float32 : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2dArray, 3 : Sdf.ValueTypeNames.FloatArray, 4 : Sdf.ValueTypeNames.FloatArray}, 3 : { 2 : Sdf.ValueTypeNames.FloatArray, 3 : Sdf.ValueTypeNames.Matrix3dArray, 4 : Sdf.ValueTypeNames.FloatArray}, 4 : { 2 : Sdf.ValueTypeNames.FloatArray, 3 : Sdf.ValueTypeNames.FloatArray, 4 : Sdf.ValueTypeNames.Matrix4dArray }}, numpy.float64 : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2dArray, 3 : Sdf.ValueTypeNames.DoubleArray, 4 : Sdf.ValueTypeNames.DoubleArray}, 3 : { 2 : Sdf.ValueTypeNames.DoubleArray, 3 : Sdf.ValueTypeNames.Matrix3dArray, 4 : Sdf.ValueTypeNames.DoubleArray}, 4 : { 2 : Sdf.ValueTypeNames.DoubleArray, 3 : Sdf.ValueTypeNames.DoubleArray, 4 : Sdf.ValueTypeNames.Matrix4dArray }}} dtype = type(value[0]) if dtype in array_simple_conversion: return array_simple_conversion[dtype] elif dtype == numpy.ndarray: shape = value[0].shape # Array if len(shape) > 1 and shape[1] > 1: # Array of matrices elemtype = type(value[0][0][0]) if elemtype in array_of_matrix: if shape[1] in array_of_matrix[elemtype]: if shape[0] in array_of_matrix[elemtype][shape[1]]: return array_of_matrix[elemtype][shape[1]][shape[0]] elif type(value[0][0]) == numpy.ndarray: # Array of vectors etype = type(value[0][0][0]) size = len(value[0]) if etype in array_of_vector_conversion: if size in array_of_vector_conversion[etype]: return array_of_vector_conversion[etype][size] else: print("Array of vector type not supported for type/size: {}/{}".format(etype, size)) elif len(value[0]) == 3: # Assume this is a color return array_simple_conversion[pymdlsdk.IType.Kind.TK_COLOR] else: print("Array type not supported for type/shape: {}/{}".format(dtype, shape)) else: print("Type not supported for type: {}".format(dtype)) def python_array_to_usd_value(value): dtype = type(value[0]) out = None if dtype == bool or \ dtype == int or \ dtype == float or \ dtype == str: return value elif dtype == numpy.ndarray: # Array shape = value[0].shape if len(shape) > 1 and shape[1] > 1: # Array of matrices elemtype = type(value[0][0][0]) nrow = shape[0] ncol = shape[1] out = None arraysize = len(value) if ncol == nrow: if ncol == 2: mattype = Gf.Matrix2d if ncol == 3: mattype = Gf.Matrix3d if ncol == 4: mattype = Gf.Matrix4d out = [] for i in range(arraysize): mat = mattype(0) for c in range(ncol): row = [] for r in range(nrow): row.append(float(value[i][c][r])) mat.SetColumn(c, row) out.append(mat) else: if elemtype == numpy.float32: otype = float elif elemtype == numpy.float64: otype = numpy.float64 out = [] for i in range(arraysize): for c in range(ncol): for r in range(nrow): out.append(otype(value[i][r][c])) elif type(value[0][0]) == numpy.ndarray: # Array of vectors etype = type(value[0][0][0]) size = len(value) out = [] if etype == numpy.bool_ or \ etype == numpy.int32: otype = int elif etype == numpy.float32: otype = float elif etype == numpy.float64: otype = numpy.float64 itemsize = len(value[0]) for i in range(size): ll = [] for j in range(itemsize): ll.append(otype(value[i][j])) out.append(ll) elif len(value[0]) == 3: # Assume this is a color size = len(value) out = [] for i in range(size): out.append([value[0][0], value[0][1], value[0][2]]) return out def custom_data_from_python_array(value): # type = dict({"mdl":{"type" : "array of matrix"}}) out = dict() dtype = type(value[0]) arraysize = len(value) if dtype == numpy.ndarray: # Array shape = value[0].shape if len(shape) > 1 and shape[1] > 1: # Array of matrices elemtype = type(value[0][0][0]) nrow = shape[0] ncol = shape[1] elemtype = type(value[0][0][0]) if ncol != nrow or elemtype == numpy.float32: # Non square matrices typename = "" if elemtype == numpy.float32: typename = "float" elif elemtype == numpy.float64: typename = "double" out = dict({"mdl":{"type" : "{}{}x{}[{}]".format(typename, ncol, nrow, arraysize)}}) elif type(value[0][0]) == numpy.ndarray: # Array of vectors etype = type(value[0][0][0]) if etype == numpy.bool_: itemsize = len(value[0]) out = dict({"mdl":{"type" : "bool{}[{}]".format(itemsize, arraysize)}}) return out def mdl_type_to_usd_type(val : pymdl.ArgumentConstant): if not val: return None kind = val.type.kind if kind in MdlITypeKindToUSD: return MdlITypeKindToUSD[kind] else: # A bit more work is required to derive the type if kind == pymdlsdk.IType.Kind.TK_VECTOR: return python_vector_to_usd_type(val.value.dtype, val.value.size) elif kind == pymdlsdk.IType.Kind.TK_MATRIX: return python_matrix_to_usd_type(val.value.dtype, val.value.shape[0], val.value.shape[1]) elif kind == pymdlsdk.IType.Kind.TK_ARRAY: return python_array_to_usd_type(val.value) return None class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def top(self): return self.items[len(self.items)-1] def size(self): return len(self.items) # When converting from MDL to USD user can choose the USD output format # SHADER: A single shader is output at the root of the USD Stage # MATERIAL: A single material is output at the root of the USD Stage # MATERIAL_AND_GEOMETRY: Geometry and Material (bound to the geometry) are output in the USD Stage class OutputType(Enum): SHADER = 1 MATERIAL = 2 MATERIAL_AND_GEOMETRY = 3 class ConverterContext(): def __init__(self): self.neuray = None self.transaction = None self.stage = None self.modules = Stack() self.usd_materials = Stack() self.parameter_names = Stack() self.usd_shaders = Stack() self.custom_data = Stack() self.type_annotation = True self.mdl_to_usd_output = OutputType.SHADER self.mdl_to_usd_output_material_nested_shaders = False # Nested/deep or flat shader tree self.ov_neuray = None GetUniqueNameInStage.s_uniqueID = 0 # Reset the unique name counter to get same output between 2 runs def enable_type_annotation(self): self.type_annotation = True def disable_type_annotation(self): self.type_annotation = False def is_type_annotation_enabled(self): return self.type_annotation == True def set_neuray(self, neuray): self.neuray = neuray def set_transaction(self, transaction): self.transaction = transaction def set_stage(self, stage): self.stage = stage def push_module(self, module): self.modules.push(module) def pop_module(self): return self.modules.pop() def current_module(self): return self.modules.top() def push_usd_material(self, material): self.usd_materials.push(material) def pop_usd_material(self): return self.usd_materials.pop() def current_usd_material(self): return self.usd_materials.top() def push_parameter_name(self, parm): self.parameter_names.push(parm) def pop_parameter_name(self): return self.parameter_names.pop() def current_parameter_name(self): return self.parameter_names.top() def push_usd_shader(self, shader): self.usd_shaders.push(shader) def pop_usd_shader(self): return self.usd_shaders.pop() def current_usd_shader(self): return self.usd_shaders.top() def push_custom_data(self, custom_data): self.custom_data.push(custom_data) def pop_custom_data(self): return self.custom_data.pop() def current_custom_data(self): return self.custom_data.top() # Example: 'mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase' # Return: 'OmniSurface/OmniSurfaceBase.mdl' def prototype_to_source_asset(prototype): source_asset = prototype if source_asset[:5] == "mdl::": source_asset = source_asset[3:] # Remove leading "mdl" if source_asset[:2] == "::": source_asset = source_asset[2:] # Remove leading "::" ll = source_asset.split("::") source_asset = '/'.join(ll[0:-1]) # Drop last part which is material name source_asset = source_asset + ".mdl" # Append ".mdl" extension return source_asset def module_mdl_name_to_source_asset(context, module_mdl_name): # Hack to convert builtin module functions if module_mdl_name == '::scene' or module_mdl_name == '::state': return 'nvidia/support_definitions.mdl' unmangle_helper = UnmangleAndFixMDLSearchPath(context) (isMangled, wasSuccess, newmodule_mdl_name) = unmangle_helper.unmangle_mdl_module(module_mdl_name) if wasSuccess and newmodule_mdl_name != module_mdl_name: return newmodule_mdl_name + '.mdl' if isMangled and not wasSuccess: # Better return empty asset than garbage asset return '' source_asset = module_mdl_name if source_asset[:5] == "mdl::": source_asset = source_asset[3:] # Remove leading "mdl" if source_asset[:2] == "::": source_asset = source_asset[2:] # Remove leading "::" source_asset = source_asset.replace("::", "/") # Replace "::" with "/" source_asset = source_asset + ".mdl" # Append ".mdl" extension return source_asset def source_asset_to_module_name(source_asset, context): module_name = source_asset module_name = os.path.normpath(module_name) if os.path.isabs(module_name): # Absolute path, try to find a mathing search path and remove it with context.neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg: if cfg.is_valid_interface(): for i in range(cfg.get_mdl_paths_length()): sp = cfg.get_mdl_path(i) sp = os.path.normpath(sp.get_c_str()) if module_name.find(sp) == 0: module_name = module_name[len(sp):] break # Split path ll = module_name.split(os.sep) # Concat path using '::' separator module_name = "::".join(ll) if not module_name[0:2] == "::": # Prepend '::' module_name = "::" + module_name if module_name[-4:] == ".mdl": # Remove '.mdl' extension module_name = module_name[0:-4] return module_name def db_name_to_prim_name(dbname): name = dbname name = name.split("(")[0] # Remove arguments name = name.split("::")[-1] # Remove package, module name = name.replace(".", "_") # Replace '.' return name def mdl_name_to_sub_identifier(mdl_name, fct_call=False): sub_id = mdl_name if sub_id[:5] == "mdl::": sub_id = sub_id[3:] # Remove leading "mdl" # split the identifier from the arguments names = sub_id.split("(") # keep only the last name from the identifier sub_id = names[0].split("::")[-1] if fct_call: # concat with args if len(names) > 1: sub_id = sub_id + "(" + names[1] return sub_id # Return a unique SdfPath for the current stage class GetUniqueNameInStage: s_uniqueID = 0 @staticmethod def get(stage, path): unique_path = path while stage.GetPrimAtPath(unique_path).IsValid(): unique_path = Sdf.Path(str(path) + str(GetUniqueNameInStage.s_uniqueID)) GetUniqueNameInStage.s_uniqueID += 1 return unique_path class GetUniqueName: s_uniqueID = 0 @staticmethod def get(transaction, prefix_in): prefix = prefix_in if len(prefix)==0: prefix = "elt" if not transaction.access_as(pymdlsdk.IInterface, prefix).is_valid_interface(): return prefix while True: prefix = prefix_in + "_" + str(GetUniqueName.s_uniqueID) GetUniqueName.s_uniqueID += 1 if not transaction.access_as(pymdlsdk.IInterface, prefix).is_valid_interface(): return prefix def create_stage(args): stageName = args.options["OUT"] stage = Usd.Stage.CreateNew(stageName) stage.SetMetadata('comment', 'MDL to USD conversion') return stage def load_stage(stageName): stage = None try: stage = Usd.Stage.Open(stageName) except: print("Error:\tFailed to load stage: {}".format(stageName)) return stage def save_stage(stage): stage.GetRootLayer().Save() def export_stage(stage, filename): stage.GetRootLayer().Export(filename) def material_to_stage_output_material(context, function: pymdl.FunctionDefinition): return material_to_stage_output_material_and_geo(context, function, want_geometry = False) def material_to_stage_output_material_and_geo(context, function: pymdl.FunctionDefinition, want_geometry = True): neuray = context.neuray transaction = context.transaction stage = context.stage db_name = function.dbName materialName = db_name_to_prim_name(db_name) # Start at root rootPath = Sdf.Path('/') spherePrim = None if want_geometry: xform = UsdGeom.Xform.Define(stage,"/World") # Add geometry spherePrim = UsdGeom.Sphere.Define(stage, xform.GetPath().AppendChild('Geom')) model = Usd.ModelAPI(xform) model.SetKind(Kind.Tokens.component) # Create Looks scope # Scope is the simplest grouping primitive... scope = UsdGeom.Scope.Define(stage, xform.GetPath().AppendChild('Looks')) rootPath = scope.GetPath() model = Usd.ModelAPI(scope) model.SetKind(Kind.Tokens.model) material = None # Create material material = UsdShade.Material.Define(stage, rootPath.AppendChild(materialName)) if spherePrim != None: # Bind material to geometry UsdShade.MaterialBindingAPI(spherePrim).Bind(material) # Create surface shader surfaceShader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("Shader")) # Create surface shader output port outPort = surfaceShader.CreateOutput('out', Sdf.ValueTypeNames.Token) # Create material output port terminal = material.CreateOutput('mdl:surface', Sdf.ValueTypeNames.Token) # Connect material output to shader output terminal.ConnectToSource(outPort) terminal = material.CreateOutput('mdl:volume', Sdf.ValueTypeNames.Token) terminal.ConnectToSource(outPort) terminal = material.CreateOutput('mdl:displacement', Sdf.ValueTypeNames.Token) terminal.ConnectToSource(outPort) # Determine module asset module_interface : pymdl.Module module_interface = context.current_module() module = module_interface.mdlName source_asset = module_mdl_name_to_source_asset(context, module) # Example: # uniform token info:implementationSource = "sourceAsset" # uniform asset info:mdl:sourceAsset = @nvidia/core_definitions.mdl@ # uniform token info:mdl:sourceAsset:subIdentifier = "::nvidia::core_definitions::flex_material" surfaceShader.GetImplementationSourceAttr().Set("sourceAsset") surfaceShader.SetSourceAsset(Sdf.AssetPath(source_asset), "mdl") node_identifier = mdl_name_to_sub_identifier(db_name) surfaceShader.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier) context.stage.SetDefaultPrim(material.GetPrim()) context.push_usd_material(material) context.push_usd_shader(surfaceShader) context.push_custom_data(dict()) definition_to_stage(context, function) # Annotations anno_dict = get_annotations_dict(context, function) add_annotations_to_prim(surfaceShader.GetPrim(), anno_dict) add_annotations_to_node(surfaceShader, anno_dict) context.pop_custom_data() context.pop_usd_shader() context.pop_usd_material() def material_to_stage_output_shader(context, function: pymdl.FunctionDefinition): neuray = context.neuray transaction = context.transaction stage = context.stage db_name = function.dbName materialName = db_name_to_prim_name(db_name) # Start at root rootPath = Sdf.Path('/') material = UsdShade.Shader.Define(stage, rootPath.AppendChild(materialName)) # Create output port outPort = material.CreateOutput('out', Sdf.ValueTypeNames.Token).SetRenderType("material") # Determine module asset module_interface : pymdl.Module module_interface = context.current_module() module = module_interface.mdlName source_asset = module_mdl_name_to_source_asset(context, module) # Example: # uniform token info:implementationSource = "sourceAsset" # uniform asset info:mdl:sourceAsset = @nvidia/core_definitions.mdl@ # uniform token info:mdl:sourceAsset:subIdentifier = "::nvidia::core_definitions::flex_material" material.GetImplementationSourceAttr().Set("sourceAsset") material.SetSourceAsset(Sdf.AssetPath(source_asset), "mdl") node_identifier = mdl_name_to_sub_identifier(db_name) material.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier) context.stage.SetDefaultPrim(material.GetPrim()) context.push_usd_material(material) context.push_usd_shader(material) context.push_custom_data(dict()) definition_to_stage(context, function) # Annotations anno_dict = get_annotations_dict(context, function) add_annotations_to_prim(material.GetPrim(), anno_dict) add_annotations_to_node(material, anno_dict) context.pop_custom_data() context.pop_usd_shader() context.pop_usd_material() def material_to_stage(context, function: pymdl.FunctionDefinition): if context.mdl_to_usd_output == OutputType.SHADER: return material_to_stage_output_shader(context, function) elif context.mdl_to_usd_output == OutputType.MATERIAL: return material_to_stage_output_material(context, function) elif context.mdl_to_usd_output == OutputType.MATERIAL_AND_GEOMETRY: return material_to_stage_output_material_and_geo(context, function) def module_to_stage(context, module: pymdl.Module): context.push_module(module) for simple_name, overloads in module.functions.items(): f: pymdl.FunctionDefinition for f in overloads: material_to_stage(context, f) anno_dict = get_annotations_dict(context, module) add_annotations_to_stage(context, context.stage, anno_dict) context.pop_module() def mdl_prim_to_usd(context : ConverterContext, stage: Usd.Stage, prim: Usd.Prim, createNewMaterial: bool = False): inst_name = None mdl_entity = None mdl_entity_snapshot = None if context.ov_neuray == None: return # Get the shader prim from Material shader_prim = get_shader_prim(context.stage, prim.GetPath()) mdl_entity = context.ov_neuray.createMdlEntity(shader_prim.GetPath().pathString) mdl_entity_snapshot = None if not mdl_entity.getMdlModule() == None: mdl_entity_snapshot = context.ov_neuray.createMdlEntitySnapshot(mdl_entity) inst_name = mdl_entity_snapshot.dbName source_asset = Sdf.AssetPath("") shader = UsdShade.Shader(shader_prim) if shader: imp_source = shader.GetImplementationSourceAttr().Get() if imp_source == "sourceAsset": # Retrieve module name source_asset = shader.GetSourceAsset("mdl") material = UsdShade.Material(prim) if createNewMaterial: rootPath = Sdf.Path(prim.GetPath().GetParentPath()) # Create material materialName = prim.GetName() + "_converted" # Find unique name materialName = GetUniqueNameInStage.get(stage, rootPath.AppendChild(materialName)) material = UsdShade.Material.Define(stage, materialName) # Create surface shader surfaceShader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild(shader_prim.GetName())) # Create output port outPort = surfaceShader.CreateOutput('out', Sdf.ValueTypeNames.Token) # Create material output port terminal = material.CreateOutput('mdl:surface', Sdf.ValueTypeNames.Token) # Connect material output to shader output terminal.ConnectToSource(outPort) terminal = material.CreateOutput('mdl:volume', Sdf.ValueTypeNames.Token) terminal.ConnectToSource(outPort) terminal = material.CreateOutput('mdl:displacement', Sdf.ValueTypeNames.Token) terminal.ConnectToSource(outPort) context.push_usd_material(material) context.push_usd_shader(surfaceShader) context.push_custom_data(dict()) fctCall = pymdl.FunctionCall._fetchFromDb(context.transaction, inst_name) handle_function_call(context, fctCall) context.pop_usd_material() context.pop_usd_shader() context.pop_custom_data() if not mdl_entity_snapshot == None: context.ov_neuray.destroyMdlEntitySnapshot(mdl_entity_snapshot) if not mdl_entity == None: context.ov_neuray.destroyMdlEntity(mdl_entity) #-------------------------------------------------------------------------------------------------- # Utilities #-------------------------------------------------------------------------------------------------- def get_examples_search_path(): """Try to get the example search path or returns 'mdl' sub folder of the current directory if it failed.""" # get the environment variable that is used in all MDL SDK examples example_sp = os.getenv('MDL_SAMPLES_ROOT') # fall back to a path relative to this script file if example_sp == None or not os.path.exists(example_sp): example_sp = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..') # go down into the mdl folder example_sp = os.path.join(example_sp, 'mdl') # fall back to the current folder if not os.path.exists(example_sp): example_sp = './mdl' return os.path.abspath(example_sp) #-------------------------------------------------------------------------------------------------- # MDL Python Example #-------------------------------------------------------------------------------------------------- # return usd_value, connection, usd_type def get_usd_value_and_type(context, val : pymdl.ArgumentConstant): if not val: return (None, None, None) kind = val.type.kind usd_type = mdl_type_to_usd_type(val) if usd_type == None: return (None, None, None) usd_val = None connection = None # -------------------------------- Atomic --------------------------------- if kind == pymdlsdk.IType.Kind.TK_BOOL or \ kind == pymdlsdk.IType.Kind.TK_INT or \ kind == pymdlsdk.IType.Kind.TK_FLOAT or \ kind == pymdlsdk.IType.Kind.TK_DOUBLE or \ kind == pymdlsdk.IType.Kind.TK_STRING: usd_val = val.value elif kind == pymdlsdk.IType.Kind.TK_ENUM: usd_val = val.value[1] # -------------------------------- Compound --------------------------------- elif kind == pymdlsdk.IType.Kind.TK_VECTOR: usd_val = python_vector_to_usd_value(val.value) if context.is_type_annotation_enabled(): custom_data = custom_data_from_python_vector(val.value) context.current_custom_data().update(custom_data) elif kind == pymdlsdk.IType.Kind.TK_MATRIX: usd_val = python_matrix_to_usd_value(val.value) elif kind == pymdlsdk.IType.Kind.TK_COLOR: usd_val = Gf.Vec3f(val.value[0], val.value[1], val.value[2]) elif kind == pymdlsdk.IType.Kind.TK_ARRAY: usd_val = python_array_to_usd_value(val.value) if context.is_type_annotation_enabled(): custom_data = custom_data_from_python_array(val.value) context.current_custom_data().update(custom_data) elif kind == pymdlsdk.IType.Kind.TK_STRUCT: parm_name = context.current_parameter_name() shader = context.current_usd_shader() usd_mat = context.current_usd_shader() new_shader = UsdShade.Shader.Define(context.stage, GetUniqueNameInStage.get(context.stage, usd_mat.GetPath().AppendChild("ShaderAttachement_" + parm_name))) connection = new_shader.CreateOutput('out', Sdf.ValueTypeNames.Token) context.push_usd_shader(new_shader) for item in val.value: field_name = item context.push_parameter_name(field_name) context.push_custom_data(dict()) v = val.value[item] handle_value(context, v) context.pop_custom_data() context.pop_parameter_name() context.pop_usd_shader() # -------------------------------- Resource --------------------------------- elif kind == pymdlsdk.IType.Kind.TK_TEXTURE: ftex = val.value[0] gamma = val.value[1] with context.transaction.access_as(pymdlsdk.ITexture, ftex) as text: if text.is_valid_interface(): with context.transaction.access_as(pymdlsdk.IImage, text.get_image()) as image: if image.is_valid_interface(): usd_val = image.get_filename(0,0) elif kind == pymdlsdk.IType.Kind.TK_LIGHT_PROFILE: v = val.value with context.transaction.access_as(pymdlsdk.ILightprofile, v) as obj: if obj.is_valid_interface(): usd_val = obj.get_filename() elif kind == pymdlsdk.IType.Kind.TK_BSDF_MEASUREMENT: v = val.value with context.transaction.access_as(pymdlsdk.IBsdf_measurement, v) as obj: if obj.is_valid_interface(): usd_val = obj.get_filename() else: print("Error: Unknown IValue Kind for parm/kind: {}/{}".format(context.current_parameter_name(), kind)) return (usd_val, connection, usd_type) def dict_of_dicts_merge(x, y): z = {} overlapping_keys = x.keys() & y.keys() for key in overlapping_keys: z[key] = dict_of_dicts_merge(x[key], y[key]) for key in x.keys() - overlapping_keys: z[key] = deepcopy(x[key]) for key in y.keys() - overlapping_keys: z[key] = deepcopy(y[key]) return z # Return a dictionary of pair [string, value] # def get_annotations_dict(context, val): main_dict = dict() # We do not want to collect type annotations during conversion of annotation expressions # Otherwise the type for the annotations is mized with the parameter annotations context.disable_type_annotation() try: # Handle annotations if val.annotations: anno_dict = dict() # print(f" Annotations:") anno: pymdl.Annotation for anno in val.annotations: # print(f" - Simple Name: {anno.simpleName}") # print(f" Qualified Name: {anno.name}") # // Special case of annotations without expressions, e.g. ::anno::hidden() # // We create a boolean VtValue and set it to true # // Annotation: # // ::anno::hidden() # // becomes: # // bool "::anno::hidden()" = 1 if len(anno.arguments.items()) == 0: usd_value = True usd_type = bool anno_dict[anno.name] = usd_value arg: pymdl.val for arg_name, arg in anno.arguments.items(): # print(f" ({arg.type.kind}) {arg_name}: {arg.value}") (usd_value, connection, usd_type) = get_usd_value_and_type(context, arg) # print(f" ({usd_value}) {connection}: {usd_type}") if usd_value != None and usd_type != None: anno_dict[anno.name+"::"+arg_name] = usd_value if len(anno_dict) > 0: main_dict.update(dict({"mdl" : {"annotations": anno_dict}})) # Handle special values, concat (possibly empty) context dictionary main_dict = dict_of_dicts_merge(main_dict, context.current_custom_data()) except Exception as e: print("Error while retrieving annotations") finally: context.enable_type_annotation() return main_dict def add_annotations_to_stage(context, stage, anno_dict): try: if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]: stage.SetMetadata('comment', 'Conversion from MDL module: ' + anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"]) else: if context.current_module() != None: stage.SetMetadata('comment', 'Conversion from MDL module: ' + context.current_module().mdlName) # TODO: Add more annotations to Stage as Metadata: version, ... except: pass def add_annotations_to_node(node, anno_dict): # display name, group and description # # sdrMetadata = { # dictionary ui = { # string displayGroup = "float2_parm group" # } # } # if "mdl" in anno_dict and "annotations" in anno_dict["mdl"]: for anno, key in ( \ ("::anno::display_name(string)::name", "ui:displayName"), \ ("::anno::in_group(string)::group", "ui:displayGroup"), \ ("::anno::in_group(string,string)::group", "ui:displayGroup"), \ ("::anno::in_group(string,string,string)::group", "ui:displayGroup"), \ ("::anno::description(string)::description", "ui:description")): if anno in anno_dict["mdl"]["annotations"]: node.SetSdrMetadataByKey( key, anno_dict["mdl"]["annotations"][anno]) # # See Also: # # ui = Usd.SceneGraphPrimAPI(minput.GetAttr()) # a = ui.CreateDisplayNameAttr() # # TODO: Could also use? # # minput.GetAttr().SetDisplayName("FOOBAR") # minput.GetAttr().SetDisplayGroup("GROUP") try: if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]: node.GetAttr().SetDisplayName(anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"]) for anno in ( \ "::anno::in_group(string)::group", \ "::anno::in_group(string,string)::group", \ "::anno::in_group(string,string,string)::group" \ ): if anno in anno_dict["mdl"]["annotations"]: node.GetAttr().SetDisplayGroup(anno_dict["mdl"]["annotations"][anno]) except: pass def add_annotations_to_prim(usd_prim, anno_dict): if len(anno_dict) > 0: cd = usd_prim.GetCustomData() cd.update(anno_dict) usd_prim.SetCustomData(cd) try: ui = UsdUI.UsdUIBackdrop(usd_prim) if "::anno::description(string)::description" in anno_dict["mdl"]["annotations"]: ui.CreateDescriptionAttr(anno_dict["mdl"]["annotations"]["::anno::description(string)::description"]) except: pass try: ui = UsdUI.SceneGraphPrimAPI(usd_prim) if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]: ui.CreateDisplayNameAttr(anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"]) for anno in ( \ "::anno::in_group(string)::group", \ "::anno::in_group(string,string)::group", \ "::anno::in_group(string,string,string)::group" \ ): if anno in anno_dict["mdl"]["annotations"]: ui.CreateDisplayGroupAttr(anno_dict["mdl"]["annotations"][anno]) except: pass # Hidden if "mdl" in anno_dict and "annotations" in anno_dict["mdl"]: if "::anno::hidden()" in anno_dict["mdl"]["annotations"]: if anno_dict["mdl"]["annotations"]["::anno::hidden()"]: usd_prim.SetHidden(True) def handle_value(context, val : pymdl.ArgumentConstant): if not val: return (usd_value, connection, usd_type) = get_usd_value_and_type(context, val) if (usd_value == None and connection == None) or usd_type == None: return parm_name = context.current_parameter_name() shader = context.current_usd_shader() minput = shader.CreateInput(parm_name, usd_type) if usd_value != None: minput.Set(usd_value) else: minput.ConnectToSource(connection) anno_dict = get_annotations_dict(context, val) add_annotations_to_prim(minput.GetAttr(), anno_dict) add_annotations_to_node(minput, anno_dict) if val.type.kind == pymdlsdk.IType.Kind.TK_ENUM: minput.SetRenderType(val.type.symbol) def handle_expression_constant(context, expression_constant : pymdl.ArgumentConstant): if not expression_constant: return handle_value(context, expression_constant) def handle_function_call(context, function_call : pymdl.FunctionCall): if not function_call: return # print("* Function definition: {}".format(function_call.functionDefinition)) # print("* MDL function definition: {}".format(function_call.mdlFunctionDefinition)) # print("* Parameter count: {}".format(len(function_call.parameters))) fdef_db_name = function_call.functionDefinition function_def = pymdl.FunctionDefinition._fetchFromDb(context.transaction, fdef_db_name) if not function_def: return sourceAsset = module_mdl_name_to_source_asset(context, function_def.mdlModuleName) node_identifier = mdl_name_to_sub_identifier( function_def.mdlName, True ) # Determine if function definition is variant fctdef = context.transaction.access_as(pymdlsdk.IFunction_definition, function_def.dbName) prototype = fctdef.get_prototype() if prototype: node_identifier = mdl_name_to_sub_identifier(prototype) sourceAsset = prototype_to_source_asset(prototype) shader = context.current_usd_shader() shader.GetImplementationSourceAttr().Set("sourceAsset") shader.SetSourceAsset(Sdf.AssetPath(sourceAsset), "mdl") shader.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier) for name, argument in function_call.parameters.items(): # print(f"* Name: {name}") # print(f" Type: {argument.type.kind}") # if argument.type.symbol: # print(f" Type Symbol: {argument.type.symbol}") # print(f" Value: {argument.value}") # print(f" Value is Constant: {isinstance(argument, pymdl.ArgumentConstant)}") # print(f" Value is Attachment: {isinstance(argument, pymdl.ArgumentCall)}") context.push_parameter_name(name) context.push_custom_data(dict()) handle_expression(context, argument) context.pop_custom_data() context.pop_parameter_name() def handle_material_instance(context, minst): if not minst.is_valid_interface(): return pass def handle_expression_call(context, expression_call : pymdl.ArgumentCall): if not expression_call: return neuray = context.neuray transaction = context.transaction # NEW fcall : pymdl.FunctionCall fcall = pymdl.FunctionCall._fetchFromDb(transaction, expression_call.value) if fcall: handle_function_call(context, fcall) return # TODO? # minst = transaction.access_as(pymdlsdk.IFunction_call, expression_call.get_call()) # if minst.is_valid_interface(): # handle_material_instance(context, minst) def handle_expression_parameter(context, expression_parameter): if not expression_parameter.is_valid_interface(): return pass def handle_expression_direct_call(context, expression_direct_call): if not expression_direct_call.is_valid_interface(): return pass def handle_expression_temporary(context, expression_temporary): if not expression_temporary.is_valid_interface(): return pass def handle_expression(context, argument : pymdl.Argument): if not argument: return if isinstance(argument, pymdl.ArgumentConstant): # A constant expression. See #mi::neuraylib::IExpression_constant. # argument_cst = pymdl.ArgumentConstant(argument) # FAILS argument_cst : pymdl.ArgumentConstant argument_cst = argument handle_expression_constant(context, argument_cst) elif isinstance(argument, pymdl.ArgumentCall): # Need to: # - create a parameter of the given type # - create a new shader in the current material # - Connect the parameter to the new shader # - Evaluate the expression expression_kind = argument.type.kind # If the exact return type can not be determined (e.g. vectors, where to get the size?) set the parm type to Token by default parm_type = Sdf.ValueTypeNames.Token parm_name = context.current_parameter_name() if expression_kind in MdlITypeKindToUSD: parm_type = MdlITypeKindToUSD[expression_kind] else: print("Warning: Indirect call expression parm/kind : {}/{}".format(parm_name,argument.type.kind)) # - create a parameter of the given type usd_shader = context.current_usd_shader() minput = usd_shader.CreateInput(parm_name, parm_type) # By default shaders are not nested, they are created immediately under the material usd_mat = context.current_usd_material() if context.mdl_to_usd_output_material_nested_shaders == True: # Nested shaders case, create under current shader usd_mat = context.current_usd_shader() # - create a new shader in thecurrent material (or current shader in the nested case) shName = GetUniqueNameInStage.get(context.stage, usd_mat.GetPath().AppendChild(parm_name)) shader = UsdShade.Shader.Define(context.stage, shName) outPort = shader.CreateOutput('out', Sdf.ValueTypeNames.Token) # - Connect the parameter to the new shader minput.ConnectToSource(outPort) context.push_usd_shader(shader) # - Evaluate the expression argument_call : pymdl.ArgumentCall argument_call = argument handle_expression_call(context, argument_call) # Annotations anno_dict = get_annotations_dict(context, argument_call) add_annotations_to_prim(minput.GetAttr(), anno_dict) add_annotations_to_node(minput, anno_dict) context.pop_usd_shader() # TODO # elif kind == pymdlsdk.IExpression.Kind.EK_PARAMETER: # # A parameter reference expression. See #mi::neuraylib::IExpression_parameter. # # handle_expression_parameter(context, expression.get_interface(pymdlsdk.IExpression_parameter)) # pass # elif kind == pymdlsdk.IExpression.Kind.EK_DIRECT_CALL: # # A direct call expression. See #mi::neuraylib::IExpression_direct_call. # # handle_expression_direct_call(context, expression.get_interface(pymdlsdk.IExpression_direct_call)) # pass # elif kind == pymdlsdk.IExpression.Kind.EK_TEMPORARY: # # A temporary reference expression. See #mi::neuraylib::IExpression_temporary. # # handle_expression_temporary(context, expression.get_interface(pymdlsdk.IExpression_temporary)) # pass def definition_to_stage(context, function: pymdl.FunctionDefinition): neuray = context.neuray transaction = context.transaction argument: pymdl.Argument for name, argument in function.parameters.items(): # print(f"* Name: {name}") # print(f" Type: {argument.type.kind}") # if argument.type.symbol: # print(f" Type Symbol: {argument.type.symbol}") # print(f" Value: {argument.value}") # print(f" Value is Constant: {isinstance(argument, pymdl.ArgumentConstant)}") # print(f" Value is Attachment: {isinstance(argument, pymdl.ArgumentCall)}") context.push_parameter_name(name) context.push_custom_data(dict()) handle_expression(context, argument) context.pop_custom_data() context.pop_parameter_name() def get_db_module_name(neuray, module_mdl_name): """Return the db name of the given module.""" module_db_name = None # When the module is loaded we can access it and all its definitions by accessing the DB # for that we need to get a the database name of the module using the factory with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory: with factory.get_db_module_name(module_mdl_name) as istring: if istring.is_valid_interface(): module_db_name = istring.get_c_str() # note, even though this name simple and could # be constructed by string operations, use the # factory to be save in case of unicode encodings # and potential upcoming changes in the future # # shortcut for the function above # # this chaining is a bit special. In the C++ interface it's not possible without # # leaking memory. Here we create the smart pointer automatically. However, the IString # # which is created temporay here is released at the end the `load_module` function, right? # # This might be unexpected, especially when we rely on the RAII pattern and that # # objects are disposed at certain points in time (usually before committing a transaction) # module_db_name_2 = factory.get_db_module_name(module_mdl_name).get_c_str() # # note, we plan to map compatible types to python. E.g. the IString class may disappear # return module_db_name_2 return module_db_name #-------------------------------------------------------------------------------------------------- def get_db_definition_name(neuray, function_mdl_name): """Return the db name of the given function definition.""" with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory: with factory.get_db_definition_name(function_mdl_name) as istring: if istring.is_valid_interface(): return istring.get_c_str() return None #-------------------------------------------------------------------------------------------------- def load_module(context, source_asset): success = False module_db_name = "" if not context.ov_neuray == None: # We are in OV if context.transaction: context.transaction.commit() context.transaction = None module_db_name = load_module_from_ov(context.ov_neuray, source_asset.path) dbScopeName = "rtx_scope" rtxTransactionReadHandle = context.ov_neuray.createReadingTransaction(dbScopeName) context.transaction: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(rtxTransactionReadHandle) module = pymdl.Module._fetchFromDb(context.transaction, module_db_name) success = (not module == None) else: module_mdl_name = source_asset_to_module_name(source_asset.path, context) success = load_module_from_neuray(context.neuray, context.transaction, module_mdl_name) if success: module_db_name = get_db_module_name(context.neuray, module_mdl_name) module = pymdl.Module._fetchFromDb(context.transaction, module_db_name) print(f'Loaded module (from omni.mdl.neuraylib={context.ov_neuray} / source asset={source_asset}): {module.filename}') return (success, module_db_name) #-------------------------------------------------------------------------------------------------- def load_module_from_neuray(neuray, transaction, module_mdl_name): """Load the module given its name. Returns true if the module is loaded to database""" with neuray.get_api_component(pymdlsdk.IMdl_impexp_api) as imp_exp: with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory: # for illustation, we don't use a `with` block for the `context`, instead we release manually context = factory.create_execution_context() res = imp_exp.load_module(transaction, module_mdl_name, context) context.release() return res >= 0 #-------------------------------------------------------------------------------------------------- def load_module_from_ov(rtxneuray, module_path): """Load the module given its name. Returns rtxModule.dbName if the module is loaded to database, otherwise return empty string """ rtxModule = None try: rtxModule = rtxneuray.createMdlModule(module_path) except: return "" return rtxModule.dbName #-------------------------------------------------------------------------------------------------- class ConvertVectorAndArray: def create_type_or_value(self, usd_type, factory): if usd_type in (\ Sdf.ValueTypeNames.Float2,\ Sdf.ValueTypeNames.Float2Array,\ Sdf.ValueTypeNames.Float3,\ Sdf.ValueTypeNames.Float3Array,\ Sdf.ValueTypeNames.Float4,\ Sdf.ValueTypeNames.Float4Array,\ Sdf.ValueTypeNames.FloatArray): return factory.create_float() elif usd_type in (\ Sdf.ValueTypeNames.Int2,\ Sdf.ValueTypeNames.Int2Array,\ Sdf.ValueTypeNames.Int3,\ Sdf.ValueTypeNames.Int3Array,\ Sdf.ValueTypeNames.Int4,\ Sdf.ValueTypeNames.Int4Array,\ Sdf.ValueTypeNames.IntArray): return factory.create_int() elif usd_type in (\ Sdf.ValueTypeNames.Double2,\ Sdf.ValueTypeNames.Double2Array,\ Sdf.ValueTypeNames.Double3,\ Sdf.ValueTypeNames.Double3Array,\ Sdf.ValueTypeNames.Double4,\ Sdf.ValueTypeNames.Double4Array,\ Sdf.ValueTypeNames.DoubleArray,\ Sdf.ValueTypeNames.Matrix2d,\ Sdf.ValueTypeNames.Matrix3d,\ Sdf.ValueTypeNames.Matrix4d): return factory.create_double() elif usd_type == Sdf.ValueTypeNames.BoolArray: return factory.create_bool() elif usd_type == Sdf.ValueTypeNames.StringArray: return factory.create_string() return None def convert(self, input, usd_type, type_factory, value_factory, expression_factory): value = input.Get() if value == None: return None if usd_type == Sdf.ValueTypeNames.Color3fArray: value = input.Get() array_size = len(value) vector_size = len(value[0]) assert(vector_size == 3) atomic_type = type_factory.create_color() if not atomic_type.is_valid_interface(): return None array_type = type_factory.create_immediate_sized_array(atomic_type, array_size) mdl_value_array = value_factory.create_array(array_type) mdl_value_array.set_size(array_size) for index in range(array_size): usd_value = value[index] atomic_value = value_factory.create_color(usd_value[0],usd_value[1],usd_value[2]) mdl_value_array.set_value(index, atomic_value) expression = expression_factory.create_constant(mdl_value_array) return expression elif usd_type == Sdf.ValueTypeNames.StringArray: value = input.Get() array_size = len(value) atomic_type = type_factory.create_string() if not atomic_type.is_valid_interface(): return None array_type = type_factory.create_immediate_sized_array(atomic_type, array_size) mdl_value_array = value_factory.create_array(array_type) mdl_value_array.set_size(array_size) for index in range(array_size): usd_value = value[index] atomic_value = value_factory.create_string() atomic_value.set_value(usd_value) mdl_value_array.set_value(index, atomic_value) expression = expression_factory.create_constant(mdl_value_array) return expression elif numpy.isscalar(value[0]): # Vector vector_size = len(value) type = self.create_type_or_value(usd_type, type_factory) if not type.is_valid_interface(): return None vector_type = type_factory.create_vector(type, vector_size) if not vector_type.is_valid_interface(): return None mdl_value_vector = value_factory.create_vector(vector_type) for index in range(vector_size): usd_value = value[index] atomic_value = self.create_type_or_value(usd_type, value_factory) atomic_value.set_value(usd_value) mdl_value_vector.set_value(index, atomic_value) expression = expression_factory.create_constant(mdl_value_vector) return expression else: # Array value = input.Get() array_size = len(value) vector_size = len(value[0]) type = self.create_type_or_value(usd_type, type_factory) if not type.is_valid_interface(): return None vector_type = type_factory.create_vector(type, vector_size) if not vector_type.is_valid_interface(): return None array_type = type_factory.create_immediate_sized_array(vector_type, array_size) mdl_value_array = value_factory.create_array(array_type) mdl_value_array.set_size(array_size) for index in range(array_size): mdl_value_vector = value_factory.create_vector(vector_type) usd_value = value[index] for index2 in range(vector_size): atomic_value = self.create_type_or_value(usd_type, value_factory) atomic_value.set_value(usd_value[index2]) mdl_value_vector.set_value(index2, atomic_value) mdl_value_array.set_value(index, mdl_value_vector) expression = expression_factory.create_constant(mdl_value_array) return expression #-------------------------------------------------------------------------------------------------- def convert_value(context, input, mdl_type): neuray = context.neuray transaction = context.transaction factory = neuray.get_api_component(pymdlsdk.IMdl_factory) expression_factory = factory.create_expression_factory(transaction) value_factory = factory.create_value_factory(transaction) type_factory = factory.create_type_factory(transaction) name = input.GetBaseName() type = input.GetTypeName() # Try to follow the connection # TODO: not sure this is properly implemented, need further tests expression = None if input.HasConnectedSource(): (source, sourceName, sourceType) = input.GetConnectedSource() if UsdShade.Shader(source): prim = source.GetPrim() inst_name = create_material_instance(context, prim.GetPath(), None) # TODO Test None expression_list if not inst_name == None: expression = expression_factory.create_call(inst_name) else: expression = convert_value(context, UsdShade.Input(input.GetValueProducingAttribute()[0]), mdl_type) if expression == None: # No connections mdlvalue = None if type == Sdf.ValueTypeNames.Int: if not input.GetRenderType() == None: # Handle Enum tf = factory.create_type_factory(transaction) if tf and tf.is_valid_interface(): et = tf.create_enum(input.GetRenderType()) if et and et.is_valid_interface(): mdlvalue = value_factory.create_enum(et) if mdlvalue == None: # Fallback mdlvalue = value_factory.create_int() elif type == Sdf.ValueTypeNames.Float: mdlvalue = value_factory.create_float() elif type == Sdf.ValueTypeNames.Bool: mdlvalue = value_factory.create_bool() elif type == Sdf.ValueTypeNames.Double: mdlvalue = value_factory.create_double() elif type == Sdf.ValueTypeNames.String: mdlvalue = value_factory.create_string() elif type == Sdf.ValueTypeNames.Color3f: value = input.Get() if value: mdlvalue = value_factory.create_color(value[0], value[1], value[2]) else: mdlvalue = value_factory.create_color(0, 0, 0) expression = expression_factory.create_constant(mdlvalue) return expression elif type == Sdf.ValueTypeNames.Asset: is_texture = mdl_type.get_kind() == pymdlsdk.IType.Kind.TK_TEXTURE if not is_texture and mdl_type.get_kind() == pymdlsdk.IType.Kind.TK_ALIAS: type_alias = mdl_type.get_interface(pymdlsdk.IType_alias) aliased_type = type_alias.get_aliased_type() is_texture = aliased_type.get_kind() == pymdlsdk.IType.Kind.TK_TEXTURE if is_texture: # Shape # TS_2D = 0, # TS_3D = 1, # TS_CUBE = 2, # TS_PTEX = 3, # TS_BSDF_DATA = 4, tt = aliased_type.get_interface(pymdlsdk.IType_texture) shape = tt.get_shape() texture_name = GetUniqueName.get(transaction, "texture") # TODO_PA: Has to specify argc and argv otherwise failure tex = transaction.create("Texture", 0, None) transaction.store(tex, texture_name) value = input.Get() if value: texture = transaction.edit_as(pymdlsdk.ITexture, texture_name) texture.set_image(value.path) tex_type = type_factory.create_texture(shape) mdlvalue = value_factory.create_texture(tex_type, texture_name) if mdlvalue: expression = expression_factory.create_constant(mdlvalue) return expression elif type in ( Sdf.ValueTypeNames.Float2,\ Sdf.ValueTypeNames.Float2Array,\ Sdf.ValueTypeNames.Float3,\ Sdf.ValueTypeNames.Float3Array,\ Sdf.ValueTypeNames.Float4,\ Sdf.ValueTypeNames.Float4Array,\ Sdf.ValueTypeNames.Int2,\ Sdf.ValueTypeNames.Int2Array,\ Sdf.ValueTypeNames.Int3,\ Sdf.ValueTypeNames.Int3Array,\ Sdf.ValueTypeNames.Int4,\ Sdf.ValueTypeNames.Int4Array,\ Sdf.ValueTypeNames.Double2,\ Sdf.ValueTypeNames.Double2Array,\ Sdf.ValueTypeNames.Double3,\ Sdf.ValueTypeNames.Double3Array,\ Sdf.ValueTypeNames.Double4,\ Sdf.ValueTypeNames.Double4Array,\ Sdf.ValueTypeNames.BoolArray,\ Sdf.ValueTypeNames.IntArray,\ Sdf.ValueTypeNames.FloatArray,\ Sdf.ValueTypeNames.DoubleArray,\ Sdf.ValueTypeNames.Color3fArray,\ Sdf.ValueTypeNames.StringArray,\ Sdf.ValueTypeNames.Matrix2d,\ Sdf.ValueTypeNames.Matrix3d,\ Sdf.ValueTypeNames.Matrix4d\ ): converter = ConvertVectorAndArray() return converter.convert(input, type, type_factory, value_factory, expression_factory) # TODO Convert structures # elif type == Sdf.ValueTypeNames.Token: # pass else: print("Error: Unsupported input (parm/type): {}/{}".format(name, type)) if mdlvalue: value = input.Get() rtn = 0 if not value == None: rtn = mdlvalue.set_value(value) if rtn and not rtn == 0: print("set_value() error ({}) for (parm/type/value): {}/{}/{}".format(rtn, name, type, value)) expression = expression_factory.create_constant(mdlvalue) return expression return expression #-------------------------------------------------------------------------------------------------- def set_default_value(context, parm_name, definition): defaults = definition.get_defaults() i = defaults.get_index(parm_name) if i != -1: return defaults.get_expression(i) return None #-------------------------------------------------------------------------------------------------- def convert_parameter(context, definition, input): name = input.GetBaseName() index = definition.get_parameter_index(name) if index >= 0: types = definition.get_parameter_types() if types: type = types.get_type(index) if type: expression = convert_value(context, input, type) if expression and expression.is_valid_interface(): return expression else: print("Error: Invalid expression for parameter: {}".format(name)) return None #-------------------------------------------------------------------------------------------------- def edit_instance(transaction, inst_name): return transaction.edit_as(pymdlsdk.IFunction_call, inst_name) #-------------------------------------------------------------------------------------------------- def dump_expression_list(expression_list): print("===== Dump expression list =====") for index in range(expression_list.get_size()): name = expression_list.get_name(index) expr = expression_list.get_expression(index) print("Expression name/kind/type kind: {} / {} / {}".format(name, expr.get_kind(), expr.get_type().get_kind())) print("===== End dump expression list =====") #-------------------------------------------------------------------------------------------------- def dump_parameter_types(fctdef, neuray, transaction): print("===== Dump parameter types =====") name = fctdef.get_mdl_simple_name() print("Function name: {}".format(name)) pt = fctdef.get_parameter_types() factory = neuray.get_api_component(pymdlsdk.IMdl_factory) type_factory = factory.create_type_factory(transaction) print(type_factory.dump(pt).get_c_str()) # for i in range(pt.get_size()): # t = pt.get_type(i) # k = t.get_kind() # if k == pymdlsdk.IType.Kind.TK_ALIAS: # a = t.get_interface(pymdlsdk.IType_alias) # k = a.get_aliased_type().get_kind() # pn = fctdef.get_parameter_name(i) # print("Parameter name/kind: {} / {}".format(pn, k)) print("===== End dump parameter types =====") #-------------------------------------------------------------------------------------------------- def convert_parameters(context, prim_path): definition = get_definition(context, prim_path) if not definition: return None stage = context.stage prim = get_shader_prim(stage, prim_path) # expression_list = definition.get_defaults() # expression_list = pymdlsdk.IExpression_list() neuray = context.neuray factory = neuray.get_api_component(pymdlsdk.IMdl_factory) transaction = context.transaction expression_factory = factory.create_expression_factory(transaction) expression_list = expression_factory.create_expression_list() if prim: shader = UsdShade.Shader(prim) if shader: inputs = shader.GetInputs() for input in inputs: name = input.GetBaseName() expression = convert_parameter(context, definition, input) if expression: rtn = expression_list.add_expression(name, expression) if rtn != 0: print("Error") # dump_expression_list(expression_list) # Handle parameters which are not set defaults = definition.get_defaults() parameter_types = definition.get_parameter_types() value_factory = factory.create_value_factory(transaction) for i in range(definition.get_parameter_count()): name = definition.get_parameter_name(i) if expression_list.get_index(name) == -1: type = parameter_types.get_type(i) value = value_factory.create(type) expr = expression_factory.create_constant(value) expression_list.add_expression(name, expr) return expression_list #-------------------------------------------------------------------------------------------------- def dump_material_instance(context, inst_name): transaction = context.transaction inst = edit_instance(transaction, inst_name) if not inst.is_valid_interface(): return print("============ MDL Dump =============") print(inst_name) print("") neuray = context.neuray factory = neuray.get_api_component(pymdlsdk.IMdl_factory) expression_factory = factory.create_expression_factory(transaction) count = inst.get_parameter_count() arguments = inst.get_arguments() for index in range(count): argument = arguments.get_expression(index) name = inst.get_parameter_name(index) argument_text = expression_factory.dump(argument, name, 1) print(argument_text.get_c_str()) print("============ MDL Dump =============") #-------------------------------------------------------------------------------------------------- # Return a shader prim corresponding to the input prim_path. # If prim_path is a shader, return the corresponding prim. # If prim_path is a material, return the first shader found in the list of children. def get_shader_prim(stage, prim_path): prim = stage.GetPrimAtPath(Sdf.Path(prim_path)) if UsdShade.Shader(prim): return prim if UsdShade.Material(prim): mat = UsdShade.Material(prim) if mat.GetOutput("mdl:surface") and mat.GetOutput("mdl:surface").HasConnectedSource(): (src, name, t) = mat.GetOutput("mdl:surface").GetConnectedSource() if UsdShade.Shader(src): return src.GetPrim() for prim in prim.GetChildren(): if UsdShade.Shader(prim): return prim if UsdShade.NodeGraph(prim): ng = UsdShade.NodeGraph(prim) if ng.GetOutput("out") and ng.GetOutput("out").HasConnectedSource(): (src, name, t) = ng.GetOutput("out").GetConnectedSource() if UsdShade.Shader(src): return src.GetPrim() for prim in prim.GetChildren(): if UsdShade.Shader(prim): return prim return None #-------------------------------------------------------------------------------------------------- def get_sub_identifier_from_prim(prim): sub_id = prim.GetAttribute("info:mdl:sourceAsset:subIdentifier").Get() if not sub_id: sub_id = prim.GetAttribute("info:sourceAsset:subIdentifier").Get() return sub_id #-------------------------------------------------------------------------------------------------- def get_definition(context, prim_path): stage = context.stage prim = get_shader_prim(stage, prim_path) if not prim: print("Error:\tCould not find any shader in prim '{}' from stage '{}'".format(prim_path, stage.GetRootLayer().GetDisplayName())) else: shader = UsdShade.Shader(prim) if shader: imp_source = shader.GetImplementationSourceAttr().Get() if imp_source == "sourceAsset": # Retrieve module name source_asset = shader.GetSourceAsset("mdl") neuray = context.neuray (success, module_db_name) = load_module(context, source_asset) if not success: print("Error: Failed to load module: {}".format(source_asset)) else: sub_id = get_sub_identifier_from_prim(prim) if sub_id: transaction = context.transaction module = pymdl.Module._fetchFromDb(transaction, module_db_name) if module: fct = find_function(module, sub_id) if fct: fctdef = transaction.access_as(pymdlsdk.IFunction_definition, fct.dbName) if fctdef.is_valid_interface(): return fctdef return None #-------------------------------------------------------------------------------------------------- def list_functions(module: pymdl.Module): for k in module.functions.keys(): for index in range(len(module.functions[k])): print(module.functions[k][index].mdlName.split("::")[-1]) #-------------------------------------------------------------------------------------------------- # return (module_name, simple_name, parameters) # module_name without trailing '::' # e.g. if sub_id = '::nvidia::foo::bar(float,color)' # module_name = '::nvidia::foo' # simple_name = 'bar' # parameters = 'float,color' def split_function_name(sub_id: str): module_name = "" simple_name = "" parameters = "" lf = sub_id.split('(') name_and_module = lf[0] lm = name_and_module.split('::') if len(lm) > 1: module_name = '::'.join(lm[0:-1]) simple_name = lm[-1] if len(lf) > 1: parameters = lf[1].split(')')[0] return (module_name, simple_name, parameters) #-------------------------------------------------------------------------------------------------- def find_function(module: pymdl.Module, sub_id: str): (module_name, simple_name, parameters) = split_function_name(sub_id) if simple_name in module.functions: if sub_id == simple_name: # Exact match, no overload, return the function return module.functions[simple_name][0] # Access the function definition, enumerate the overloads for index in range(len(module.functions[simple_name])): fct = module.functions[simple_name][index] (candidate_module_name, candidate_simple_name, candidate_parameters) = split_function_name(fct.mdlName) if parameters == candidate_parameters: return module.functions[simple_name][index] print("Error: Function not found in module (function/module): {} / {}".format(sub_id, module.filename)) # list_functions(module) return None #-------------------------------------------------------------------------------------------------- def create_material_instance(context, prim_path, expression_list): stage = context.stage prim = get_shader_prim(stage, prim_path) if prim: shader = UsdShade.Shader(prim) if shader: imp_source = shader.GetImplementationSourceAttr().Get() if imp_source == "sourceAsset": # Retrieve module name source_asset = shader.GetSourceAsset("mdl") neuray = context.neuray (success, module_db_name) = load_module(context, source_asset) if success: sub_id = get_sub_identifier_from_prim(prim) if sub_id: transaction = context.transaction module = pymdl.Module._fetchFromDb(transaction, module_db_name) if module: fct = find_function(module, sub_id) if fct: with transaction.access_as(pymdlsdk.IFunction_definition, fct.dbName) as fctdef: inst = None if fctdef.is_valid_interface(): if expression_list == None: expression_list = convert_parameters(context, prim_path) # dump_parameter_types(fctdef, context.neuray, context.transaction) (inst, ret) = fctdef.create_function_call_with_ret(expression_list) fname = "create_material_instance()" error = {0: "Success.", -1: "An argument for a non-existing parameter was provided in 'arguments'.", -2: "The type of an argument in 'arguments' does not have the correct type, see #get_parameter_types().", -3: "A parameter that has no default was not provided with an argument value.", -4: "The definition can not be instantiated because it is not exported.", -5: "A parameter type is uniform, but the corresponding argument has a varying return type.", -6: "An argument expression is not a constant nor a call.", -8: "One of the parameter types is uniform, but the corresponding argument or default is a \ call expression and the return type of the called function definition is effectively varying since the \ function definition itself is varying.", -9: "The function definition is invalid due to a module reload, see #is_valid() for diagnostics."} if inst: if inst.is_valid_interface(): (module_name, simple_name, parameters) = split_function_name(fct.dbName) inst_name = module_name + "::" + simple_name + "::converted" inst_name = GetUniqueName.get(transaction, inst_name) transaction.store(inst, inst_name) return inst_name else: print("Error: Invalid instance for function: {}".format(fct.mdlSimpleName)) print("{} error {}: {}".format(fname, ret, error[ret])) if ret == -2: dump_parameter_types(fctdef, context.neuray, context.transaction) return None #-------------------------------------------------------------------------------------------------- async def convert_usd_to_mdl(context, prim_path, output_filename): inst_name = None mdl_entity = None mdl_entity_snapshot = None if not context.ov_neuray == None: # We are in OV # Get the shader prim from Material shader_prim_path = get_shader_prim(context.stage, prim_path) if shader_prim_path == None: print(f"Error: can not access prim: '{prim_path}'") return None mdl_entity = context.ov_neuray.createMdlEntity(shader_prim_path.GetPath().pathString) mdl_entity_snapshot = None if not mdl_entity.getMdlModule() == None: mdl_entity_snapshot = context.ov_neuray.createMdlEntitySnapshot(mdl_entity) inst_name = mdl_entity_snapshot.dbName else: print(f"Error: can not access entity: '{prim_path}'") else: # Outside of OV, conversion is done here expression_list = convert_parameters(context, prim_path) inst_name = create_material_instance(context, prim_path, expression_list) if inst_name is not None: dump_material_instance(context, inst_name) if output_filename: # we use a temporary folder for resources from the server with tempfile.TemporaryDirectory() as temp_dir: success = await save_instance_to_module(context, inst_name, prim_path, temp_dir, output_filename) if not success: inst_name = None if not context.ov_neuray == None: # We are in OV if not mdl_entity_snapshot == None: context.ov_neuray.destroyMdlEntitySnapshot(mdl_entity_snapshot) if not mdl_entity == None: context.ov_neuray.destroyMdlEntity(mdl_entity) return inst_name #-------------------------------------------------------------------------------------------------- # Split the input string or list of strings using given the split char # Return a list of strings def split_list(list_of_strings, split_char): res = [] if type(list_of_strings) == list: for s in list_of_strings: res += s.split(split_char) else: res = list_of_strings.split(split_char) return res #-------------------------------------------------------------------------------------------------- # Remove all occurences of element from the list def remove_all_occurences_of_element_from_list(element, alist): try: while True: alist.remove(element) except: pass finally: return alist #-------------------------------------------------------------------------------------------------- # Split the input string or list of strings using all the input split chars def multi_split_list(list_of_strings, list_of_splits): res = list_of_strings for split in list_of_splits: res = split_list(res, split) return res #-------------------------------------------------------------------------------------------------- # Identify a line containing an MD import declaration # From the MDL 1.7 specs: # import : import qualified_import {, qualified_import} ; # | [export] using import_path # import ( * | simple_name {, simple_name} ) ; def is_import_line(token_list): if 'import' in token_list: if token_list[0] == 'import' or token_list[0] == 'export' or token_list[0] == 'using': return True return False #-------------------------------------------------------------------------------------------------- # Construct a set or strings found in an MDL module # Split the input strings using several separators (' ',';','(', ')') # if filter_import_lines is set to True, then only process lines beginning with 'import' def find_tokens(lines, filter_import_lines = False): all_ids = set() input_list = lines if not type(lines) == list: input_list = [lines] for l in input_list: ids = multi_split_list(l, [' ',';','(', ')']) remove_all_occurences_of_element_from_list('', ids) if filter_import_lines: if not is_import_line(ids): continue for id in ids: if not id.find('::') == -1: tokens = id.split('::') for t in tokens: if len(t) > 0: all_ids.add(t) return all_ids #-------------------------------------------------------------------------------------------------- # Find MDL identifier in this line of text if text is an import statement def find_import(line): ids = multi_split_list(line, [' ',';','(', ')']) remove_all_occurences_of_element_from_list('', ids) if is_import_line(ids): for id in ids: if not id.find('::') == -1: return id return '' #-------------------------------------------------------------------------------------------------- # Find MDL identifier in this line of text def find_identifiers(line): rtn_identifiers = set() ids = multi_split_list(line, [' ', ';', '(', ')', ',', '\n']) remove_all_occurences_of_element_from_list('', ids) for id in ids: if not id.find('::') == -1: rtn_identifiers.add(id) return rtn_identifiers #-------------------------------------------------------------------------------------------------- # Substitute source strings with target strings found in the input table in the input lines # Input lines is a string or list of strings def replace_tokens(lines, table): if type(lines) == list: for i in range(len(lines)): for k in table.keys(): lines[i] = lines[i].replace(k, table[k]) return lines else: for k in table.keys(): lines = lines.replace(k, table[k]) return lines #-------------------------------------------------------------------------------------------------- # Helper to perfom unmangling on MDL module files and MDL identifiers # Un-mangling is only done in the framework of OV if an un-mangling routine exists class Unmangle: unmangle_routine = None def __init__(self, context): if context.ov_neuray != None: if "_unmangleMdlModulePath" in dir(context.ov_neuray): self.unmangle_routine = context.ov_neuray._unmangleMdlModulePath # Un-mangle a single token # token should not contain any '::' def _unmangle_token(self, token): assert(token.find("::") == -1) # Un-mangle the input token # Add prefix otherwise unmangling has not effect unmangled_token = self.unmangle_routine("::" + token) # Remove any '.mdl' extension from unmangled token if len(unmangled_token) > 4 and unmangled_token[-4:] == '.mdl': unmangled_token = unmangled_token[:-4] unmangled = (unmangled_token != token) return (unmangled, unmangled_token) # Build an un-mangling mapping table from the input list of tokens def build_mapping_table(self, token_list): table = dict() for token in token_list: (unmangled_flag, unmangled_token) = self._unmangle_token(token) if unmangled_flag: table[token] = unmangled_token return table # Un-mangled an MDL identifier # Return a tuple (True if unmagling was done, unmangled value) def unmangle_mdl_identifier(self, source): if self.unmangle_routine == None: return (False, source) token_list = find_tokens(source) table = self.build_mapping_table(token_list) unmangled_str = replace_tokens(source, table) return (unmangled_str != source, unmangled_str) # Un-mangle an MDL file and create a new un-mangled output file def unmangle_mdl_file(self, infile, outfile): if self.unmangle_routine == None: return # Only consider 'import' statements filter_import_lines = True with open(infile, 'r') as f_in: lines = f_in.readlines() token_list = find_tokens(lines, filter_import_lines) mapping = self.build_mapping_table(token_list) lines = replace_tokens(lines, mapping) with open(outfile, 'w') as f_out: f_out.writelines(lines) #-------------------------------------------------------------------------------------------------- def parse_alias(pattern, line): match = pattern.match(line) if match == None: return(False, '', '') alias = match.group("alias") path_segment = match.group("value") # print(f"alias: '{alias}' path_segment: '{path_segment}'") return(True, alias, path_segment) #-------------------------------------------------------------------------------------------------- # This unmangling class uses MDL search path to trim down MDL identifiers # It uses also MDL aliases to perform substitutions in the MDL identifier class UnmangleAndFixMDLSearchPath(Unmangle): alias_pattern = None def __init__(self, context): # compile pattern only once as it is constant self.alias_pattern = re.compile(r"""\s*using\s* # whitespace, using, whitespace (?P<alias>.*?) # alias name \s*=\s* # whitespace, equal, whitespace \"(?P<value>.*?)\" # value in quotes, \s*;""", re.VERBOSE) # semicolon, whitespace # Build MDL search path list self.mdl_search_paths = list() with context.neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg: if cfg.is_valid_interface(): for i in range(cfg.get_mdl_paths_length()): sp = cfg.get_mdl_path(i) sp = os.path.normpath(sp.get_c_str()) self.mdl_search_paths.append(sp) super(UnmangleAndFixMDLSearchPath, self).__init__(context) # Determine if this line is defining an alias def __is_alias(self, line): (is_alias, alias, path_segment) = parse_alias(self.alias_pattern, line) if is_alias: return (True, path_segment, alias) return (False, '', '') # Determine if this identifier is mangled def __is_mangled_identifier(self, id): token_list = id.split("::") remove_all_occurences_of_element_from_list('', token_list) for token in token_list: (unmangled_flag, unmangled_token) = self._unmangle_token(token) if unmangled_flag: return unmangled_flag return False # Determine if this string contains a mangled identifier def __get_mangled_identifiers(self, line): identifiers = find_identifiers(line) rtn_identifiers = set() for id in identifiers: if len(id) > 0: if self.__is_mangled_identifier(id): rtn_identifiers.add(id) return rtn_identifiers # Build mapping table for a given mangled identifier # Using the stored MDL search paths and the MDL aliases def __build_table_from_mangled_id(self, id, aliases, makeRelativeIfFailure: bool = False): key = '' value = '' # unmangle using _unmangleMdlModulePath if not id.find('::') == 0: unmangled_id = self.unmangle_routine("::" + id) else: unmangled_id = self.unmangle_routine(id) unmangled_id = re.sub('^file:/', '', unmangled_id) # Replace aliases for alias in aliases.keys(): unmangled_id = unmangled_id.replace(aliases[alias], alias) unmangled_id = os.path.normpath(unmangled_id) # Remove MDL seach path search_path_removed = False mapping_table = dict() for sp in self.mdl_search_paths: temp_id = unmangled_id temp_sp = sp if platform.system() == 'Windows': temp_id = unmangled_id.lower() temp_sp = sp.lower() # Remove the search path only when the path is found at the head of id if temp_id.startswith(temp_sp): unmangled_id = unmangled_id[len(sp):] search_path_removed = True break # Conversion is done only if we did find search path prefix in the identifier if search_path_removed: replaced = unmangled_id replaced = replaced.replace('\\', '::') replaced = replaced.replace('.mdl::', '::') what_to_replace = id mapping_table[what_to_replace] = replaced return (True, mapping_table) else: if makeRelativeIfFailure: # Turn absolute path to relative unmangled_id = os.path.basename(unmangled_id) replaced = unmangled_id replaced = replaced.replace('.mdl::', '::') what_to_replace = id mapping_table[what_to_replace] = replaced return (True, mapping_table) return (False, mapping_table) # Un-mangle an MDL file and create a new un-mangled output file def unmangle_mdl_file(self, infile, outfile): if self.unmangle_routine == None: return # Read file mapping_table = dict() with open(infile, 'r') as f_in: input_lines = f_in.readlines() if not type(input_lines) == list: # handle single line input_lines = [input_lines] # aliases mapping table aliases = dict() for line in input_lines: (alias, key, value) = self.__is_alias(line) if alias: aliases[key] = value continue ids = self.__get_mangled_identifiers(line) for id in ids: (success, new_mapping_table) = self.__build_table_from_mangled_id(id, aliases) if success: # Mege new mapping in mapping_table.update(new_mapping_table) # Replace in file and write out result with open(infile, 'r') as f_in: lines = f_in.readlines() lines = replace_tokens(lines, mapping_table) with open(outfile, 'w') as f_out: f_out.writelines(lines) # Un-mangle an MDL file and create a new un-mangled output file # Return (is identifier mangled, demangling and removing search path succeeded, un-mangled module name) def unmangle_mdl_module(self, module): if self.unmangle_routine == None: return (False, True, module) rtn = module isMangled = self.__is_mangled_identifier(module) (success, mapping_table) = self.__build_table_from_mangled_id(module, dict(), makeRelativeIfFailure = True) if success: rtn = mapping_table[module] if rtn.find('::') == 0: rtn = rtn[2:] rtn = rtn.replace("::", "/") return (isMangled, success, rtn) #-------------------------------------------------------------------------------------------------- def is_reserved_word(name : str): # there will be an API function for this soon reserved_words = ['annotation', 'auto', 'bool', 'bool2', 'bool3', 'bool4', 'break', 'bsdf', 'bsdf_measurement', 'case', 'cast', 'color', 'const', 'continue', 'default', 'do', 'double', 'double2', 'double2x2', 'double2x3', 'double3', 'double3x2', 'double3x3', 'double3x4', 'double4', 'double4x3', 'double4x4', 'double4x2', 'double2x4', 'edf', 'else', 'enum', 'export', 'false', 'float', 'float2', 'float2x2', 'float2x3', 'float3', 'float3x2', 'float3x3', 'float3x4', 'float4', 'float4x3', 'float4x4', 'float4x2', 'float2x4', 'for', 'hair_bsdf', 'if', 'import', 'in', 'int', 'int2', 'int3', 'int4', 'intensity_mode', 'intensity_power', 'intensity_radiant_exitance', 'let', 'light_profile', 'material', 'material_emission', 'material_geometry', 'material_surface', 'material_volume', 'mdl', 'module', 'package', 'return', 'string', 'struct', 'switch', 'texture_2d', 'texture_3d', 'texture_cube', 'texture_ptex', 'true', 'typedef', 'uniform', 'using', 'varying', 'vdf', 'while', 'catch', 'char', 'class', 'const_cast', 'delete', 'dynamic_cast', 'explicit', 'extern', 'external', 'foreach', 'friend', 'goto', 'graph', 'half', 'half2', 'half2x2', 'half2x3', 'half3', 'half3x2', 'half3x3', 'half3x4', 'half4', 'half4x3', 'half4x4', 'half4x2', 'half2x4', 'inline', 'inout', 'lambda', 'long', 'mutable', 'namespace', 'native', 'new', 'operator', 'out', 'phenomenon', 'private', 'protected', 'public', 'reinterpret_cast', 'sampler', 'shader', 'short', 'signed', 'sizeof', 'static', 'static_cast', 'technique', 'template', 'this', 'throw', 'try', 'typeid', 'typename', 'union', 'unsigned', 'virtual', 'void', 'volatile', 'wchar_t'] return name in reserved_words #-------------------------------------------------------------------------------------------------- # the db name of a texture is constructed here: # rendering\include\rtx\neuraylib\NeurayLibUtils.h # computeSceneIdentifierTexture def parse_ov_resource_name(texture_db_name : str): # drop the db prefix texture_db_name = texture_db_name[5:] undescore = texture_db_name.rfind('_') texture_db_name = texture_db_name[:undescore] undescore = texture_db_name.rfind('_') return texture_db_name[:undescore] async def prepare_resources_for_export(transaction : pymdlsdk.ITransaction, inst_name, temp_dir): functionCall = pymdl.FunctionCall._fetchFromDb(transaction, inst_name) for name, param in functionCall.parameters.items(): # name if param.type.kind == pymdlsdk.IType.Kind.TK_TEXTURE and param.value[0] != None: # print(f"* Name: {name}") # print(f" Type Kind: {param.type.kind}") texture_path = parse_ov_resource_name(param.value[0]) # print(f" texture_path: {texture_path}") # print(f" db_name: {param.value[0]}") # print(f" gamma: {param.value[1]}") # special handling for resources on the server if texture_path.startswith("omniverse:") or \ texture_path.startswith("file:") or \ texture_path.startswith("ftp:") or \ texture_path.startswith("http:") or \ texture_path.startswith("https:"): basename = os.path.basename(texture_path) filename, fileext = os.path.splitext(basename) id = 0 dst_path = os.path.join(temp_dir, basename) while (os.path.exists(dst_path)): dst_path = os.path.join(temp_dir, f"{filename}_{id}{fileext}") id = id + 1 result = await copy_async(texture_path, dst_path) if not result: print(f"Cannot copy from {texture_path} to {dst_path}, error code: {result}.") continue else: print(f"Downloaded resource from {texture_path} to {dst_path}. Will be deleted after export.") # use the resource in the temp folder texture_path = dst_path # create a new image new_image_db_name = "mdlexp::" + texture_path with transaction.create("Image", 0, None) as new_interface: with new_interface.get_interface(pymdlsdk.IImage) as new_image: new_image.reset_file(texture_path) transaction.store(new_image, new_image_db_name) transaction.remove(new_image_db_name) # drop after transaction is closed # assign the image to the texture # todo make sure the transaction is aborted, we don't want this change visible to other components with transaction.edit_as(pymdlsdk.ITexture, param.value[0]) as itexture: itexture.set_image(new_image_db_name) itexture.set_gamma(param.value[1]) # TODO check if srgb and linear work with floating precission here if isinstance(param, pymdl.ArgumentCall): # print(f"* Name: {name}") # print(f" Type Kind: {param.type.kind}") # print(f" dbName: {param.value}") await prepare_resources_for_export(transaction, param.value, temp_dir) # ExportHelper: Helps to save files to Nucleus server. # If we want to export a file to Nucleus, this helper: # 1- creates a temp folder, # 2- substitutes the original Nucleus folder with the temp folder, # 3- files are saved/exported to the temp folder, # 4- when finalize() is called, the content of the temp folder is saved to Nucleus server # and temp folder is deleted class ExportHelper: def __init__(self, out_filename): self.original_filename = out_filename self.out_filename = out_filename self.temp_dir = None # If out_filename is on Nucleus, then change it to temp filename if out_filename.startswith("omniverse:") or \ out_filename.startswith("file:") or \ out_filename.startswith("ftp:"): # create a temp folder self.temp_dir = tempfile.TemporaryDirectory() # substitutes the original Nucleus folder with the temp folder self.out_filename = os.path.join(self.temp_dir.name, os.path.basename(out_filename)) async def finalize(self, copy_files: bool = True): # If out_filename is different from the original one, copy all files # from the temp folder to the Nucleus server if self.temp_dir != None: if copy_files: from_dir = os.path.dirname(self.out_filename) to_dir = os.path.dirname(self.original_filename) for ld in os.listdir(from_dir): f = os.path.basename(ld) result = await copy_async(os.path.join(from_dir, f), to_dir + '/' + f) if not result: print(f"Cannot copy from {f} to {to_dir}, error code: {result}.") else: print(f"Copied resource {f} to {to_dir}.") # Delete temp folder self.temp_dir.cleanup() async def save_instance_to_module(context, inst_name, usd_prim, temp_dir, out_filename): print("============ MDL Save Instance to Module =============") neuray = context.neuray transaction = context.transaction stage = context.stage # access shader prim prim = get_shader_prim(stage, usd_prim) prim_name = usd_prim.pathString.split('/')[-1] if out_filename == None or os.path.isdir(out_filename) or os.path.splitext(out_filename)[1] != '.mdl': print(f"Error: output filename is invalid, expected an .mdl file: '{out_filename}'") return False # Handle Nucleus: OM-46539 Graph to MDL fails to copy Nucleus textures to local filesystem when exporting export_helper = ExportHelper(out_filename) out_filename = export_helper.out_filename # Sanity checks with transaction.access_as(pymdlsdk.IFunction_call, inst_name) as inst: if inst == None or not inst.is_valid_interface(): print("Error: Invalid instance name (IFunction_call): {}".format(inst_name)) return False with transaction.access_as(pymdlsdk.IFunction_definition, inst.get_function_definition()) as fd: if fd == None or not fd.is_valid_interface(): print("Error: Invalid IFunction_definition: {}".format(inst.get_function_definition())) return False module = pymdl.Module._fetchFromDb(transaction, fd.get_module()) if module == None: print("Error: Invalid Module: {}".format(fd.get_module())) return False # since resourcse are handled by the renderer we need to pass them to neuray before exporting await prepare_resources_for_export(transaction, inst_name, temp_dir) factory: pymdlsdk.IMdl_factory = neuray.get_api_component(pymdlsdk.IMdl_factory) execution_context = factory.create_execution_context() # Create the module builder. module_name = "mdl::new_module_28f8c871b7034e55a0541be81655ffb1" module_builder = factory.create_module_builder( transaction, module_name, pymdlsdk.MDL_VERSION_1_6, # In order to use aliases pymdlsdk.MDL_VERSION_LATEST, execution_context) if not module_builder.is_valid_interface(): print("Error: Failed to create module builder") return False module_builder.clear_module(execution_context) # Create a variant success = False with transaction.access_as(pymdlsdk.IFunction_call, inst_name) as inst, \ factory.create_expression_factory(transaction) as ef, \ ef.create_annotation_block() as empty_anno_block: if inst.is_valid_interface(): if is_reserved_word(prim_name): variant_name = "Main" else: variant_name = prim_name result = module_builder.add_variant( variant_name, inst.get_function_definition(), inst.get_arguments(), empty_anno_block, empty_anno_block, True, execution_context) if result != 0: print("Error: Failed to add variant to module builder:\n\t'{}'\n\t'{}'\n\t'{}'".format(prim.GetName(), inst.get_function_definition(), inst.get_arguments())) for i in range(execution_context.get_messages_count()): print(execution_context.get_message(i).get_string()) if result == 0: with neuray.get_api_component(pymdlsdk.IMdl_impexp_api) as imp_exp: rtn = -1 execution_context.set_option("bundle_resources", True) rtn = imp_exp.export_module(transaction, module_name, out_filename, execution_context) if rtn >= 0: unmangle_helper = UnmangleAndFixMDLSearchPath(context) unmangle_helper.unmangle_mdl_file(out_filename, out_filename) print(f"Success: Material '{prim_name}' exported to module '{out_filename}'") # Copy files to Nucleus if needed await export_helper.finalize() success = True else: print(f"Failure: Could not export Material '{prim_name}' to module '{out_filename}'") await export_helper.finalize(copy_files = False) module_builder.clear_module(execution_context) return success
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/test_usd_converter.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.mdl.usd_converter import omni.usd import shutil import pathlib import os import carb import carb.settings # Having a test class derived from omni.kit.test.AsyncTestCase declared on the root of module # will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCaseFailOnLogError): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._test_data = str(pathlib.Path(__file__).parent.joinpath("data")) self._test_data_usd = str(pathlib.Path(self._test_data).joinpath("usd")) self._test_data_mdl = str(pathlib.Path(self._test_data).joinpath("mdl")) # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_mdl_to_usd(self): # Disable standard path to ensure reproducible results locally and in TC NO_STD_PATH = "/app/mdl/nostdpath" settings = carb.settings.get_settings() settings.set_bool(NO_STD_PATH, True) filter_import = False tokens = omni.mdl.usd_converter.find_tokens('mdl::ZA0OmniGlass_2Emdl::OmniGlass::converted_27', filter_import) result = (tokens == {'ZA0OmniGlass_2Emdl', 'converted_27', 'mdl', 'OmniGlass'}) self.assertEqual(result, True) filter_import = True tokens = omni.mdl.usd_converter.find_tokens('import ::state::normal;\n', filter_import) result = (tokens == {'state', 'normal'}) self.assertEqual(result, True) filter_import = False tokens = omni.mdl.usd_converter.find_tokens(' anno::author("NVIDIA CORPORATION"),\n', filter_import) result = (tokens == {'anno', 'author'}) self.assertEqual(result, True) filter_import = True tokens = omni.mdl.usd_converter.find_tokens(' anno::author("NVIDIA CORPORATION"),\n', filter_import) result = (len(tokens) == 0) self.assertEqual(result, True) with omni.mdl.usd_converter.TemporaryDirectory() as temp_dir: test_search_path = self._test_data_mdl fn = "core_definitions.usda" ADD_MDL_PATH = "/app/mdl/additionalUserPaths" settings = carb.settings.get_settings() mdl_custom_paths: List[str] = settings.get(ADD_MDL_PATH) or [] mdl_custom_paths.append(test_search_path) mdl_custom_paths.append(temp_dir) mdl_custom_paths = list(set(mdl_custom_paths)) settings.set_string_array(ADD_MDL_PATH, mdl_custom_paths) result = omni.mdl.usd_converter.mdl_to_usd( moduleName="nvidia/core_definitions.mdl", targetFolder=temp_dir, targetFilename=fn, output=omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY) self.assertEqual(result, True) # fn = "tutorials.usda" # # WORKAROUND: Copy test file to temp folder, NeurayLib does not handle folder containing '*.mdl.*' in their name # source_file = str(pathlib.Path(self._test_data_mdl).joinpath('nvidia/sdk_examples/tutorials.mdl')) # shutil.copy2(source_file, temp_dir) # module = str(pathlib.Path(temp_dir).joinpath("tutorials.mdl")) # if os.path.exists(module): # result = omni.mdl.usd_converter.mdl_to_usd( # moduleName=module, # targetFolder=temp_dir, # targetFilename=fn, # searchPath=test_search_path) # self.assertEqual(result, True) # fn = "test_types.usda" # WORKAROUND: Copy test file to temp folder, NeurayLib does not handle folder containing '*.mdl.*' in their name # source_file = str(pathlib.Path(self._test_data_mdl).joinpath('test/test_types.mdl')) # shutil.copy2(source_file, temp_dir) # module = str(pathlib.Path(temp_dir).joinpath("test_types.mdl")) # if os.path.exists(module): # result = omni.mdl.usd_converter.mdl_to_usd( # moduleName=module, # targetFolder=temp_dir, # targetFilename=fn, # searchPath=test_search_path) # self.assertEqual(result, True) tutorial_scene = str(pathlib.Path(self._test_data_usd).joinpath("tutorials.usda")) if os.path.exists(tutorial_scene): result = await omni.mdl.usd_converter.usd_prim_to_mdl( tutorial_scene, "/example_material", test_search_path, forceNotOV=True) self.assertEqual(result, True) result = await omni.mdl.usd_converter.usd_prim_to_mdl( tutorial_scene, "/example_modulemdl_material_examples", test_search_path, forceNotOV=True) self.assertEqual(result, True) result = await omni.mdl.usd_converter.usd_prim_to_mdl( tutorial_scene, "/wave_gradient", test_search_path, forceNotOV=True) self.assertEqual(result, True) omni.mdl.usd_converter.test_mdl_prim_to_usd('/root') simple_scene = str(pathlib.Path(self._test_data_usd).joinpath("scene.usda")) if os.path.exists(simple_scene): test_prim = '/World/Looks/Material' stage = omni.mdl.usd_converter.mdl_usd.Usd.Stage.Open(simple_scene) prim = stage.GetPrimAtPath(test_prim) omni.mdl.usd_converter.mdl_prim_to_usd(stage, prim) omni.mdl.usd_converter.mdl_usd.get_examples_search_path() mdl_tmpfile = str(pathlib.Path(temp_dir).joinpath("tmpout.mdl")) result = await omni.mdl.usd_converter.export_to_mdl(mdl_tmpfile, prim, forceNotOV=True) self.assertEqual(result, True) # Example: 'mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase' # Return: 'OmniSurface/OmniSurfaceBase.mdl' omni.mdl.usd_converter.mdl_usd.prototype_to_source_asset('mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase') omni.mdl.usd_converter.mdl_usd.parse_ov_resource_name('mdl::resolvedPath_texture_raw')
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/__init__.py
from .test_usd_converter import *
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/data/mdl/nvidia/sdk_examples/tutorials.mdl
/****************************************************************************** * Copyright 2022 NVIDIA Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ mdl 1.6; import ::anno::*; import ::base::*; import ::df::*; import ::math::*; import ::state::*; import ::tex::*; // A simple struct. export struct example_struct { int param_int; float param_float = 0.0; }; // A constant. export const int example_constant = 42; // A simple material. export material example_material(color tint = color(1.0), float roughness = 0) = let bsdf tmp = df::diffuse_reflection_bsdf(tint, roughness); in material( surface: material_surface(scattering: tmp), backface: material_surface(scattering: tmp) ); // A simple function. export color example_function(color tint, float distance) { return distance <= 0 ? color(0.0) : -1.0 * math::log(tint) / distance; } // A material used for instance compilation vs class compilation. export material example_compilation(color tint = color(1.0)) = material( surface: material_surface( scattering: df::diffuse_reflection_bsdf(tint: tint) ), backface: material_surface( scattering: df::diffuse_reflection_bsdf(tint: tint * color(state::normal())) ) ); // The first material used to show the execution of material sub-expressions. export material example_execution1(color tint = color(1.0)) = let { float3 tex_coord = state::texture_coordinate(0); base::texture_return tex = base::file_texture(texture_2d("./resources/example.png")); } in material( surface: material_surface( scattering: df::diffuse_reflection_bsdf( tint: tint * color( 0.5, math::sin(state::position().y) * 0.4 + 0.6, math::cos(state::position().x) * 0.3 + 0.5) * ( 1.1 * tex.tint * tex.mono + base::perlin_noise_texture( uvw: base::texture_coordinate_info( position: tex_coord + state::animation_time() * float3(0, 0, 0.04) ), color1: color(0.1), color2: color(0.7), size: .2, noise_levels: 4 ).tint * (1 - tex.mono * 0.5) ) ) ) ); // Calculate height of waves at the given position. export float wave_height( float2 pos, float2[3] wave_centers = float2[3](float2(0.2, 0.7), float2(0.6, 0.4), float2(0.35, 0.6))) { float radians_per_unit = 5 * 2 * math::PI; float val = 0; for ( int i = 0; i < 3; ++i ) { float dist = math::distance(pos, wave_centers[i]); val += math::cos(dist * radians_per_unit); } return (math::cos(val * math::PI) + 1) / 2; } // Calculate the gradient of the waves at the given texture coordinates. export float3 wave_gradient( base::texture_coordinate_info uvw = base::texture_coordinate_info(), float3 normal = state::normal(), float delta = 0.01, float factor = 1.0, float2[3] wave_centers = float2[3](float2(0.2, 0.7), float2(0.6, 0.4), float2(0.35, 0.6))) { float2[3] offsets( float2(0.0, 0.0), float2(delta, 0.0), float2(0.0, delta) ); float[3] results; for ( int i = 0; i < 3; ++i ) { float2 pos = float2( uvw.position.x + offsets[i].x, uvw.position.y + offsets[i].y); results[i] = wave_height(pos, wave_centers); } if ( (results[2] == results[0]) && (results[1] == results[0]) ) { return normal; } else { return math::normalize( normal + uvw.tangent_v * (results[2] - results[0]) * factor + uvw.tangent_u * (results[1] - results[0]) * factor); } } // A second material used to show the execution of material sub-expressions. export material example_execution2( float3 light_pos = float3(-5, 3, 5)) = let { float time = state::animation_time(); float2[3] wave_centers = float2[3]( float2(0.2 + 0.2 * math::cos(0.3 * time), 0.7 + 0.3 * math::sin(0.4 * time)), float2(0.6, 0.4), float2(0.35, 0.6)); float3 grad = wave_gradient(wave_centers: wave_centers); base::texture_return tex = base::file_texture( texture_2d("./resources/example.png"), uvw: base::texture_coordinate_info( position: state::texture_coordinate(0) + 0.02 * grad )); } in material( surface: material_surface( scattering: df::diffuse_reflection_bsdf( tint: ( color(0.3) * (1 - tex.mono * 0.5) + (1.4 * tex.tint * tex.mono) ) * math::dot(grad, math::normalize(light_pos)) ) ) ); // A third material used to show the execution of material sub-expressions. export material example_execution3() = let { float time = state::animation_time(); float3 pos = state::texture_coordinate(0) + (4 + math::cos(0.005 * time)) * float3(math::sin(0.005 * time), math::cos(0.005 * time), 0); base::texture_return tex = base::file_texture(texture_2d("./resources/example.png")); } in material( surface: material_surface( scattering: df::diffuse_reflection_bsdf( tint: (tex.tint * tex.mono) + (1 - tex.mono * 0.8) * base::flake_noise_texture( uvw: base::texture_coordinate_info(position: pos), scale: 0.1, maximum_size: 1.2, noise_type: 1).tint ) ) ); const float[4] global_arr(0.25, 0.7, 0.4, 1); // Example material using the rodata-segment in HLSL. export material example_execution4() = let { float time = state::animation_time(); float3 pos = state::texture_coordinate(0); } in material( surface: material_surface( scattering: df::diffuse_reflection_bsdf( tint: color(0.5 + math::cos(time * 2 * math::PI / 4) / 2) * global_arr[int(pos.x * 8) & 3] ) ) ); // simple material with textures and light profile export material example_modulemdl_material_examples( color tint = color(1.0), uniform light_profile profile = light_profile("./resources/example_modules.ies") ) = let { base::texture_return tex = base::file_texture(texture_2d("./resources/example.png")); } in material( surface: material_surface( scattering: df::diffuse_reflection_bsdf( tint: tex.tint ), emission: material_emission ( emission: df::measured_edf(profile: profile, global_distribution: true, global_frame: float3x3(1.,0,0, 0,0,1., 0.,1,0) ), intensity: tint ) ) ); // simple measured material export material example_modules2() = material ( surface: material_surface( scattering: df::measured_bsdf( measurement: bsdf_measurement("./resources/example_modules.mbsdf"), multiplier: 1 ) ) ); export struct checker_value { float2 roughness; float weight; }; export enum Options { None, Checker }; export checker_value checker(float2 uv, float roughness, float anisotropy) { checker_value val; bool x = (int(uv.x) & 1) != 0; bool y = (int(uv.y) & 1) != 0; if (x != y) { float iso = (1.0f - anisotropy); val.roughness = x ? float2(roughness * iso, roughness / iso) : float2(roughness / iso, roughness * iso); val.weight = 1.0f; } return val; } // get a checker pattern based on the UV coordinate. // used by the create expression graph python example. export color color_checker( float scale = 1.0f, color a = color(1.0), color b = color(0.0)) { float3 uvw = state::texture_coordinate(0); float2 uv = float2(uvw.x, uvw.y) * scale; bool x = (int(uv.x) & 1) != 0; bool y = (int(uv.y) & 1) != 0; return x == y ? a : b; } // a material combining a diffuse, glossy, and specular export material example_df( float tex_coord_scale = 14.0f, float checker_scale = 1.0f, color glossy_tint = color(0.3f, 0.5f, 1.0f), float glossy_weight = 1.0f [[ anno::hard_range(0.0f, 1.0f) ]], color diffuse_tint = color(1.0f, 0.5f, 0.3f), float diffuse_weight = 0.25f [[ anno::hard_range(0.0f, 1.0f) ]], float clearcoat_ior = 1.5f [[ anno::hard_range(1.0f, 10.0f) ]], float roughness = 0.1f [[ anno::hard_range(0.0f, 1.0f) ]], float anisotropy = 0.5f [[ anno::hard_range(0.0f, 1.0f) ]], Options add_checker = Checker, color emission_intensity = color(0.25f,0.5f,0.75f), uniform float emission_intensity_scale = 0.5f [[ anno::hard_range(0.0f, 10.0f) ]], uniform string emission_usage = "full", uniform texture_2d tex = "./resources/example.png" ) = let { float3 tex_coord3 = state::texture_coordinate(0); float2 tex_coord = float2(tex_coord3.x, tex_coord3.y) * tex_coord_scale; color tex_value = tex::lookup_color(tex, tex_coord); checker_value cval = add_checker != None ? checker(tex_coord * checker_scale, roughness, anisotropy) : checker_value(); color scaled_intensity = emission_usage == "full" ? emission_intensity * emission_intensity_scale : emission_usage == "half" ? 0.5 * emission_intensity * emission_intensity_scale : color(0); } in material( surface: material_surface( scattering: df::fresnel_layer( ior: clearcoat_ior, layer: df::specular_bsdf( handle: "coat" ), base: df::normalized_mix( df::bsdf_component[2]( df::bsdf_component( weight: diffuse_weight, component: df::diffuse_reflection_bsdf( tint: tex_value * diffuse_tint, handle: "base")), df::bsdf_component( weight: glossy_weight * cval.weight, component: df::simple_glossy_bsdf( roughness_u: cval.roughness.x, roughness_v: cval.roughness.y, tint: glossy_tint, handle: "base")) ) ) ), emission: material_emission ( emission: df::diffuse_edf( handle: "glow"), intensity: scaled_intensity ) ) ); export material example_edf( color diffuse_tint = color(0.0f), uniform float exponent = 32.0f [[ anno::hard_range(0.0f, 1024.0f) ]], uniform float spread = math::PI [[ anno::hard_range(0.0f, math::PI) ]], uniform color emission_intensity = color(0.25f,0.5f,0.75f), uniform float emission_intensity_scale = 1.0f [[ anno::hard_range(0.0f, 10.0f) ]], uniform float diffuse_emission_weight = 0.25f [[ anno::hard_range(0.0f, 1.0f) ]], uniform float spot_emission_weight = 0.25f [[ anno::hard_range(0.0f, 1.0f) ]], uniform bool spot_global_distribution = false ) = let { color scaled_intensity = emission_intensity * emission_intensity_scale; } in material( surface: material_surface( scattering: df::diffuse_reflection_bsdf( tint: diffuse_tint ), emission: material_emission ( emission: df::clamped_mix( df::edf_component[3]( df::edf_component( weight: 0.5f, component: edf() ), df::edf_component( weight: diffuse_emission_weight, component: df::diffuse_edf() ), df::edf_component( weight: spot_emission_weight, component: df::spot_edf( exponent: exponent, spread: spread, global_distribution: spot_global_distribution ) ) ) ), intensity: scaled_intensity ) ) ); // A simple texture modulated material. export material example_mod_rough(color tint = color(1.0), float roughness = 0) = let { uniform texture_2d tex = texture_2d("./resources/example_roughness.png", ::tex::gamma_linear); float3 tex_coord = state::texture_coordinate(0); float mod_roughness = roughness * tex::lookup_float3(tex, float2(tex_coord.x, tex_coord.y)).x; bsdf tmp = df::diffuse_reflection_bsdf(tint, mod_roughness); } in material( surface: material_surface(scattering: tmp), backface: material_surface(scattering: tmp) ); export material dxr_sphere_mat( color tint = color(0.3), float roughness_scale = 1.0, float roughness_offset = 0.25 ) = let { uniform texture_2d tex = texture_2d("./resources/example_roughness.png", ::tex::gamma_linear); float3 tex_coord = state::texture_coordinate(0); float mod_roughness = roughness_offset + roughness_scale * tex::lookup_float3(tex, float2(tex_coord.x, tex_coord.y)).x; } in material( surface: material_surface( scattering: df::simple_glossy_bsdf( roughness_u: mod_roughness, tint: tint ) ) ); // simple measured material export material example_measured_bsdf( uniform df::scatter_mode mode = df::scatter_reflect_transmit, uniform bsdf_measurement mbsdf = bsdf_measurement("./resources/example_modules.mbsdf"), uniform float multiplier = 1.0 ) = material ( surface: material_surface( scattering: df::measured_bsdf( measurement: mbsdf, multiplier: multiplier, mode: mode ) ) ); // simple material with a light profile export material example_measured_edf( color tint = color(0.0), uniform light_profile profile = light_profile("./resources/example_modules.ies"), uniform bool global_distribution = false, uniform float multiplier = 1.0 [[anno::hard_range(0.0f, 10.0f)]] ) = material( surface: material_surface( scattering: df::diffuse_reflection_bsdf( tint: tint ), emission: material_emission ( emission: df::measured_edf( profile: profile, global_distribution: global_distribution, multiplier: multiplier / df::light_profile_power(profile) ), intensity: color(1.0) ) ) ); // sample material with some parameters for testing the mdle example export material example_texture_lookup_bsdf( uniform texture_2d tex = texture_2d("./resources/example.png", ::tex::gamma_default), uniform texture_2d tex2 = texture_2d("./resources/example.png", ::tex::gamma_default) ) [[ anno::author("NVIDIA Corporation"), anno::display_name("aaa"), anno::hidden(), anno::description("test material") ]] = let { float3 tex_coord = state::texture_coordinate(0); } in material( surface: material_surface( scattering: df::diffuse_reflection_bsdf( tint: color(tex::lookup_float3(tex, float2(tex_coord.x, tex_coord.y))) * color(tex::lookup_float3(tex2, float2(tex_coord.x, tex_coord.y))) ) ) ); // A function with a single parameter with default. export int fd_1(int param0 = 42) = param0; // A function which has another function as default. export int fd_default_call( int param0 = fd_1()) = param0; // An auto-uniform function. export color fd_auto_uniform() = color(); // An auto-varying function. export color fd_auto_varying() = color(state::normal()); // A animated simple material. export material blinker_material( color base = color(0.1), color light = color(1.0, 0.9, 0.0), bool enabled = true, float speed = 5.0) = let { float sin_curve = math::sin(state::animation_time() * speed); bool shine = enabled && sin_curve > 0.25; } in material( surface: material_surface( scattering: df::diffuse_reflection_bsdf( tint: base ), emission: material_emission( emission: df::diffuse_edf(), intensity: shine ? light : color(0.0) ) ) );
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/data/mdl/test/test_types.mdl
/****************************************************************************** * Copyright 1986, 2017 NVIDIA Corporation. All rights reserved. ******************************************************************************/ /* THE MDL MATERIALS ARE PROVIDED PURSUANT TO AN END USER LICENSE AGREEMENT, WHICH WAS ACCEPTED IN ORDER TO GAIN ACCESS TO THIS FILE. IN PARTICULAR, THE MDL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS */ mdl 1.5; // anno::version_number(0,1,10,0), import df::*; import state::*; import math::*; import base::*; import tex::*; import anno::*; export using base import texture_return; export using base import mono_mode; export using base import color_layer_mode; export enum material_type [[ anno::description("used to annotate materials as hint for grouping in the ui"), anno::hidden() ]] { simple_material [[ anno::description("Simple material") ]], complex_material [[ anno::description("Complex material") ]], combiner_material [[ anno::description("Combiner material") ]], modifier_material [[ anno::description("Material modifier") ]] }; export enum emission_type [[ anno::description("Used in light sources to define the emission mode"), anno::hidden() ]] { lumen_m2 [[ anno::description("lumen/m2") ]], lumen [[ anno::description("lumen") ]], candela [[ anno::description("candela") ]], nit [[ anno::description("nit (candela/m2)") ]] }; export enum cell_type [[ anno::description("used to define the behavior of Worley noise"), anno::hidden() ]] { simple_cells = 0 [[ anno::description("Simple Cells") ]], crystal_cells = 1 [[ anno::description("Crystal cells") ]], bordered_cells = 2 [[ anno::description("Bordered cells") ]] }; export enum cell_base [[ anno::description("used to annotate materials as hint for grouping in the ui"), anno::hidden() ]] { circular_cells = 0 [[ anno::description("Circle base") ]], diamond_cells = 1 [[ anno::description("Diamond base") ]] }; uniform float4x4 rotation_translation_scale( uniform float3 rotation = float3(0.) [[ anno::description("Rotation applied to every UVW coordinate") ]], uniform float3 translation = float3(0.) [[ anno::description("Offset applied to every UVW coordinate") ]], uniform float3 scaling = float3(1.) [[ anno::description("Scale applied to every UVW coordinate") ]] ) [[ anno::description("Construct transformation matrix from Euler rotation, translation and scale"), anno::hidden() ]] { float4x4 scale = float4x4(scaling.x , 0. , 0. , 0., 0. , scaling.y , 0. , 0., 0. , 0. , scaling.z , 0., translation.x, translation.y, translation.z, 1.); float3 s = math::sin(rotation); float3 c = math::cos(rotation); float4x4 rotate = float4x4( c.y*c.z , -c.x*s.z + s.x*s.y*c.z , s.x*s.z + c.x*s.y*c.z , 0.0, c.y*s.z , c.x*c.z + s.x*s.y*s.z , -s.x*c.z + c.x*s.y*s.z , 0.0, -s.y , s.x*c.y , c.x*c.y , 0.0, 0. , 0 , 0 , 1.); return scale*rotate; } export annotation suitable_as_light(); export annotation type_of_material(material_type type); export annotation ui_position(int position); export annotation typical_object_size(float size); const string COPYRIGHT = "THE MDL MATERIALS ARE PROVIDED PURSUANT TO AN END USER LICENSE AGREEMENT, WHICH WAS ACCEPTED IN ORDER TO GAIN ACCESS TO THIS FILE. IN PARTICULAR, THE MDL MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE MDL MATERIALS OR FROM OTHER DEALINGS IN THE MDL MATERIALS"; export texture_return blend_colors( color color_1 = color(0.0) [[ anno::display_name("Color 1") ]], color color_2 = color(1.0) [[ anno::display_name("Color 2") ]], uniform color_layer_mode mode = color_layer_blend [[ anno::description("Describes how Color 1 and Color 2 are combined"), anno::display_name("Blend mode") ]], float weight = 1. [[ anno::description("Defines strength of the effect. At weight of 0, only color 1 will be visible. At weight 1, the blend function will have full effect"), anno::display_name("Blend weight") ]] ) [[ anno::display_name("Blend colors"), anno::description("Allows combining textures in varied ways"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::blend_color_layers( layers: base::color_layer[]( base::color_layer( layer_color: color_2, weight: weight, mode: mode )), base: color_1 ); } export texture_return file_texture( uniform texture_2d texture [[ anno::display_name("Bitmap file"), anno::in_group("Bitmap parameters"), ui_position(0) ]], uniform mono_mode mono_source = mono_average [[ anno::display_name("Scalar mode"), anno::description("Defines how the texture applies to scalar parameters"), anno::in_group("Bitmap parameters"), ui_position(1) ]], uniform float brightness = 1. [[ anno::display_name("Brightness"), anno::in_group("Bitmap parameters"), ui_position(2) ]], uniform float contrast = 1. [[ anno::display_name("Contrast"), anno::in_group("Bitmap parameters"), ui_position(3) ]], uniform float2 scaling = float2(1.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(8) ]], uniform float2 translation = float2(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(7) ]], uniform float rotation = 0. [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(6) ]], uniform bool clip = false [[ anno::description("If set to true, texture will not repeat. Outside of the texture, color will be black and the scalar value will be 0"), anno::display_name("Clip"), anno::in_group("Placement"), ui_position(9) ]], uniform int texture_space = 0 [[ anno::description("Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(5) ]], uniform bool invert = false [[ anno::description("Invert image"), anno::display_name("Invert image"), anno::in_group("Bitmap parameters"), ui_position(4) ]] ) [[ anno::display_name("Bitmap texture"), anno::description("Allows texturing using image files of various file formats"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return invert == false? base::file_texture( texture: texture, mono_source: mono_source, color_offset: color(0.5*brightness-0.5*contrast*brightness), color_scale: color(brightness*contrast), uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: float3(scaling.x, scaling.y, 1.0), rotation: float3(0.0, 0.0, rotation/180.*math::PI ), translation: float3(translation.x, translation.y, 0.0) ), coordinate: base::coordinate_source(texture_space: texture_space) ), wrap_u: clip?tex::wrap_clip:tex::wrap_repeat, wrap_v: clip?tex::wrap_clip:tex::wrap_repeat ): base::file_texture( texture: texture, mono_source: mono_source, color_offset: color(1.0-0.5*brightness+0.5*contrast*brightness), color_scale: color(-brightness*contrast), uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: float3(scaling.x, scaling.y, 1.0), rotation: float3(0.0, 0.0, rotation/180.*math::PI ), translation: float3(translation.x, translation.y, 0.0) ), coordinate: base::coordinate_source(texture_space: texture_space) ), wrap_u: clip?tex::wrap_clip:tex::wrap_repeat, wrap_v: clip?tex::wrap_clip:tex::wrap_repeat ); } export texture_return perlin_noise_texture( color color1 = color(1.) [[ anno::display_name("Color 1"), anno::in_group("Noise parameters"), ui_position(1) ]], color color2 = color(0.) [[ anno::display_name("Color 2"), anno::in_group("Noise parameters"), ui_position(2) ]], uniform bool object_space = true [[ anno::description("If off, UV space will be used. If on, 3d texturing in object space will apply. For applications that do not support object space, world space will be used"), anno::display_name("Use object space"), anno::in_group("Placement"), ui_position(7) ]], uniform int noise_levels = 3. [[ anno::description("Higher amounts will add detail to the noise"), anno::display_name("Levels"), anno::hard_range(1,6), anno::in_group("Noise parameters"), ui_position(3) ]], uniform bool absolute_noise = false [[ anno::display_name("Billowing appearance"), anno::in_group("Noise parameters"), ui_position(4) ]], uniform float noise_threshold_high = 1. [[ anno::hard_range(0.0,1.), anno::description("Lowering this value will create bigger areas uniformly colored with Color 1"), anno::display_name("Upper threshold"), anno::in_group("Noise parameters"), ui_position(6) ]], uniform float noise_threshold_low = 0. [[ anno::hard_range(0.0,1.), anno::description("Increasing this value will create bigger areas uniformly colored with Color 2"), anno::display_name("Lower threshold"), anno::in_group("Noise parameters"), ui_position(5) ]], uniform float3 scaling = float3(10.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(11) ]], uniform float3 translation = float3(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(10) ]], uniform float3 rotation = float3(0.) [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(9) ]], uniform int texture_space = 0 [[ anno::description("Only applies if \"Use object space\" is off. Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(8) ]] ) [[ anno::display_name("Perlin noise texture"), anno::description("Allow texturing with a random noise pattern"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::perlin_noise_texture( color1: color1, color2: color2, noise_levels: noise_levels, absolute_noise: absolute_noise, noise_threshold_high: noise_threshold_high, noise_threshold_low: noise_threshold_low, uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: object_space?scaling*state::meters_per_scene_unit() :scaling, translation: translation, rotation: float3(rotation.x/180.*math::PI,rotation.y/180.*math::PI,rotation.z/180.*math::PI) ), coordinate: object_space? base::coordinate_source(coordinate_system: base::texture_coordinate_object): base::coordinate_source(texture_space: texture_space) ) ); } export float3 perlin_noise_bump_texture( uniform float factor = 1. [[ anno::display_name("Bump strength"), anno::in_group("Noise parameters"), ui_position(0) ]], uniform float3 scaling = float3(10.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(9) ]], uniform int noise_levels = 1. [[ anno::description("Higher amounts will add detail to the noise"), anno::display_name("Levels"), anno::hard_range(1,6), anno::in_group("Noise parameters"), ui_position(1) ]], uniform bool object_space = true [[ anno::description("If off, UV space will be used. If on, 3d texturing in object space will apply. For applications that do not support object space, world space will be used"), anno::display_name("Use object space"), anno::in_group("Placement"), ui_position(5) ]], uniform bool absolute_noise = false [[ anno::display_name("Billowing appearance"), anno::in_group("Noise parameters"), ui_position(2) ]], uniform float noise_threshold_high = 1. [[ anno::hard_range(0.0,1.), anno::description("Lowering this value will create bigger areas uniformly colored with Color 1"), anno::display_name("Upper threshold"), anno::in_group("Noise parameters"), ui_position(4) ]], uniform float noise_threshold_low = 0. [[ anno::hard_range(0.0,1.), anno::description("Increasing this value will create bigger areas uniformly colored with Color 2"), anno::display_name("Lower threshold"), anno::in_group("Noise parameters"), ui_position(3) ]], uniform float3 translation = float3(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(8) ]], uniform float3 rotation = float3(0.) [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(7) ]], uniform int texture_space = 0 [[ anno::description("Only applies if \"Use object space\" is off. Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(6) ]] ) [[ anno::display_name("Perlin noise texture"), anno::description("Allows texturing a random noise pattern"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::perlin_noise_bump_texture( factor: factor, noise_levels: noise_levels, absolute_noise: absolute_noise, noise_threshold_high: noise_threshold_high, noise_threshold_low: noise_threshold_low, uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: scaling, translation: translation, rotation: float3(rotation.x/180.*math::PI,rotation.y/180.*math::PI,rotation.z/180.*math::PI) ), coordinate: object_space? base::coordinate_source(coordinate_system: base::texture_coordinate_object): base::coordinate_source(texture_space: texture_space) ) ); } export texture_return worley_noise_texture( color color1 = color(1.) [[ anno::display_name("Color 1"), anno::in_group("Noise parameters"), ui_position(0) ]], color color2 = color(0.) [[ anno::display_name("Color 2"), anno::in_group("Noise parameters"), ui_position(1) ]], uniform bool object_space = true [[ anno::description("If off, UV space will be used. If on, 3d texturing in object space will apply. For applications that do not support object space, world space will be used"), anno::display_name("Use object space") , anno::in_group("Placement"), ui_position(6) ]], uniform int texture_space = 0 [[ anno::description("Only applies if \"Use object space\" is off. Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(7) ]], uniform cell_type mode = simple_cells [[ anno::display_name("Cell type") , anno::description("Cell pattern type"), anno::in_group("Noise parameters"), ui_position(2) ]], uniform cell_base metric = circular_cells [[ anno::display_name("Cell shape") , anno::description("The shape of the cell form"), anno::in_group("Noise parameters"), ui_position(3) ]], uniform float noise_threshold_high = 1. [[ anno::hard_range(0.0,1.), anno::description("Lowering this value will create bigger areas uniformly colored with Color 1"), anno::display_name("Upper threshold"), anno::in_group("Noise parameters"), ui_position(5) ]], uniform float noise_threshold_low = 0. [[ anno::hard_range(0.0,1.), anno::description("Increasing this value will create bigger areas uniformly colored with Color 2"), anno::display_name("Lower threshold"), anno::in_group("Noise parameters"), ui_position(4) ]], uniform float3 scaling = float3(10.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(10) ]], uniform float3 translation = float3(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(9) ]], uniform float3 rotation = float3(0.) [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(8) ]]) [[ anno::display_name("Cellular noise texture"), anno::description("Allow texturing with a cell forming pattern"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::worley_noise_texture( color1: color1, color2: color2, mode: mode==crystal_cells?2:mode==bordered_cells?3:0, metric: metric, noise_threshold_high: noise_threshold_high, noise_threshold_low: noise_threshold_low, uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: object_space?scaling*state::meters_per_scene_unit() :scaling, translation: translation, rotation: float3(rotation.x/180.*math::PI,rotation.y/180.*math::PI,rotation.z/180.*math::PI) ), coordinate: object_space? base::coordinate_source(coordinate_system: base::texture_coordinate_object): base::coordinate_source(texture_space: texture_space) ) ); } export float3 worley_noise_bump_texture( uniform float factor = 1. [[ anno::display_name("Bump strength"), anno::in_group("Noise parameters"), ui_position(0) ]], uniform cell_base metric = circular_cells [[ anno::display_name("Cell shape") , anno::description("The shape of the cell form"), anno::in_group("Noise parameters"), ui_position(1) ]], uniform bool object_space = true [[ anno::description("If off, UV space will be used. If on, 3d texturing in object space will apply. For applications that do not support object space, world space will be used"), anno::display_name("Use object space"), anno::in_group("Placement"), ui_position(4) ]], uniform int texture_space = 0 [[ anno::description("Only applies if \"Use object space\" is off. Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(5) ]], uniform float noise_threshold_high = 1. [[ anno::hard_range(0.0,1.), anno::description("Lowering this value will create bigger areas uniformly colored with Color 1"), anno::display_name("Upper threshold"), anno::in_group("Noise parameters"), ui_position(3) ]], uniform float noise_threshold_low = 0. [[ anno::hard_range(0.0,1.), anno::description("Increasing this value will create bigger areas uniformly colored with Color 2"), anno::display_name("Lower threshold"), anno::in_group("Noise parameters"), ui_position(2) ]], uniform float3 scaling = float3(10.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(8) ]], uniform float3 translation = float3(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(7) ]], uniform float3 rotation = float3(0.) [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(6) ]]) [[ anno::display_name("Cellular noise texture"), anno::description("Allow texturing with a cell forming pattern"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::worley_noise_bump_texture( factor: factor, metric: metric, noise_threshold_high: noise_threshold_high, noise_threshold_low: noise_threshold_low, uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: object_space?scaling*state::meters_per_scene_unit() :scaling, translation: translation, rotation: float3(rotation.x/180.*math::PI,rotation.y/180.*math::PI,rotation.z/180.*math::PI) ), coordinate: object_space? base::coordinate_source(coordinate_system: base::texture_coordinate_object): base::coordinate_source(texture_space: texture_space) ) ); } export texture_return flow_noise_texture( color color1 = color(1.) [[ anno::display_name("Color 1"), anno::in_group("Noise parameters"), ui_position(0) ]], color color2 = color(0.) [[ anno::display_name("Color 2"), anno::in_group("Noise parameters"), ui_position(1) ]], uniform bool object_space = false [[ anno::description("If off, UV space will be used. If on, 3d texturing in object space will apply. For applications that do not support object space, world space will be used"), anno::display_name("Use object space"), anno::in_group("Placement"), ui_position(10) ]], uniform int texture_space = 0 [[ anno::description("Only applies if \"Use object space\" is off. Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(11) ]], uniform int noise_levels = 3. [[ anno::description("Higher amounts will add detail to the noise"), anno::display_name("Levels"), anno::hard_range(1,6), anno::in_group("Noise parameters"), ui_position(3) ]], uniform bool absolute_noise = false [[ anno::display_name("Billowing appearance"), anno::in_group("Noise parameters"), ui_position(4) ]], uniform float phase = 0.0 [[ anno::display_name("Phase offset"), anno::description("Controls the 3rd dimension of the function"), anno::in_group("Noise parameters") , ui_position(5) ]], uniform float level_gain = 0.5 [[ anno::display_name("Level intensity gain"), anno::description("If multiple levels are used, \"level_gain\" specifies a weighting factor for subsequent levels"), anno::in_group("Noise parameters"), ui_position(6) ]], uniform float level_scale = 2.0 [[ anno::display_name("Level scaling"), anno::description("If multiple levels are used, \"level_scale\" specifies a global scaling factor for subsequent levels"), anno::in_group("Noise parameters"), ui_position(7) ]], uniform float level_progressive_u_scale = 1. [[ anno::display_name("Progressive u scale"), anno::description("If multiple levels are used, \"level_progressive_u_scale\" specifies an additional scaling factor in the \"u\" direction"), anno::in_group("Noise parameters"), ui_position(8) ]], uniform float level_progressive_v_motion = 0. [[ anno::display_name("Progressive v offset"), anno::description("If multiple levels are used, \"level_progressive_v_motion\" specifies an offset for subsequent levels in the \"v\" direction"), anno::in_group("Noise parameters"), ui_position(9) ]], uniform float3 scaling = float3(10.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(15) ]], uniform float3 translation = float3(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(14) ]], uniform float3 rotation = float3(0.) [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(13) ]]) [[ anno::display_name("Flow noise texture"), anno::description("Allow texturing with a 2D noise pattern suitable for waves"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::flow_noise_texture( color1: color1, color2: color2, levels: noise_levels, phase: phase, level_gain: level_gain, level_scale: level_scale, level_progressive_u_scale: level_progressive_u_scale, level_progressive_v_motion: level_progressive_v_motion, absolute_noise: absolute_noise, uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: object_space?scaling*state::meters_per_scene_unit() :scaling, translation: translation, rotation: float3(rotation.x/180.*math::PI,rotation.y/180.*math::PI,rotation.z/180.*math::PI) ), coordinate: object_space? base::coordinate_source(coordinate_system: base::texture_coordinate_object): base::coordinate_source(texture_space: texture_space) ) ); } export float3 flow_noise_bump_texture( uniform float factor = 1. [[ anno::display_name("Bump strength"), anno::in_group("Noise parameters"), ui_position(0) ]], uniform float3 scaling = float3(10.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(12) ]], uniform int noise_levels = 1. [[ anno::description("Higher amounts will add detail to the noise"), anno::display_name("Levels"), anno::hard_range(1,6), anno::in_group("Noise parameters"), ui_position(1) ]], uniform bool object_space = false [[ anno::description("If off, UV space will be used. If on, 3d texturing in object space will apply. For applications that do not support object space, world space will be used"), anno::display_name("Use object space"), anno::in_group("Placement"), ui_position(8) ]], uniform int texture_space = 0 [[ anno::description("Only applies if \"Use object space\" is off. Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(9) ]], uniform bool absolute_noise = false [[ anno::display_name("Billowing appearance"), anno::in_group("Noise parameters"), ui_position(2) ]], uniform float phase = 0.0 [[ anno::display_name("Phase offset"), anno::description("Controls the 3rd dimension of the function"), anno::in_group("Noise parameters"), ui_position(3) ]], uniform float level_gain = 0.5 [[ anno::display_name("Level intensity gain"), anno::description("If multiple levels are used, \"level_gain\" specifies a weighting factor for subsequent levels"), anno::in_group("Noise parameters"), ui_position(4) ]], uniform float level_scale = 2.0 [[ anno::display_name("Level scaling"), anno::description("If multiple levels are used, \"level_scale\" specifies a global scaling factor for subsequent levels"), anno::in_group("Noise parameters"), ui_position(5) ]], uniform float level_progressive_u_scale = 1. [[ anno::display_name("Progressive u scale"), anno::description("If multiple levels are used, \"level_progressive_u_scale\" specifies an additional scaling factor in the \"u\" direction"), anno::in_group("Noise parameters"), ui_position(6) ]], uniform float level_progressive_v_motion = 0. [[ anno::display_name("Progressive v offset"), anno::description("If multiple levels are used, \"level_progressive_v_motion\" specifies an offset for subsequent levels in the \"v\" direction"), anno::in_group("Noise parameters"), ui_position(7) ]], uniform float3 translation = float3(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(11) ]], uniform float3 rotation = float3(0.) [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(10) ]]) [[ anno::display_name("Flow noise texture"), anno::description("Allow texturing with a 2D noise pattern suitable for waves"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::flow_noise_bump_texture( factor: factor, levels: noise_levels, phase: phase, level_gain: level_gain, level_scale: level_scale, level_progressive_u_scale: level_progressive_u_scale, level_progressive_v_motion: level_progressive_v_motion, absolute_noise: absolute_noise, uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: object_space?scaling*state::meters_per_scene_unit() :scaling, translation: translation, rotation: float3(rotation.x/180.*math::PI,rotation.y/180.*math::PI,rotation.z/180.*math::PI) ), coordinate: object_space? base::coordinate_source(coordinate_system: base::texture_coordinate_object): base::coordinate_source(texture_space: texture_space) ) ); } export texture_return checker_texture( color color1 = color(1.) [[ anno::display_name("Color 1"), anno::in_group("Checker parameters"), ui_position(0) ]], color color2 = color(0.) [[ anno::display_name("Color 2"), anno::in_group("Checker parameters"), ui_position(1) ]], uniform float3 scaling = float3(10.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(7) ]], uniform float3 translation = float3(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(6) ]], uniform bool object_space = false [[ anno::description("If off, UV space will be used. If on, 3d texturing in object space will apply. For applications that do not support object space, world space will be used"), anno::display_name("Use object space"), anno::in_group("Placement"), ui_position(3) ]], uniform float blur = 0 [[ anno::hard_range(0.0,1.0), anno::display_name("Blur"), anno::in_group("Checker parameters"), ui_position(2) ]], uniform float3 rotation = float3(0.) [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(5) ]], uniform int texture_space = 0 [[ anno::description("Only applies if \"Use object space\" is off. Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(4) ]] ) [[ anno::display_name("3d checker texture"), anno::description("Allows texturing a checkerboard pattern"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::checker_texture( color1: color1, color2: color2, blur: blur/4., uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: object_space?scaling*state::meters_per_scene_unit() :scaling, translation: translation, rotation: float3(rotation.x/180.*math::PI,rotation.y/180.*math::PI,rotation.z/180.*math::PI) ), coordinate: object_space? base::coordinate_source(coordinate_system: base::texture_coordinate_object): base::coordinate_source(texture_space: texture_space) ) ); } export float3 checker_bump_texture( uniform float factor = 1. [[ anno::display_name("Bump strength"), anno::in_group("Checker parameters"), ui_position(0) ]], uniform float blur = 0 [[ anno::hard_range(0.0,1.0), anno::display_name("Blur"), anno::in_group("Checker parameters"), ui_position(1) ]], uniform bool object_space = false [[ anno::description("If off, UV space will be used. If on, 3d texturing in object space will apply. For applications that do not support object space, world space will be used"), anno::display_name("Use object space"), anno::in_group("Placement"), ui_position(2) ]], uniform float3 scaling = float3(10.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(6) ]], uniform float3 translation = float3(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(5) ]], uniform float3 rotation = float3(0.) [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(4) ]], uniform int texture_space = 0 [[ anno::description("Only applies if \"Use object space\" is off. Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(3) ]] ) [[ anno::display_name("3d checker texture"), anno::description("Allows texturing a checkerboard pattern"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::checker_bump_texture( factor: factor, blur: blur/4., uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: object_space?scaling*state::meters_per_scene_unit() :scaling, translation: translation, rotation: float3(rotation.x/180.*math::PI,rotation.y/180.*math::PI,rotation.z/180.*math::PI) ), coordinate: object_space? base::coordinate_source(coordinate_system: base::texture_coordinate_object): base::coordinate_source(texture_space: texture_space) ) ); } export float3 file_bump_texture( uniform texture_2d texture [[ anno::display_name("Bitmap file"), anno::in_group("Bitmap parameters"), ui_position(1) ]], uniform mono_mode bump_source = mono_average [[ anno::display_name("Bump mode"), anno::description("Defines how the texture is evaluated to create the bumps"), anno::in_group("Bitmap parameters"), ui_position(2) ]], uniform float2 scaling = float2(1.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(8) ]], uniform float2 translation = float2(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(7) ]], uniform float rotation = 0. [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(6) ]], uniform bool clip = false [[ anno::description("If set to true, texture will not repeat. Outside of the texture the surface will be flat"), anno::display_name("Clip"), anno::in_group("Placement"), ui_position(5) ]], uniform float factor = 1 [[ anno::display_name("Bump strength"), anno::in_group("Bitmap parameters"), ui_position(3) ]], uniform int texture_space = 0 [[ anno::description("Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(4) ]] ) [[ anno::display_name("Bitmap texture"), anno::description("Allows texturing using image files of various file formats"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::file_bump_texture( texture: texture, bump_source: bump_source, factor: factor, uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: float3(scaling.x, scaling.y, 1.0), rotation: float3(0.0, 0.0, rotation/180.*math::PI ), translation: float3(translation.x, translation.y, 0.0) ), coordinate: base::coordinate_source(texture_space: texture_space) ), wrap_u: clip?tex::wrap_clamp:tex::wrap_repeat, wrap_v: clip?tex::wrap_clamp:tex::wrap_repeat, clip: clip ); } export float3 normalmap_texture( uniform texture_2d texture [[ anno::display_name("Normalmap file"), anno::in_group("Normalmap parameters"), ui_position(1) ]], uniform float2 scaling = float2(1.) [[ anno::description("Controls the scale of the texture on the object"), anno::display_name("Tiling"), anno::in_group("Placement"), ui_position(7) ]], uniform float2 translation = float2(0.) [[ anno::description("Controls position of the texture on the object"), anno::display_name("Offset"), anno::in_group("Placement"), ui_position(6) ]], uniform float rotation = 0. [[ anno::description("Rotation angle of the texture in degrees"), anno::display_name("Rotation"), anno::in_group("Placement"), ui_position(5) ]], uniform bool clip = false [[ anno::description("If set to true, texture will not repeat. Outside of the texture the surface will be flat"), anno::display_name("Clip"), anno::in_group("Placement"), ui_position(4) ]], uniform float factor = 1 [[ anno::display_name("Strength"), anno::in_group("Normalmap parameters"), ui_position(2) ]], uniform int texture_space = 0 [[ anno::description("Selects a specific UV space"), anno::display_name("UV space index"), anno::hard_range(0,3), anno::in_group("Placement"), ui_position(3) ]] ) [[ anno::display_name("Normalmap texture"), anno::description("Allows the use of tangent space normal maps"), anno::author("NVIDIA Corporation"), anno::version_number(0,1,9,0), anno::copyright_notice(COPYRIGHT) ]] { return base::tangent_space_normal_texture( texture: texture, factor: factor, uvw: base::transform_coordinate( transform: rotation_translation_scale( scaling: float3(scaling.x, scaling.y, 1.0), rotation: float3(0.0, 0.0, rotation/180.*math::PI ), translation: float3(translation.x, translation.y, 0.0) ), coordinate: base::coordinate_source(texture_space: texture_space) ), wrap_u: clip?tex::wrap_clamp:tex::wrap_repeat, wrap_v: clip?tex::wrap_clamp:tex::wrap_repeat, clip: clip ); } export float dummy_float_function() {return 3.14;} // A simple struct. export struct example_struct { int param_int; float param_float = 0.0; }; // A complex struct which references another struct. export struct complex_struct { int param_int; example_struct param_struct; }; //material section export material testMaterial( bool test_bool, int test_int = 2 ) = material( thin_walled: true, surface: material_surface( scattering: df::weighted_layer( weight: 1., layer: df::diffuse_reflection_bsdf( roughness: 1, tint: color(.8) ) ) ) ); export material materialWithEnum( uniform color_layer_mode mode = color_layer_blend ) = material(); // A simple struct. export struct simple_struct { int paramInt; float paramFloat = 0.0; }; export material materialWithStructure( simple_struct structInput = simple_struct(1, 2.0), uniform texture_2d test_texture = texture_2d("./dummy.jpg", ::tex::gamma_default) ) = material(); export material simpleMaterial( int param_int = 1, float param_float = 2.0 ) = material(); export material materialWithMaterialInput( material materialInput = simpleMaterial() ) = material(); export material diffuse( // Test simple types bool test_bool = true, int test_int = true, material_type test_enum = complex_material, float roughness = 0.0 [[ anno::display_name("Diffuse roughness"), anno::hard_range(0.0,1.), anno::description("Higher roughness values lead a powdery appearance") ]], double test_double = 3.14, string test_string = "Test string", color diffuse_color = color(.8) [[ anno::display_name("Color"), anno::description("The color of the material") ]], uniform texture_2d test_texture = texture_2d("./dummy.jpg", ::tex::gamma_default), // Test vectors // MDL provides two, three, and four component vector types with either float, double, int, or bool // component types. Vectors are named by taking the component type name and appending the dimension // of the vector, which can be 2, 3, or 4. bool2 test_bool2 = bool2(true,false), bool3 test_bool3 = bool3(true), bool4 test_bool4 = bool4(true), int2 test_int2 = int2(1,2), int3 test_int3 = int3(3), int4 test_int4 = int4(4), float2 test_float2 = float2(1.0,2.0), float3 test_float3 = float3(3.0), float4 test_float4 = float4(4.0), double2 test_double2 = double2(1.0,2.0), double3 test_double3 = double3(3.0), double4 test_double4 = double4(4.0), // Test matrices // built-in matrix types are: float2x2, float2x3, float3x2, float3x3, float3x4, float4x2, // float2x4, float4x3, float4x4, double2x2, double2x3, double3x2, double3x3, double3x4, double4x2, // double2x4, double4x3, and double4x4. float2x2 test_float2x2 = float2x2(1,2,3,4), float3x3 test_float3x3 = float3x3(1), float4x4 test_float4x4 = float4x4(2), float3x2 test_float3x2 = float3x2(1), // Error, not supported double2x2 test_double2x2 = double2x2(2), double3x3 test_double3x3 = double3x3(2), double4x4 test_double4x4 = double4x4(2), // Test arrays of simple types bool[4] bool_array = bool[](true,false,true,false), int[4] int_array = int[](1,2,3,4), float[4] float_array = float[](1.0,2.0,3.0,4.0), double[4] double_array = double[](1.0,2.0,3.0,4.0), string[4] string_array = string[]("1.0","2.0","3.0","4.0"), color[4] color_array = color[](color(.8),color(.8),color(.8),color(.8)), // Test arrays of vectors bool2[2] bool2_array_of_vectors = bool2[](bool2(true,false),bool2(false,true)), bool3[2] bool3_array_of_vectors = bool3[](bool3(true,false, false),bool3(false,true,true)), bool4[2] bool4_array_of_vectors = bool4[](bool4(true,false, false, false),bool4(false,true,true,true)), int2[2] int2_array_of_vectors = int2[](int2(1,2),int2(3,4)), int3[2] int3_array_of_vectors = int3[](int3(1,2,3),int3(4,5,6)), int4[2] int4_array_of_vectors = int4[](int4(1,2,3,4),int4(5,6,7,8)), float2[3] float2_array_of_vectors = float2[](float2(1.0,2.0),float2(3.0,4.0),float2(5.0,6.0)), float3[3] float3_array_of_vectors = float3[](float3(1.0,2.0,2.5),float3(3.0,4.0,4.5),float3(5.0,6.0,6.5)), float4[3] float4_array_of_vectors = float4[](float4(1.0,2.0,2.5,2.6),float4(3.0,4.0,4.5,4.6),float4(5.0,6.0,6.5,6.6)), double2[2] double2_array_of_vectors = double2[](double2(5,6),double2(7,8)), double3[2] double3_array_of_vectors = double3[](double3(5,6,7),double3(7,8,9)), double4[2] double4_array_of_vectors = double4[](double4(5,6,7,8),double4(7,8,9,10)), // Test function call texture_return file_tex = file_texture(texture: texture_2d("./dummy.jpg")), // float3 perlin_parm = perlin_noise_bump_texture(dummy_float_function()), // CRASH - WHY? // Test structure example_struct test_struct = example_struct(1,1.0), // complex_struct test_struct2 = complex_struct(), // example_struct test_struct = example_struct(), float3 normal = state::normal() [[ anno::display_name("Bumps"), anno::description("Attach bump or normal maps here") ]] ) [[ anno::display_name("Simple diffuse"), anno::description("A basic diffuse material"), anno::author("NVIDIA Corporation"), anno::copyright_notice(COPYRIGHT), anno::version_number(0,1,9,0), type_of_material(simple_material), typical_object_size(1.0), anno::key_words(string[]("generic")) ]] = material( thin_walled: true, surface: material_surface( scattering: df::weighted_layer( weight: 1., normal: normal, layer: df::diffuse_reflection_bsdf( roughness: roughness, tint: diffuse_color ) ) ) ); export material materialWithTextureInput( base::texture_return textureInput = base::file_texture( texture : texture_2d("dummy.jpg") ) ) = material(surface: material_surface ( scattering : df::diffuse_reflection_bsdf ( tint: textureInput.tint ) ) ); export material materialWithAnnotations( int int_parm = 0.0 [[ anno::hard_range(-3,4), anno::soft_range(-3,4) ]], uniform int2 int2_parm = int2(0,1) [[ anno::hard_range(int2(0),int2(1)), anno::soft_range(int2(0),int2(1)) ]], uniform int3 int3_parm = int3(0,1,2) [[ anno::hard_range(int3(0),int3(3)), anno::soft_range(int3(0),int3(3)) ]], uniform int4 int4_parm = int4(0,1,2,3) [[ anno::hard_range(int4(0),int4(3)), anno::soft_range(int4(0),int4(3)) ]], float float_parm = 0.0 [[ anno::display_name("float_parm display name"), anno::in_group("float_parm group", "float_parm Subgroup", "float_parm Subsubgroup"), anno::hard_range(-10,20), anno::soft_range(-3,10), anno::description("Description for the float_parm values"), anno::key_words(string[]("generic","dielectric","plastic","wood","stone")), anno::hidden(), anno::unused(), anno::author("Author"), anno::contributor("Contributor"), anno::copyright_notice("Copyright notice"), anno::created(2019, 12, 6, "created string notes"), anno::modified(2019, 12, 6, "modified string notes"), anno::deprecated("Deprecated string"), anno::origin("string name"), anno::ui_order(1), anno::usage("string hint"), anno::version(6,0,1,"Prerelease notes"), anno::enable_if("1==1"), anno::dependency("string modulename",1,2,3,"string prerelease") ]], uniform float2 float2_parm = float2(78,79) [[ anno::in_group("float2_parm group", "float2_parm Subgroup"), anno::hard_range(float2(-10,-11),float2(100,101)), anno::soft_range(float2(-10,-11),float2(100,101)) ]], uniform float3 float3_parm = float3(0,1,2) [[ anno::in_group("float3_parm group"), anno::hard_range(float3(0),float3(3)), anno::soft_range(float3(0),float3(3)) ]], uniform float4 float4_parm = float4(0,1,2,3) [[ anno::hard_range(float4(0),float4(3)), anno::soft_range(float4(0),float4(3)) ]], uniform double double_parm = double(3.14) [[ anno::hard_range(0,10), anno::soft_range(0,10) ]], uniform double2 double2_parm = double2(78,79) [[ anno::hard_range(double2(-10,-11),double2(100,101)), anno::soft_range(double2(-10,-11),double2(100,101)) ]], uniform double3 double3_parm = double3(0,1,2) [[ anno::hard_range(double3(0),double3(3)), anno::soft_range(double3(0),double3(3)) ]], uniform double4 double4_parm = double4(0,1,2,3) [[ anno::hard_range(double4(0),double4(3)), anno::soft_range(double4(0),double4(3)) ]], color color_parm = color(0.4) [[ anno::soft_range(color(0.01), color(.9)), anno::hard_range(color(0.01), color(.9)), anno::deprecated(), anno::unused("Unused string") ]] ) [[ anno::thumbnail("dummy.jpg"), anno::display_name("Material display name"), anno::description("A basic material"), anno::author("NVIDIA Corporation"), anno::copyright_notice(COPYRIGHT), anno::version(6,0,1,"Prerelease notes"), type_of_material(simple_material), typical_object_size(1.0), anno::key_words(string[]("generic")) ]] = material(surface: material_surface ( scattering : df::diffuse_reflection_bsdf ( ) ) ); // User defined annotations export annotation test_annotation_standard(bool p1 = bool(true), int p2 = int(1), float p3 = float(1), double p4 = double(1)); export annotation test_annotation_standard2(bool2 p1 = bool2(true), int2 p2 = int2(1), float2 p3 = float2(1), double2 p4 = double2(1)); export annotation test_annotation_standard3(bool3 p1 = bool3(true), int3 p2 = int3(1), float3 p3 = float3(1), double3 p4 = double3(1)); export annotation test_annotation_standard4(bool4 p1 = bool4(true), int4 p2 = int4(1), float4 p3 = float4(1), double4 p4 = double4(1)); export annotation test_annotation_color(color col); export annotation test_annotation_string(string s = string("test string")); // float2x2jfloat2x3jfloat2x4jfloat3x2jfloat3x3jfloat3x4jfloat4x2jfloat4x3jfloat4x4 export annotation test_annotation_matrix(float2x2 p1 = float2x2(1), float2x3 p2 = float2x3(2), float2x4 p3 = float2x4(3), float3x2 p5 = float3x2(5), float3x3 p6 = float3x3(1,2,3,4,5,6,7,8,9), float3x4 p7 = float3x4(7), float4x2 p8 = float4x2(8), float4x3 p9 = float4x3(9), float4x4 p10 = float4x4(10)); // Forbidden // export annotation test_annotation_other(bsdf b = bsdf()); // export annotation test_annotation_other(edf b = edf()); // export annotation test_annotation_other(light_profile b = light_profile()); // export annotation test_annotation_other(bsdf_measurement b = bsdf_measurement()); // export annotation test_annotation_other(texture_2d b = texture_2d()); export material simpleMaterialWithUserDefinedAnnotations( uniform double3 double3_parm = double3(0,1,2) [[ test_annotation_matrix(), test_annotation_string(), test_annotation_color(color(.1)), test_annotation_standard(), test_annotation_standard2(), test_annotation_standard3(), test_annotation_standard4(), anno::hard_range(double3(0),double3(3)), anno::soft_range(double3(0),double3(3)) ]] ) [[ type_of_material(simple_material), typical_object_size(1.0) ]] = material(surface: material_surface ( scattering : df::diffuse_reflection_bsdf ( ) ) ); export material materialWithVectorParm( int int_parm = 0.0, uniform int2 int2_parm = int2(0,1), bool2 test_bool2 = bool2(true,false), bool3 test_bool3 = bool3(true), bool4 test_bool4 = bool4(true) ) = material(surface: material_surface ( scattering : df::diffuse_reflection_bsdf ( ) ) ); export annotation test_annotation_empty_expression(); export material materialWithAnnotationWithoutExpressions( int int_parm = 0.0 [[ anno::unused(), anno::deprecated(), anno::hidden(), test_annotation_empty_expression() ]] ) [[ anno::unused(), anno::noinline(), // for material and functions only anno::deprecated(), anno::hidden(), test_annotation_empty_expression() ]] = material(surface: material_surface ( scattering : df::diffuse_reflection_bsdf ( ) ) ); export material material_MDL_420( // float3x2 is an array of size 3, each element is a float2 float3x2 test_float3x2 = float3x2( 1, 2, 3, 4, 5, 6 ) [[anno::display_name("test_float3x2")]] , float3x4 test_float3x4 = float3x4( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ) , float2x3 test_float2x3 = float2x3(1) , float2x4 test_float2x4 = float2x4(1) , float4x2 test_float4x2 = float4x2(1) , float4x3 test_float4x3 = float4x3(1) , float3x3 test_float3x3 = float3x3( 1, 2, 3, 4, 5, 6, 7, 8, 9 ) , float2[3] float2_array_of_vectors = float2[](float2(1.0,2.0),float2(3.0,4.0),float2(5.0,6.0)) , double2x3 test_double2x3 = double2x3( 1, 2, 3, 4, 5, 6 ) , double2x4 test_double2x4 = double2x4(1) , double3x2 test_double3x2 = double3x2(1) , double3x4 test_double3x4 = double3x4(1) , double4x2 test_double4x2 = double4x2(1) , double4x3 test_double4x3 = double4x3(1) ) = material(surface: material_surface ( scattering : df::diffuse_reflection_bsdf ( ) ) ); // Arrays of matrices export material material_MDL_423( // Array of matrix: square double2x2[3] test_double2x2 = double2x2[](1,1,1) , double3x3[2] test_double3x3 = double3x3[](1,1) , double4x4[1] test_double4x4 = double4x4[](1) , float2x2[3] test_float2x2 = float2x2[](1,1,1) , float3x3[2] test_float3x3 = float3x3[](1,1) , float4x4[1] test_float4x4 = float4x4[](1) // Array of matrix: non-square , double2x3[1] test_double2x3 = double2x3[](1) , double2x4[1] test_double2x4 = double2x4[](1) , double3x2[1] test_double3x2 = double3x2[](1) , double3x4[1] test_double3x4 = double3x4[](1) , double4x2[1] test_double4x2 = double4x2[](1) , double4x3[1] test_double4x3 = double4x3[](1) , float2x3[1] test_float2x3 = float2x3[](1) , float2x4[1] test_float2x4 = float2x4[](1) , float3x2[1] test_float3x2 = float3x2[](1) , float3x4[1] test_float3x4 = float3x4[](1) , float4x2[1] test_float4x2 = float4x2[](1) , float4x3[1] test_float4x3 = float4x3[](float4x3(1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.5,0.0)) // size deferred array , float[<n>] test_size_deferred = float[2](1, 2) // Array of enum , material_type[4] test_enum_array = material_type[4](simple_material,complex_material,combiner_material,modifier_material) , material_type test_enum = combiner_material // Array of struct , example_struct test_struct = example_struct(1,1.0) // Arrays not supported in MDL // , light_profile[1] test_light_profile = light_profile[1](light_profile()) // , bsdf_measurement[1] test_bsdf_measurement = bsdf_measurement[1](bsdf_measurement()) // , bsdf[1] test_bsdf = bsdf[1](bsdf()) // , edf[1] test_edf = edf[1](edf()) // , vdf[1] test_vdf = vdf[1](vdf()) // , uniform texture_2d[2] test_texture_array = texture_2d[](texture_2d("./dummy.jpg", ::tex::gamma_default),texture_2d("./dummy.jpg", ::tex::gamma_default)) ) = material(surface: material_surface ( scattering : df::diffuse_reflection_bsdf ( ) ) ); // MDL-421 Add MDL light_profile support for USD SDK export material material_MDL_421( uniform light_profile test_light_profile = light_profile("./test.ies") , uniform light_profile test_light_profile_2 = light_profile(light_profile("./test.ies")) , uniform light_profile test_light_profile_3 = light_profile(test_light_profile_2) ) = material(surface: material_surface ( scattering : df::diffuse_reflection_bsdf ( ) ) ); // MDL-422 Add MDL BSDF measurement support for USD SDK export material material_MDL_422( uniform bsdf_measurement test_bsdf_measurement = bsdf_measurement("./test.mbsdf") ) = material(surface: material_surface ( scattering : df::diffuse_reflection_bsdf ( ) ) );
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/data/usd/scene.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (-81.16798659180053, 83.21013327845546, -160.2964729767833) double3 target = (-1.6342102521720427, -7.714286630979341, -3.647924803090891) } dictionary Right = { double3 position = (-50000, 0, -1.1102230246251565e-11) double radius = 500 } dictionary Top = { double3 position = (-4.329780281177466e-12, 50000, 1.1102230246251565e-11) double radius = 500 } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { float3 "rtx:debugView:pixelDebug:textColor" = (0, 1e18, 0) float3 "rtx:dynamicDiffuseGI:probeCounts" = (6, 6, 6) float3 "rtx:dynamicDiffuseGI:probeGridOrigin" = (-210, -250, -10) float3 "rtx:dynamicDiffuseGI:volumeSize" = (600, 440, 300) float3 "rtx:fog:fogColor" = (0.75, 0.75, 0.75) float3 "rtx:iray:environment_dome_ground_position" = (0, 0, 0) float3 "rtx:iray:environment_dome_ground_reflectivity" = (0, 0, 0) float3 "rtx:iray:environment_dome_rotation_axis" = (0, 1, 0) float3 "rtx:lightspeed:material:overrideAlbedo" = (0.5, 0.5, 0.5) float3 "rtx:lightspeed:material:overrideEmissiveColor" = (0.5, 0.5, 0.5) float3 "rtx:post:backgroundZeroAlpha:backgroundDefaultColor" = (0, 0, 0) float3 "rtx:post:colorcorr:contrast" = (1, 1, 1) float3 "rtx:post:colorcorr:gain" = (1, 1, 1) float3 "rtx:post:colorcorr:gamma" = (1, 1, 1) float3 "rtx:post:colorcorr:offset" = (0, 0, 0) float3 "rtx:post:colorcorr:saturation" = (1, 1, 1) float3 "rtx:post:colorgrad:blackpoint" = (0, 0, 0) float3 "rtx:post:colorgrad:contrast" = (1, 1, 1) float3 "rtx:post:colorgrad:gain" = (1, 1, 1) float3 "rtx:post:colorgrad:gamma" = (1, 1, 1) float3 "rtx:post:colorgrad:lift" = (0, 0, 0) float3 "rtx:post:colorgrad:multiply" = (1, 1, 1) float3 "rtx:post:colorgrad:offset" = (0, 0, 0) float3 "rtx:post:colorgrad:whitepoint" = (1, 1, 1) float3 "rtx:post:lensDistortion:lensFocalLengthArray" = (10, 30, 50) float3 "rtx:post:lensFlares:anisoFlareFalloffX" = (450, 475, 500) float3 "rtx:post:lensFlares:anisoFlareFalloffY" = (10, 10, 10) float3 "rtx:post:lensFlares:cutoffPoint" = (2, 2, 2) float3 "rtx:post:lensFlares:haloFlareFalloff" = (10, 10, 10) float3 "rtx:post:lensFlares:haloFlareRadius" = (75, 75, 75) float3 "rtx:post:lensFlares:isotropicFlareFalloff" = (50, 50, 50) float3 "rtx:post:tonemap:whitepoint" = (1, 1, 1) float3 "rtx:raytracing:inscattering:singleScatteringAlbedo" = (0.9, 0.9, 0.9) float3 "rtx:raytracing:inscattering:transmittanceColor" = (0.5, 0.5, 0.5) token "rtx:rendermode" = "PathTracing" float3 "rtx:sceneDb:ambientLightColor" = (0.1, 0.1, 0.1) } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def DistantLight "defaultLight" ( prepend apiSchemas = ["ShapingAPI"] ) { float angle = 1 float intensity = 3000 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file double3 xformOp:rotateXYZ = (315, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Mesh "Plane" { int[] faceVertexCounts = [4] int[] faceVertexIndices = [0, 2, 3, 1] rel material:binding = </World/Looks/Material> ( bindMaterialAs = "weakerThanDescendants" ) normal3f[] normals = [(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)] ( interpolation = "faceVarying" ) point3f[] points = [(-50, 0, -50), (50, 0, -50), (-50, 0, 50), (50, 0, 50)] float2[] primvars:st = [(1, 0), (1, 1), (0, 1), (0, 0)] ( interpolation = "faceVarying" ) uniform token subdivisionScheme = "none" double3 xformOp:rotateXYZ = (-60.8521, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Scope "Looks" { def Material "Material" ( customData = { dictionary ui = { dictionary nodegraph = { dictionary node = { dictionary pos = { double2 output = (3.056504249572754, 19.027803421020508) } } } } } ) { token outputs:mdl:displacement token outputs:mdl:surface.connect = </World/Looks/Material/OmniSurfaceLiteBase.outputs:out> token outputs:mdl:volume def Shader "OmniSurfaceLiteBase" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { reorder properties = ["inputs:diffuse_reflection_weight", "inputs:diffuse_reflection_color", "inputs:diffuse_reflection_roughness", "inputs:metalness", "inputs:specular_reflection_weight", "inputs:specular_reflection_color", "inputs:specular_reflection_roughness", "inputs:specular_reflection_ior_preset", "inputs:specular_reflection_ior", "inputs:specular_reflection_anisotropy", "inputs:specular_reflection_anisotropy_rotation", "inputs:coat_weight", "inputs:coat_color", "inputs:coat_roughness", "inputs:coat_ior_preset", "inputs:coat_ior", "inputs:coat_anisotropy", "inputs:coat_anisotropy_rotation", "inputs:coat_affect_color", "inputs:coat_affect_roughness", "inputs:coat_normal", "inputs:emission_weight", "inputs:emission_mode", "inputs:emission_intensity", "inputs:emission_color", "inputs:emission_use_temperature", "inputs:emission_temperature", "inputs:enable_opacity", "inputs:geometry_opacity", "inputs:geometry_opacity_threshold", "inputs:geometry_normal", "inputs:geometry_displacement"] uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @OmniSurface/OmniSurfaceLiteBase.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "OmniSurfaceLiteBase" float inputs:coat_affect_color ( customData = { float default = 0 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Coat" displayName = "Affect Color" hidden = false renderType = "float" ) float inputs:coat_affect_roughness ( customData = { float default = 0 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Coat" displayName = "Affect Roughness" hidden = false renderType = "float" ) float inputs:coat_anisotropy ( customData = { float default = 0 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Coat" displayName = "Anisotropy" hidden = false renderType = "float" ) float inputs:coat_anisotropy_rotation ( customData = { float default = 0 dictionary soft_range = { float max = 1 float min = 0 } } displayGroup = "Coat" displayName = "Rotation (radian)" hidden = false renderType = "float" ) color3f inputs:coat_color ( customData = { float3 default = (1, 1, 1) } displayGroup = "Coat" displayName = "Color" hidden = false renderType = "color" ) float inputs:coat_ior ( customData = { float default = 1.5 dictionary range = { float max = 3.4028235e38 float min = 1 } dictionary soft_range = { float max = 5 float min = 1 } } displayGroup = "Coat" displayName = "IOR" hidden = false renderType = "float" ) float3 inputs:coat_normal ( customData = { float3 default = (0, 0, 0) } displayGroup = "Coat" displayName = "Normal" hidden = true renderType = "float3" ) float inputs:coat_roughness ( customData = { float default = 0.1 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Coat" displayName = "Roughness" hidden = false renderType = "float" ) float inputs:coat_weight ( customData = { float default = 0 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Coat" displayName = "Weight" hidden = false renderType = "float" ) color3f inputs:diffuse_reflection_color ( customData = { float3 default = (1, 1, 1) } displayGroup = "Base" displayName = "Color" hidden = false renderType = "color" ) color3f inputs:diffuse_reflection_color.connect = </World/Looks/Material/file_texture.outputs:color> float inputs:diffuse_reflection_roughness ( customData = { float default = 0 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Base" displayName = "Diffuse Roughness" hidden = false renderType = "float" ) float inputs:diffuse_reflection_weight ( customData = { float default = 0.8 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Base" displayName = "Weight" hidden = false renderType = "float" ) color3f inputs:emission_color ( customData = { float3 default = (1, 1, 1) } displayGroup = "Emission" displayName = "Color" hidden = false renderType = "color" ) float inputs:emission_intensity ( customData = { float default = 1 dictionary soft_range = { float max = 1000 float min = 0 } } displayGroup = "Emission" displayName = "Intensity" hidden = false renderType = "float" ) float inputs:emission_temperature ( customData = { float default = 6500 dictionary soft_range = { float max = 10000 float min = 0 } } displayGroup = "Emission" displayName = "Temperature (kelvin)" hidden = false renderType = "float" ) bool inputs:emission_use_temperature ( customData = { bool default = 0 } displayGroup = "Emission" displayName = "Use Temperature" hidden = false renderType = "bool" ) float inputs:emission_weight ( customData = { float default = 0 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Emission" displayName = "Weight" hidden = false renderType = "float" ) bool inputs:enable_opacity ( customData = { bool default = 0 } displayGroup = "Geometry" displayName = "Enable Opacity" doc = "Enables the use of cutout opacity" hidden = false renderType = "bool" ) float3 inputs:geometry_displacement ( customData = { float3 default = (0, 0, 0) } displayGroup = "Geometry" displayName = "Displacement" hidden = false renderType = "float3" ) float3 inputs:geometry_normal ( customData = { float3 default = (0, 0, 0) } displayGroup = "Geometry" displayName = "Geometry Normal" hidden = true renderType = "float3" ) float inputs:geometry_opacity ( customData = { float default = 1 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Geometry" displayName = "Opacity" hidden = false renderType = "float" ) float inputs:geometry_opacity_threshold ( customData = { float default = 0 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Geometry" displayName = "Opacity Threshold" doc = "If > 0, remap opacity values to 1 when >= threshold and to 0 otherwise" hidden = false renderType = "float" ) float inputs:metalness = 1 ( customData = { float default = 0 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Base" displayName = "Metalness" hidden = false renderType = "float" ) float inputs:specular_reflection_anisotropy ( customData = { float default = 0 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Specular" displayName = "Anisotropy" hidden = false renderType = "float" ) float inputs:specular_reflection_anisotropy_rotation ( customData = { float default = 0 dictionary soft_range = { float max = 1 float min = 0 } } displayGroup = "Specular" displayName = "Rotation (radian)" hidden = false renderType = "float" ) color3f inputs:specular_reflection_color ( customData = { float3 default = (1, 1, 1) } displayGroup = "Specular" displayName = "Color" hidden = false renderType = "color" ) float inputs:specular_reflection_ior ( customData = { float default = 1.5 dictionary range = { float max = 3.4028235e38 float min = 0 } dictionary soft_range = { float max = 5 float min = 1 } } displayGroup = "Specular" displayName = "IOR" hidden = false renderType = "float" ) float inputs:specular_reflection_roughness ( customData = { float default = 0.2 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Specular" displayName = "Roughness" hidden = false renderType = "float" ) float inputs:specular_reflection_roughness.connect = </World/Looks/Material/file_texture.outputs:r> float inputs:specular_reflection_weight ( customData = { float default = 1 dictionary range = { float max = 1 float min = 0 } } displayGroup = "Specular" displayName = "Weight" hidden = false renderType = "float" ) token outputs:out ( renderType = "material" ) uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-371.21375, 36.668747) } def NodeGraph "file_texture" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { reorder properties = ["inputs:texture", "inputs:mono_source", "inputs:brightness", "inputs:contrast", "inputs:invert", "inputs:texture_space", "inputs:rotation", "inputs:translation", "inputs:scaling", "inputs:clip", "outputs:tex", "outputs:color", "outputs:mono", "outputs:r", "outputs:g", "outputs:b"] float inputs:brightness ( customData = { double default = 1 } displayGroup = "Bitmap parameters" displayName = "Brightness" renderType = "float" ) bool inputs:clip ( customData = { bool default = 0 } displayGroup = "Placement" displayName = "Clip" renderType = "bool" ) float inputs:contrast ( customData = { double default = 1 } displayGroup = "Bitmap parameters" displayName = "Contrast" renderType = "float" ) bool inputs:invert ( customData = { bool default = 0 } displayGroup = "Bitmap parameters" displayName = "Invert image" renderType = "bool" ) int inputs:mono_source ( customData = { int default = 1 } displayGroup = "Bitmap parameters" displayName = "Scalar mode" renderType = "mono_mode" sdrMetadata = { string __SDR__enum_value = "mono_average" string options = "mono_alpha:0|mono_average:1|mono_luminance:2|mono_maximum:3" } ) float inputs:rotation ( customData = { double default = 0 } displayGroup = "Placement" displayName = "Rotation" renderType = "float" ) float2 inputs:scaling ( customData = { double2 default = (1, 1) } displayGroup = "Placement" displayName = "Tiling" renderType = "float2" ) asset inputs:texture = @./ash_uvgrid07.jpg@ ( colorSpace = "sRGB" customData = { asset default = @@ } displayGroup = "Bitmap parameters" displayName = "Bitmap file" renderType = "texture_2d" ) int inputs:texture_space ( customData = { int default = 0 dictionary range = { int max = 3 int min = 0 } } displayGroup = "Placement" displayName = "UV space index" renderType = "int" ) float2 inputs:translation ( customData = { double2 default = (0, 0) } displayGroup = "Placement" displayName = "Offset" renderType = "float2" ) float outputs:b ( renderType = "float" ) float outputs:b.connect = </World/Looks/Material/file_texture/z.outputs:out> color3f outputs:color ( renderType = "color" ) color3f outputs:color.connect = </World/Looks/Material/file_texture/construct_color.outputs:out> float outputs:g ( renderType = "float" ) float outputs:g.connect = </World/Looks/Material/file_texture/y.outputs:out> float outputs:mono ( renderType = "float" ) float outputs:mono.connect = </World/Looks/Material/file_texture/construct_float.outputs:out> float outputs:r ( renderType = "float" ) float outputs:r.connect = </World/Looks/Material/file_texture/x.outputs:out> token outputs:tex ( renderType = "texture_return" ) token outputs:tex.connect = </World/Looks/Material/file_texture/file_texture.outputs:out> custom token ui:description = "Allows texturing using image files of various file formats" uniform token ui:displayGroup = "Texturing, high level" uniform token ui:displayName = "Bitmap texture" uniform token ui:nodegraph:node:expansionState = "open" uniform asset ui:nodegraph:node:icon = @core_definitions.file_texture.png@ uniform float2 ui:nodegraph:node:pos = (-772.8611, -87.96896) custom int ui:order = 30 def Shader "file_texture" { reorder properties = ["inputs:texture", "inputs:mono_source", "inputs:brightness", "inputs:contrast", "inputs:invert", "inputs:texture_space", "inputs:rotation", "inputs:translation", "inputs:scaling", "inputs:clip"] uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/core_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "file_texture(texture_2d,::base::mono_mode,float,float,float2,float2,float,bool,int,bool)" float inputs:brightness ( customData = { double default = 1 } displayGroup = "Bitmap parameters" displayName = "Brightness" renderType = "float" ) float inputs:brightness.connect = </World/Looks/Material/file_texture.inputs:brightness> bool inputs:clip ( customData = { bool default = 0 } displayGroup = "Placement" displayName = "Clip" doc = "If set to true, texture will not repeat. Outside of the texture, color will be black and the scalar value will be 0" renderType = "bool" ) bool inputs:clip.connect = </World/Looks/Material/file_texture.inputs:clip> float inputs:contrast ( customData = { double default = 1 } displayGroup = "Bitmap parameters" displayName = "Contrast" renderType = "float" ) float inputs:contrast.connect = </World/Looks/Material/file_texture.inputs:contrast> bool inputs:invert ( customData = { bool default = 0 } displayGroup = "Bitmap parameters" displayName = "Invert image" doc = "Invert image" renderType = "bool" ) bool inputs:invert.connect = </World/Looks/Material/file_texture.inputs:invert> int inputs:mono_source ( customData = { int default = 1 } displayGroup = "Bitmap parameters" displayName = "Scalar mode" doc = "Defines how the texture applies to scalar parameters" renderType = "mono_mode" sdrMetadata = { string __SDR__enum_value = "mono_average" string options = "mono_alpha:0|mono_average:1|mono_luminance:2|mono_maximum:3" } ) int inputs:mono_source.connect = </World/Looks/Material/file_texture.inputs:mono_source> float inputs:rotation ( customData = { double default = 0 } displayGroup = "Placement" displayName = "Rotation" doc = "Rotation angle of the texture in degrees" renderType = "float" ) float inputs:rotation.connect = </World/Looks/Material/file_texture.inputs:rotation> float2 inputs:scaling ( customData = { double2 default = (1, 1) } displayGroup = "Placement" displayName = "Tiling" doc = "Controls the scale of the texture on the object" renderType = "float2" ) float2 inputs:scaling.connect = </World/Looks/Material/file_texture.inputs:scaling> asset inputs:texture ( colorSpace = "sRGB" customData = { asset default = @@ } displayGroup = "Bitmap parameters" displayName = "Bitmap file" renderType = "texture_2d" ) asset inputs:texture.connect = </World/Looks/Material/file_texture.inputs:texture> int inputs:texture_space ( customData = { int default = 0 dictionary range = { int max = 3 int min = 0 } } displayGroup = "Placement" displayName = "UV space index" doc = "Selects a specific UV space" renderType = "int" ) int inputs:texture_space.connect = </World/Looks/Material/file_texture.inputs:texture_space> float2 inputs:translation ( customData = { double2 default = (0, 0) } displayGroup = "Placement" displayName = "Offset" doc = "Controls position of the texture on the object" renderType = "float2" ) float2 inputs:translation.connect = </World/Looks/Material/file_texture.inputs:translation> token outputs:out ( renderType = "texture_return" ) } def Shader "construct_float" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/aux_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "construct_float(::base::texture_return)" token inputs:a ( renderType = "texture_return" ) token inputs:a.connect = </World/Looks/Material/file_texture/file_texture.outputs:out> float outputs:out ( renderType = "float" ) } def Shader "construct_color" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/aux_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "construct_color(::base::texture_return)" token inputs:a ( renderType = "texture_return" ) token inputs:a.connect = </World/Looks/Material/file_texture/file_texture.outputs:out> color3f outputs:out ( renderType = "color" ) } def Shader "x" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/aux_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "x(color)" color3f inputs:a ( renderType = "color" ) color3f inputs:a.connect = </World/Looks/Material/file_texture/construct_color.outputs:out> float outputs:out ( renderType = "float" ) } def Shader "y" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/aux_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "y(color)" color3f inputs:a ( renderType = "color" ) color3f inputs:a.connect = </World/Looks/Material/file_texture/construct_color.outputs:out> float outputs:out ( renderType = "float" ) } def Shader "z" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/aux_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "z(color)" color3f inputs:a ( renderType = "color" ) color3f inputs:a.connect = </World/Looks/Material/file_texture/construct_color.outputs:out> float outputs:out ( renderType = "float" ) } } } } } def "Environment" { def DomeLight "sky_champagne_castle_1_4k" ( prepend apiSchemas = ["ShapingAPI"] ) { float intensity = 1000 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus = 0 color3f shaping:focusTint = (0, 0, 0) asset shaping:ies:file float specular = 1 asset texture:file = @http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Skies/Cloudy/champagne_castle_1_4k.hdr@ token texture:format = "latlong" token visibility = "inherited" bool visibleInPrimaryRay = 1 double3 xformOp:rotateXYZ = (270, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } }
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/data/usd/tutorials.usda
#usda 1.0 ( "MDL to USD conversion" defaultPrim = "blinker_material" ) def Shader "example_struct" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_struct" float inputs:param_float = 0 token outputs:out ( renderType = "material" ) } def Shader "example_struct_param_int" ( customData = { dictionary mdl = { dictionary annotations = { bool "::anno::hidden()" = 1 } } } hidden = true ) { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_struct.param_int" token outputs:out ( renderType = "material" ) } def Shader "example_struct_param_float" ( customData = { dictionary mdl = { dictionary annotations = { bool "::anno::hidden()" = 1 } } } hidden = true ) { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_struct.param_float" token outputs:out ( renderType = "material" ) } def Shader "example_function" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_function" token outputs:out ( renderType = "material" ) } def Shader "wave_height" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "wave_height" float2[] inputs:wave_centers = [(0.2, 0.7), (0.6, 0.4), (0.35, 0.6)] token outputs:out ( renderType = "material" ) } def Shader "wave_gradient" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "wave_gradient" float inputs:delta = 0.01 float inputs:factor = 1 token inputs:normal.connect = </wave_gradient/normal.outputs:out> token inputs:uvw.connect = </wave_gradient/uvw.outputs:out> float2[] inputs:wave_centers = [(0.2, 0.7), (0.6, 0.4), (0.35, 0.6)] token outputs:out ( renderType = "material" ) def Shader "uvw" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @base.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "texture_coordinate_info(float3,float3,float3)" token inputs:position.connect = </wave_gradient/position.outputs:out> token inputs:tangent_u.connect = </wave_gradient/tangent_u.outputs:out> token inputs:tangent_v.connect = </wave_gradient/tangent_v.outputs:out> token outputs:out } def Shader "position" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/support_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "texture_coordinate(int)" int inputs:index = 0 token outputs:out } def Shader "tangent_u" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/support_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "texture_tangent_u(int)" int inputs:index = 0 token outputs:out } def Shader "tangent_v" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/support_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "texture_tangent_v(int)" int inputs:index = 0 token outputs:out } def Shader "normal" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/support_definitions.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "normal()" token outputs:out } } def Shader "checker_value" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "checker_value" token outputs:out ( renderType = "material" ) } def Shader "checker_value_roughness" ( customData = { dictionary mdl = { dictionary annotations = { bool "::anno::hidden()" = 1 } } } hidden = true ) { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "checker_value.roughness" token outputs:out ( renderType = "material" ) } def Shader "checker_value_weight" ( customData = { dictionary mdl = { dictionary annotations = { bool "::anno::hidden()" = 1 } } } hidden = true ) { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "checker_value.weight" token outputs:out ( renderType = "material" ) } def Shader "Options" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "Options" int inputs:v = 0 ( renderType = "::nvidia::sdk_examples::tutorials::Options" ) token outputs:out ( renderType = "material" ) } def Shader "int" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "int" token outputs:out ( renderType = "material" ) } def Shader "checker" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "checker" token outputs:out ( renderType = "material" ) } def Shader "color_checker" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "color_checker" color3f inputs:a = (1, 1, 1) color3f inputs:b = (0, 0, 0) float inputs:scale = 1 token outputs:out ( renderType = "material" ) } def Shader "fd_1" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "fd_1" int inputs:param0 = 42 token outputs:out ( renderType = "material" ) } def Shader "fd_default_call" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "fd_default_call" int inputs:param0.connect = </fd_default_call/param0.outputs:out> token outputs:out ( renderType = "material" ) def Shader "param0" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "fd_1(int)" int inputs:param0 = 42 token outputs:out } } def Shader "fd_auto_uniform" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "fd_auto_uniform" token outputs:out ( renderType = "material" ) } def Shader "fd_auto_varying" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "fd_auto_varying" token outputs:out ( renderType = "material" ) } def Shader "example_material" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_material" float inputs:roughness = 0 color3f inputs:tint = (1, 1, 1) token outputs:out ( renderType = "material" ) } def Shader "example_compilation" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_compilation" color3f inputs:tint = (1, 1, 1) token outputs:out ( renderType = "material" ) } def Shader "example_execution1" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_execution1" color3f inputs:tint = (1, 1, 1) token outputs:out ( renderType = "material" ) } def Shader "example_execution2" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_execution2" float3 inputs:light_pos = (-5, 3, 5) token outputs:out ( renderType = "material" ) } def Shader "example_execution3" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_execution3" token outputs:out ( renderType = "material" ) } def Shader "example_execution4" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_execution4" token outputs:out ( renderType = "material" ) } def Shader "example_modulemdl_material_examples" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_modulemdl_material_examples" asset inputs:profile = @nvidia/sdk_examples/resources/example_modules.ies@ color3f inputs:tint = (1, 1, 1) token outputs:out ( renderType = "material" ) } def Shader "example_modules2" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_modules2" token outputs:out ( renderType = "material" ) } def Shader "example_df" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_df" int inputs:add_checker = 1 ( renderType = "::nvidia::sdk_examples::tutorials::Options" ) float inputs:anisotropy = 0.5 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 1 double "::anno::hard_range(float,float)::min" = 0 } } } ) float inputs:checker_scale = 1 float inputs:clearcoat_ior = 1.5 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 10 double "::anno::hard_range(float,float)::min" = 1 } } } ) color3f inputs:diffuse_tint = (1, 0.5, 0.3) float inputs:diffuse_weight = 0.25 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 1 double "::anno::hard_range(float,float)::min" = 0 } } } ) color3f inputs:emission_intensity = (0.25, 0.5, 0.75) float inputs:emission_intensity_scale = 0.5 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 10 double "::anno::hard_range(float,float)::min" = 0 } } } ) string inputs:emission_usage = "full" color3f inputs:glossy_tint = (0.3, 0.5, 1) float inputs:glossy_weight = 1 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 1 double "::anno::hard_range(float,float)::min" = 0 } } } ) float inputs:roughness = 0.1 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 1 double "::anno::hard_range(float,float)::min" = 0 } } } ) asset inputs:tex = @nvidia/sdk_examples/resources/example.png@ float inputs:tex_coord_scale = 14 token outputs:out ( renderType = "material" ) } def Shader "example_edf" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_edf" float inputs:diffuse_emission_weight = 0.25 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 1 double "::anno::hard_range(float,float)::min" = 0 } } } ) color3f inputs:diffuse_tint = (0, 0, 0) color3f inputs:emission_intensity = (0.25, 0.5, 0.75) float inputs:emission_intensity_scale = 1 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 10 double "::anno::hard_range(float,float)::min" = 0 } } } ) float inputs:exponent = 32 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 1024 double "::anno::hard_range(float,float)::min" = 0 } } } ) float inputs:spot_emission_weight = 0.25 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 1 double "::anno::hard_range(float,float)::min" = 0 } } } ) bool inputs:spot_global_distribution = 0 float inputs:spread = 3.1415927 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 3.1415927410125732 double "::anno::hard_range(float,float)::min" = 0 } } } ) token outputs:out ( renderType = "material" ) } def Shader "example_mod_rough" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_mod_rough" float inputs:roughness = 0 color3f inputs:tint = (1, 1, 1) token outputs:out ( renderType = "material" ) } def Shader "dxr_sphere_mat" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "dxr_sphere_mat" float inputs:roughness_offset = 0.25 float inputs:roughness_scale = 1 color3f inputs:tint = (0.3, 0.3, 0.3) token outputs:out ( renderType = "material" ) } def Shader "example_measured_bsdf" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_measured_bsdf" asset inputs:mbsdf = @nvidia/sdk_examples/resources/example_modules.mbsdf@ int inputs:mode = 2 ( renderType = "::df::scatter_mode" ) float inputs:multiplier = 1 token outputs:out ( renderType = "material" ) } def Shader "example_measured_edf" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_measured_edf" bool inputs:global_distribution = 0 float inputs:multiplier = 1 ( customData = { dictionary mdl = { dictionary annotations = { double "::anno::hard_range(float,float)::max" = 10 double "::anno::hard_range(float,float)::min" = 0 } } } ) asset inputs:profile = @nvidia/sdk_examples/resources/example_modules.ies@ color3f inputs:tint = (0, 0, 0) token outputs:out ( renderType = "material" ) } def Shader "example_texture_lookup_bsdf" ( customData = { dictionary mdl = { dictionary annotations = { string "::anno::author(string)::name" = "NVIDIA Corporation" string "::anno::description(string)::description" = "test material" string "::anno::display_name(string)::name" = "aaa" bool "::anno::hidden()" = 1 } } } hidden = true sdrMetadata = { dictionary ui = { string description = "test material" string displayName = "aaa" } } ) { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_texture_lookup_bsdf" asset inputs:tex = @nvidia/sdk_examples/resources/example.png@ asset inputs:tex2 = @nvidia/sdk_examples/resources/example.png@ token outputs:out ( renderType = "material" ) uniform token ui:displayName = "aaa" } def Shader "blinker_material" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "blinker_material" color3f inputs:base = (0.1, 0.1, 0.1) bool inputs:enabled = 1 color3f inputs:light = (1, 0.9, 0) float inputs:speed = 5 token outputs:out ( renderType = "material" ) }
omniverse-code/kit/exts/omni.mdl.usd_converter/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.mdl.usd_converter`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`_. ## [1.0.1] - 2021-09-20 ### Changed - Added interface for USD to MDL conversion ## [1.0.0] - 2021-05-12 ### Added - Initial extensions 2.0
omniverse-code/kit/exts/omni.mdl.usd_converter/docs/README.md
# Python Extension for MDL <--> USD conversions [omni.mdl.usd_converter] This is an extension for MDL to USD and for USD to MDL conversions. ## Interfaces ### mdl_to_usd(moduleName: str, searchPath: str = None, targetFolder: str = MDL_AUTOGEN_PATH, targetFilename: str = None, output: mdl_usd.OutputType = mdl_usd.OutputType.SHADER, nestedShaders: bool = False) - moduleName: Module to convert (example: `nvidia/core_definitions.mdl`) - searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set) - targetFolder: Destination folder for USD stage (default = `${data}/shadergraphs/mdl_usd`) - targetFilename: Destination stage filename, extension `.usd` or `.usda` can be omitted (default is module name, example: `core_definitions.usda`) - output: What to output: a shader: omni.mdl.usd_converter.mdl_usd.OutputType.SHADER a material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL material and geometry: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY - nestedShaders: Do we want nested shaders or flat (default = False) ### usd_prim_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None, forceNotOV: bool = False) - usdStage: Input stage containing the prim to convert - usdPrim: Prim path to convert (default = not set, use stage default prim) - searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set) - forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False) ### export_to_mdl(path: str, prim: mdl_usd.Usd.Prim, forceNotOV: bool = False) - path: Output filename to save the new module to (need to end with .mdl, example: "c:/temp/new_module.mdl") - prim: The Usd.Prim to convert - forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False) ## Examples ### MDL -> USD conversion ``` omni.mdl.usd_converter.mdl_to_usd("nvidia/core_definitions.mdl") ``` Convert core_definitions module to USD. Save the result of the conversion in the folder `${data}/shadergraphs/mdl_usd`. ``` omni.mdl.usd_converter.mdl_to_usd( moduleName = "nvidia/core_definitions.mdl", targetFolder = "C:/ProgramData/NVIDIA Corporation/mdl") ``` Convert core_definitions module to USD. Save the result of the conversion in the folder `C:/ProgramData/NVIDIA Corporation/mdl`. ``` omni.mdl.usd_converter.mdl_to_usd( moduleName = "nvidia/core_definitions.mdl", targetFolder = "C:/ProgramData/NVIDIA Corporation/mdl", targetFilename = "stage.usda") ``` Convert core_definitions module to USD. Save the result of the conversion in the folder `C:/ProgramData/NVIDIA Corporation/mdl` under the name `stage.usda`. ### USD -> MDL conversion ``` import asyncio asyncio.ensure_future(omni.mdl.usd_converter.usd_prim_to_mdl( "C:/temp/tutorials.usda", "/example_material", "C:/ProgramData/NVIDIA Corporation/mdl", forceNotOV = True)) ``` Convert the USD Prim `/example_material` found in the stage `C:/temp/tutorials.usda`. Assuming `/example_material` is a valid prim in the stage `C:/temp/tutorials.usda`, and that MDL material module `tutorials.mdl` is under `C:/ProgramData/NVIDIA Corporation/mdl/nvidia/sdk_examples`, convert the prim to MDL in memory. Here is the shader prim: ``` def Shader "example_material" { uniform token info:implementationSource = "sourceAsset" uniform asset info:mdl:sourceAsset = @nvidia/sdk_examples/tutorials.mdl@ uniform token info:mdl:sourceAsset:subIdentifier = "example_material" float inputs:roughness = 0 color3f inputs:tint = (1, 1, 1) token outputs:out ( renderType = "material" ) } ```
omniverse-code/kit/exts/omni.mdl.usd_converter/docs/index.rst
omni.mdl.usd_converter ########################### .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.kit.menu.file/PACKAGE-LICENSES/omni.kit.menu.file-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.menu.file/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.1.4" category = "Internal" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "File Menu" description="Implementation of File Menu. New, Open, Save, Exit etc." # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "ui", "menu"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" [settings] persistent.app.file.recentFiles = [] [dependencies] "omni.usd" = {} "omni.kit.menu.utils" = {} "omni.kit.window.file" = {} "omni.client" = {} [[python.module]] name = "omni.kit.menu.file" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/file/ignoreUnsavedStage=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window", ] dependencies = [ "omni.hydra.pxr", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.window.preferences", "omni.kit.property.usd", "omni.kit.material.library", "omni.kit.ui_test", "omni.kit.test_suite.helpers" ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop "*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available ] unreliable = true # OM-55408
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/__init__.py
from .scripts import *
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/__init__.py
from .file import *
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/file_actions.py
import carb import omni.usd import omni.kit.window.file import omni.kit.actions.core def post_notification(message: str, info: bool = False, duration: int = 3): try: import omni.kit.notification_manager as nm if info: type = nm.NotificationStatus.INFO else: type = nm.NotificationStatus.WARNING nm.post_notification(message, status=type, duration=duration) except ModuleNotFoundError: carb.log_warn(message) def quit(fast: bool = False): if fast: carb.settings.get_settings().set("/app/fastShutdown", True) omni.kit.app.get_app().post_quit() def open_stage_with_new_edit_layer(): stage = omni.usd.get_context().get_stage() if not stage: post_notification(f"Cannot Re-open with New Edit Layer. No valid stage") return omni.kit.window.file.open_with_new_edit_layer(stage.GetRootLayer().identifier) def register_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "File Actions" omni.kit.actions.core.get_action_registry().register_action( extension_id, "quit", lambda: quit(fast=False), display_name="File->Exit", description="Exit", tag=actions_tag, ) omni.kit.actions.core.get_action_registry().register_action( extension_id, "quit_fast", lambda: quit(fast=True), display_name="File->Exit Fast", description="Exit Fast", tag=actions_tag, ) omni.kit.actions.core.get_action_registry().register_action( extension_id, "open_stage_with_new_edit_layer", open_stage_with_new_edit_layer, display_name="File->Open Current Stage With New Edit Layer", description="Open Stage With New Edit Layer", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/file.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import urllib.parse import carb.input import omni.client import omni.ext import omni.kit.menu.utils import omni.kit.ui import omni.usd from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types, FILE_EVENT_QUEUE_UPDATED from omni.kit.menu.utils import MenuItemDescription from .file_actions import register_actions, deregister_actions from omni.ui import color as cl from pathlib import Path _extension_instance = None _extension_path = None INTERACTIVE_TEXT = cl.shade(cl("#1A91C5")) SHARE_ICON_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)).joinpath("data/icons/share.svg") class FileMenuExtension(omni.ext.IExt): def __init__(self): super().__init__() omni.kit.menu.utils.set_default_menu_proirity("File", -10) def on_startup(self, ext_id): global _extension_instance _extension_instance = self global _extension_path _extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id) self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name) settings = carb.settings.get_settings() self._max_recent_files = settings.get("exts/omni.kit.menu.file/maxRecentFiles") or 10 self._file_menu_list = None self._recent_menu_list = None self._build_file_menu() event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._event_sub = event_stream.create_subscription_to_pop_by_type(FILE_EVENT_QUEUE_UPDATED, lambda _: self._build_recent_menu()) events = omni.usd.get_context().get_stage_event_stream() self._stage_event_subscription = events.create_subscription_to_pop(self._on_stage_event, name="omni.kit.menu.file stage watcher") def on_shutdown(self): global _extension_instance deregister_actions(self._ext_name) _extension_instance = None self._stage_sub = None omni.kit.menu.utils.remove_menu_items(self._recent_menu_list, "File") omni.kit.menu.utils.remove_menu_items(self._file_menu_list, "File") self._recent_menu_list = None self._file_menu_list = None self._event_sub = None def _on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): self._build_file_menu() def _build_file_menu(self): # setup menu self._file_menu_list = [ MenuItemDescription( name="New", glyph="file.svg", onclick_action=("omni.kit.window.file", "new"), hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.N), ), MenuItemDescription( name="Open", glyph="folder_open.svg", onclick_action=("omni.kit.window.file", "open"), hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.O), ), MenuItemDescription(), MenuItemDescription( name="Re-open with New Edit Layer", glyph="external_link.svg", # enable_fn=lambda: not FileMenuExtension.is_new_stage(), onclick_action=("omni.kit.menu.file", "open_stage_with_new_edit_layer") ), MenuItemDescription(), MenuItemDescription( name="Share", glyph=str(SHARE_ICON_PATH), enable_fn=FileMenuExtension.can_share, onclick_action=("omni.kit.window.file", "share") ), MenuItemDescription(), MenuItemDescription( name="Save", glyph="save.svg", # enable_fn=FileMenuExtension.can_close, onclick_action=("omni.kit.window.file", "save"), hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.S), ), MenuItemDescription( name="Save With Options", glyph="save.svg", # enable_fn=FileMenuExtension.can_close, onclick_action=("omni.kit.window.file", "save_with_options"), hotkey=( carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL | carb.input.KEYBOARD_MODIFIER_FLAG_ALT, carb.input.KeyboardInput.S, ), ), MenuItemDescription( name="Save As...", glyph="none.svg", # enable_fn=FileMenuExtension.can_close, onclick_action=("omni.kit.window.file", "save_as"), hotkey=( carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL | carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT, carb.input.KeyboardInput.S, ), ), MenuItemDescription( name="Save Flattened As...", glyph="none.svg", # enable_fn=FileMenuExtension.can_close, onclick_action=("omni.kit.window.file", "save_as_flattened"), ), MenuItemDescription(), MenuItemDescription( name="Add Reference", glyph="none.svg", onclick_action=("omni.kit.window.file", "add_reference"), ), MenuItemDescription( name="Add Payload", glyph="none.svg", onclick_action=("omni.kit.window.file", "add_payload") ), MenuItemDescription(), MenuItemDescription(name="Exit", glyph="none.svg", onclick_action=("omni.kit.menu.file", "quit")), ] if not carb.settings.get_settings().get("/app/fastShutdown"): self._file_menu_list.append(MenuItemDescription(name="Exit Fast (Experimental)", glyph="none.svg", onclick_action=("omni.kit.menu.file", "quit_fast"))) self._build_recent_menu() omni.kit.menu.utils.add_menu_items(self._file_menu_list, "File", -10) def _build_recent_menu(self): if self._recent_menu_list: omni.kit.menu.utils.remove_menu_items(self._recent_menu_list, "File", rebuild_menus=False) recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD) sub_menu = [] # add reopen stage = omni.usd.get_context().get_stage() is_anonymous = stage.GetRootLayer().anonymous if stage else False filename_url = "" if not is_anonymous: filename_url = stage.GetRootLayer().identifier if stage else "" if filename_url: sub_menu.append( MenuItemDescription( name=f"Current stage: {filename_url}", onclick_action=("omni.kit.window.file", "reopen"), user={"user_style": {"color": INTERACTIVE_TEXT}} ) ) elif not recent_files: sub_menu.append(MenuItemDescription(name="None", enabled=False)) if recent_files: for recent_file in recent_files: # NOTE: not compatible with hotkeys as passing URL to open_stage sub_menu.append( MenuItemDescription( name=urllib.parse.unquote(recent_file), onclick_action=("omni.kit.window.file", "open_stage", recent_file), ) ) self._recent_menu_list = [ MenuItemDescription(name="Open Recent", glyph="none.svg", appear_after="Open", sub_menu=sub_menu) ] omni.kit.menu.utils.add_menu_items(self._recent_menu_list, "File") def is_new_stage(): return omni.usd.get_context().is_new_stage() def can_open(): stage_state = omni.usd.get_context().get_stage_state() return stage_state == omni.usd.StageState.OPENED or stage_state == omni.usd.StageState.CLOSED def can_save(): return ( omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED and not FileMenuExtension.is_new_stage() and omni.usd.get_context().is_writable() ) def can_close(): return omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED def can_close_and_not_is_new_stage(): return FileMenuExtension.can_close() and not FileMenuExtension.is_new_stage() def can_share(): return ( omni.usd.get_context() is not None and omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED and omni.usd.get_context().get_stage_url().startswith("omniverse://") ) def get_extension_path(sub_directory): global _extension_path path = _extension_path if sub_directory: path = os.path.normpath(os.path.join(path, sub_directory)) return path def get_instance(): global _extension_instance return _extension_instance
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_recent_menu.py
import carb import omni.kit.test import omni.kit.helper.file_utils as file_utils from omni.kit import ui_test from .. import get_instance from omni.kit.window.file_importer.test_helper import FileImporterTestHelper class TestMenuFileRecents(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await omni.usd.get_context().new_stage_async() file_utils.reset_file_event_queue() # After running each test async def tearDown(self): await omni.usd.get_context().new_stage_async() file_utils.reset_file_event_queue() async def _mock_open_stage_async(self, url: str): # Doesn't actually open a stage but pushes an opened event like that action would. This # should cause the file event queue to update. message_bus = omni.kit.app.get_app().get_message_bus_event_stream() message_bus.push(file_utils.FILE_OPENED_EVENT, payload=file_utils.FileEventModel(url=url).dict()) await ui_test.human_delay(4) async def test_file_recent_menu(self): test_files = [ "omniverse://ov-test/first.usda", "c:/users/me/second.usda", "omniverse://ov-test/third.usda", ] under_test = get_instance() get_recent_list = lambda: under_test._recent_menu_list[0].sub_menu # load first.usda file... rebuild_menu == 1 await self._mock_open_stage_async(test_files[0]) recent_list = get_recent_list() self.assertEqual(len(recent_list), 1) self.assertEqual(recent_list[0].name, test_files[0]) # load second.usda file... rebuild_menu == 2 await self._mock_open_stage_async(test_files[1]) recent_list = get_recent_list() self.assertEqual(len(recent_list), 2) self.assertEqual(recent_list[0].name, test_files[1]) # load second.usda file again... rebuild_menu still == 2 await self._mock_open_stage_async(test_files[1]) recent_list = get_recent_list() self.assertEqual(len(recent_list), 2) self.assertEqual(recent_list[0].name, test_files[1]) # load third.usda ... rebuild_menu == 3 await self._mock_open_stage_async(test_files[2]) recent_list = get_recent_list() self.assertEqual(len(recent_list), 3) self.assertEqual(recent_list[0].name, test_files[2]) # confirm list order is as expected expected = test_files[::-1] self.assertEqual([i.name for i in recent_list], expected) async def test_file_recent_menu_current_stage(tester, _): under_test = get_instance() get_recent_list = lambda: under_test._recent_menu_list[0].sub_menu # verify recent == "None" recent_list = get_recent_list() tester.assertEqual(len(recent_list), 1) tester.assertTrue(recent_list[0].name.startswith("None")) await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open").click() await ui_test.human_delay(5) async with FileImporterTestHelper() as file_import_helper: dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests") await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda") await tester.wait_for_stage_event() await ui_test.human_delay(5) # verify name of stage stage = omni.usd.get_context().get_stage() tester.assertTrue(stage.GetRootLayer().identifier.replace("\\", "/").endswith("data/tests/4Lights.usda")) # verify recent == "Current stage:" and "4Lights.usda" recent_list = get_recent_list() tester.assertEqual(len(recent_list), 2) tester.assertTrue(recent_list[0].name.startswith("Current stage:")) tester.assertTrue(recent_list[0].name.endswith("data/tests/4Lights.usda")) tester.assertFalse(recent_list[1].name.startswith("Current stage:")) tester.assertTrue(recent_list[1].name.endswith("data/tests/4Lights.usda")) await omni.usd.get_context().new_stage_async() await ui_test.human_delay(5) # verify recent == "4Lights.usda" recent_list = get_recent_list() tester.assertEqual(len(recent_list), 1) tester.assertFalse(recent_list[0].name.startswith("Current stage:")) tester.assertTrue(recent_list[0].name.endswith("data/tests/4Lights.usda"))
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/__init__.py
from .file_tests import * from .test_recent_menu import *
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_templates.py
import asyncio import carb import omni.usd import omni.ui as ui from omni.kit import ui_test from omni.kit.menu.utils import MenuItemDescription, MenuLayout async def file_test_func_file_new_from_stage_template_empty(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("New From Stage Template").click() # select empty and wait for stage open await menu_widget.find_menu("Empty").click() await tester.wait_for_stage_event() # verify Empty stage stage = omni.usd.get_context().get_stage() tester.assertFalse(stage.GetRootLayer().identifier == layer_name) prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertTrue(prim_list == ['/World']) async def file_test_func_file_new_from_stage_template_sunlight(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("New From Stage Template").click() # select Sunlight and wait for stage open await menu_widget.find_menu("Sunlight").click() await tester.wait_for_stage_event() # verify Sunlight stage stage = omni.usd.get_context().get_stage() tester.assertFalse(stage.GetRootLayer().identifier == layer_name) prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertTrue(prim_list == ['/World', '/Environment', '/Environment/defaultLight']) async def file_test_func_file_new_from_stage_template_default_stage(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("New From Stage Template").click() # select Default Stage and wait for stage open await menu_widget.find_menu("Default Stage").click() await tester.wait_for_stage_event() # verify Default Stage stage = omni.usd.get_context().get_stage() tester.assertFalse(stage.GetRootLayer().identifier == layer_name) prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertEqual(set(prim_list), set([ '/World', '/Environment', '/Environment/Sky', '/Environment/DistantLight', '/Environment/Looks', '/Environment/Looks/Grid', '/Environment/Looks/Grid/Shader', '/Environment/ground', '/Environment/groundCollider']))
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_media.py
import os import shutil import tempfile import asyncio import carb import omni.usd import omni.ui as ui from omni.kit import ui_test from omni.kit.menu.utils import MenuItemDescription, MenuLayout from omni.kit.window.file_importer.test_helper import FileImporterTestHelper from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper async def file_test_func_file_new(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("New").click() await tester.wait_for_stage_event() # verify its a new layer tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier == layer_name) async def file_test_func_file_open(tester, menu_item: MenuItemDescription): await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open").click() await ui_test.human_delay(5) async with FileImporterTestHelper() as file_import_helper: dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests") await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda") await tester.wait_for_stage_event() # verify name of stage stage = omni.usd.get_context().get_stage() tester.assertTrue(stage.GetRootLayer().identifier.replace("\\", "/").endswith("data/tests/4Lights.usda")) async def file_test_func_file_reopen(tester, menu_item: MenuItemDescription): await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open Recent").click() await menu_widget.find_menu(tester._light_path, ignore_case=True).click() await tester.wait_for_stage_event() # verify its a unmodified stage tester.assertFalse(omni.kit.undo.can_undo()) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # verify its a modified stage tester.assertTrue(omni.kit.undo.can_undo()) await tester.reset_stage_event(omni.usd.StageEventType.OPENED) await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open Recent").click() await menu_widget.find_menu("Current stage:", contains_path=True).click() await tester.wait_for_stage_event() # verify its a unmodified stage tester.assertFalse(omni.kit.undo.can_undo()) async def file_test_func_file_re_open_with_new_edit_layer(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await file_test_func_file_open(tester, {}) await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Re-open with New Edit Layer").click() await ui_test.human_delay(50) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights_layer.usda") await tester.wait_for_stage_event() # verify its not saved to tmpdir layer = omni.usd.get_context().get_stage().GetRootLayer() expected_name = f"{tmpdir}/4Lights_layer.usd".replace("\\", "/") tester.assertTrue(layer.anonymous) tester.assertTrue(len(layer.subLayerPaths) == 2) tester.assertTrue(layer.subLayerPaths[0] == expected_name) tester.assertTrue(layer.subLayerPaths[1].endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda")) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_save(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save").click() await ui_test.human_delay(50) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") expected_size = os.path.getsize(expected_name) tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # save again, it should not show dialog.... await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save").click() await ui_test.human_delay() # handle dialog.... save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'") await save_widget.click() await ui_test.human_delay() await tester.wait_for_stage_event() # verify file was saved tester.assertFalse(os.path.getsize(expected_name) == expected_size) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_save_with_options(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save With Options").click() await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") expected_size = os.path.getsize(expected_name) tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # save again, it should not show dialog.... await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save").click() await ui_test.human_delay() # handle dialog.... save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'") await save_widget.click() await ui_test.human_delay() await tester.wait_for_stage_event() # verify file was saved tester.assertFalse(os.path.getsize(expected_name) == expected_size) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_save_as(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await file_test_func_file_open(tester, {}) await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save As...").click() await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_save_flattened_as(tester, menu_item: MenuItemDescription): # save flattened doesn't send any stage events as it exports not saves tmpdir = tempfile.mkdtemp() await file_test_func_file_open(tester, {}) stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier.replace("\\", "/") if stage else "None" await tester.reset_stage_event(omni.usd.StageEventType.SAVED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Save Flattened As...").click() await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda") await ui_test.human_delay(20) # verify its exported to tmpdir & hasn't changed stage path expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == layer_name) tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_open_recent_exts_omni_kit_menu_file_data_tests_4lights_usda(tester, menu_item: MenuItemDescription): await tester.reset_stage_event(omni.usd.StageEventType.OPENED) menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Open Recent").click() await menu_widget.find_menu(tester._light_path, ignore_case=True).click() await tester.wait_for_stage_event() # verify its 4lights tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/").endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda")) async def file_test_func_file_exit(tester, menu_item: MenuItemDescription): # not sure how to test this without kit exiting... pass async def file_test_func_file_exit_fast__experimental(tester, menu_item: MenuItemDescription): # not sure how to test this without kit exiting... pass async def file_test_hotkey_func_file_new(tester, menu_item: MenuItemDescription): stage = omni.usd.get_context().get_stage() layer_name = stage.GetRootLayer().identifier if stage else "None" # emulate hotkey await tester.reset_stage_event(omni.usd.StageEventType.OPENED) await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await tester.wait_for_stage_event() # verify its a new layer tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier == layer_name) async def file_test_hotkey_func_file_open(tester, menu_item: MenuItemDescription): # emulate hotkey await tester.reset_stage_event(omni.usd.StageEventType.OPENED) await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(5) async with FileImporterTestHelper() as file_import_helper: dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests") await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda") await tester.wait_for_stage_event() # verify its 4lights tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/").endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda")) async def file_test_hotkey_func_file_save(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await tester.reset_stage_event(omni.usd.StageEventType.SAVED) # emulate hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) expected_size = os.path.getsize(expected_name) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await ui_test.human_delay() # save again, it should not show dialog.... await tester.reset_stage_event(omni.usd.StageEventType.SAVED) await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.S, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) # handle dialog.... save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'") if save_widget: await save_widget.click() await ui_test.human_delay() await tester.wait_for_stage_event() # verify file was saved tester.assertFalse(os.path.getsize(expected_name) == expected_size) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_hotkey_func_file_save_with_options(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await tester.reset_stage_event(omni.usd.StageEventType.SAVED) # emulate hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") expected_size = os.path.getsize(expected_name) tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await ui_test.human_delay() # save again, it should not show dialog.... await tester.reset_stage_event(omni.usd.StageEventType.SAVED) # emulate hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) # handle dialog.... save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'") await save_widget.click() await ui_test.human_delay() await tester.wait_for_stage_event() # verify file was saved tester.assertFalse(os.path.getsize(expected_name) == expected_size) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_hotkey_func_file_save_as(tester, menu_item: MenuItemDescription): tmpdir = tempfile.mkdtemp() await file_test_func_file_open(tester, {}) await tester.reset_stage_event(omni.usd.StageEventType.SAVED) # emulate hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(5) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda") await tester.wait_for_stage_event() # verify its saved to tmpdir expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/") tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name) # cleanup shutil.rmtree(tmpdir, ignore_errors=True) async def file_test_func_file_share(tester, menu_item: MenuItemDescription): # File->Share will only work on omniverse:// files. Currently there is no way to mock this scenario. menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Share").click() pass
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_payload.py
import asyncio import carb import omni.usd import omni.ui as ui from omni.kit import ui_test from omni.kit.menu.utils import MenuItemDescription, MenuLayout async def file_test_func_file_add_reference(tester, menu_item: MenuItemDescription): from carb.input import KeyboardInput menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Add Reference").click() await ui_test.human_delay() dir_widget = ui_test.find("Select File//Frame/**/StringField[*].identifier=='filepicker_directory_path'") await ui_test.human_delay() await dir_widget.input(carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")) await ui_test.human_delay() await tester.find_content_file("Select File", "sphere.usda").click(double=True) await ui_test.human_delay(20) # verify reference was added... stage = omni.usd.get_context().get_stage() prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertTrue(len(prim_list) > 0) async def file_test_func_file_add_payload(tester, menu_item: MenuItemDescription): from carb.input import KeyboardInput menu_widget = ui_test.get_menubar() await menu_widget.find_menu("File").click() await menu_widget.find_menu("Add Payload").click() await ui_test.human_delay() dir_widget = ui_test.find("Select File//Frame/**/StringField[*].identifier=='filepicker_directory_path'") await ui_test.human_delay() await dir_widget.input(carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")) await ui_test.human_delay() await tester.find_content_file("Select File", "sphere.usda").click(double=True) await ui_test.human_delay(20) # verify payload was added... stage = omni.usd.get_context().get_stage() prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()] tester.assertTrue(len(prim_list) > 0)
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/file_tests.py
import sys import re import asyncio import carb import omni.kit.test import omni.kit.helper.file_utils as file_utils from .test_func_media import * from .test_func_payload import * from .test_func_templates import * from .test_recent_menu import test_file_recent_menu_current_stage class TestMenuFile(omni.kit.test.AsyncTestCase): async def setUp(self): self._light_path = carb.tokens.get_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests/4Lights.usda") # load stage so menu shows reopen await omni.usd.get_context().open_stage_async(self._light_path) async def tearDown(self): pass async def test_file_menus(self): import omni.kit.material.library # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() await ui_test.human_delay() menus = omni.kit.menu.utils.get_merged_menus() prefix = "file_test" to_test = [] this_module = sys.modules[__name__] for key in menus.keys(): if key.startswith("File"): for item in menus[key]['items']: if item.name != "" and item.has_action(): key_name = re.sub('\W|^(?=\d)','_', key.lower()) func_name = re.sub('\W|^(?=\d)','_', item.name.replace("${kit}/", "").lower()) while key_name and key_name[-1] == "_": key_name = key_name[:-1] while func_name and func_name[-1] == "_": func_name = func_name[:-1] test_fn = f"{prefix}_func_{key_name}_{func_name}" if test_fn.startswith("file_test_func_file_open_recent_reopen_current_stage"): test_fn = "file_test_func_file_reopen" elif test_fn.startswith("file_test_func_file_open_recent"): continue try: to_call = getattr(this_module, test_fn) to_test.append((to_call, test_fn, item)) except AttributeError: carb.log_error(f"test function \"{test_fn}\" not found") if item.original_menu_item and item.original_menu_item.hotkey: test_fn = f"{prefix}_hotkey_func_{key_name}_{func_name}" try: to_call = getattr(this_module, test_fn) to_test.append((to_call, test_fn, item.original_menu_item)) except AttributeError: carb.log_error(f"test function \"{test_fn}\" not found") self._future_test = None self._required_stage_event = -1 self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.menu.file") # add in any additional tests test_fn = "test_file_recent_menu_current_stage" to_call = getattr(this_module, test_fn) to_test.append((to_call, test_fn, None)) for to_call, test_fn, menu_item in to_test: file_utils.reset_file_event_queue() carb.settings.get_settings().set("/persistent/app/omniverse/lastOpenDirectory", "") carb.settings.get_settings().set("/persistent/app/file_exporter/directory", "") carb.settings.get_settings().set("/persistent/app/file_exporter/filename", "") carb.settings.get_settings().set("/persistent/app/file_exporter/file_extension", "") await self.wait_stage_loading() await omni.usd.get_context().new_stage_async() await ui_test.human_delay() print(f"Running test {test_fn}") await to_call(self, menu_item) self._stage_event_sub = None def find_content_file(self, window_name, filename): for widget in ui_test.find_all(f"{window_name}//Frame/**/TreeView[*]"): for file_widget in widget.find_all(f"**/Label[*]"): if file_widget.widget.text==filename: return file_widget return None def _on_stage_event(self, event): if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done(): self._future_test.set_result(event.type) async def reset_stage_event(self, stage_event): self._required_stage_event = stage_event self._future_test = asyncio.Future() async def wait_for_stage_event(self): async def wait_for_event(): await self._future_test try: await asyncio.wait_for(wait_for_event(), timeout=30.0) except asyncio.TimeoutError: carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}") self._future_test = None self._required_stage_event = -1 async def wait_stage_loading(self): while True: _, files_loaded, total_files = omni.usd.get_context().get_stage_loading_status() if files_loaded or total_files: await ui_test.human_delay() continue break await ui_test.human_delay()
omniverse-code/kit/exts/omni.kit.menu.file/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.1.4] - 2023-01-18 ### Changes - Cancel update task after stage closing. ## [1.1.3] - 2022-11-01 ### Changes - Restored failing test & fixed ## [1.1.2] - 2022-11-01 ### Changes - Remove failing test ## [1.1.1] - 2022-07-19 ### Changes - Disabled contextual greying of menu items ## [1.1.0] - 2022-06-08 ### Changes - Updated menu to use actions ## [1.0.9] - 2022-06-15 ### Changes - Updated unittests. ## [1.0.8] - 2022-05-19 ### Changes - Optimized recents menu rebuilding ## [1.0.7] - 2022-02-23 ### Changes - Removed "Open With Payloads Disabled" from file menu. ## [1.0.6] - 2021-11-25 ### Changes - Only rebuild recent list on stage save/load/open/close events ## [1.0.5] - 2021-08-23 ### Changes - Set menus default order ## [1.0.4] - 2021-07-13 ### Changes - Added "Open With Payloads Disabled" - Added "Add Payload" ## [1.0.3] - 2021-06-21 ### Changes - Moved recents from USDContext ## [1.0.2] - 2021-05-05 ### Changes - Added "Save With Options" ## [1.0.1] - 2020-12-03 ### Changes - Added "Add Reference" ## [1.0.0] - 2020-08-17 ### Changes - Created
omniverse-code/kit/exts/omni.kit.menu.file/docs/index.rst
omni.kit.menu.file ########################### File Menu .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.kit.menu.file/data/tests/4Lights.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (641.3717781423547, 641.3717781423395, 641.3717781423386) double3 target = (0, 0, 0) } dictionary Right = { double3 position = (-50000, 0, -1.1102230246251565e-11) double radius = 500 } dictionary Top = { double3 position = (-4.329780281177466e-12, 50000, 1.1102230246251565e-11) double radius = 500 } string boundCamera = "/OmniverseKit_Persp" } dictionary renderSettings = { double "rtx:post:lensDistortion:cameraFocalLength" = 18.14756202697754 } } defaultPrim = "Stage" metersPerUnit = 0.009999999776482582 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "Stage" { def SphereLight "SphereLight_01" ( prepend apiSchemas = ["ShapingAPI"] kind = "model" ) { float intensity = 30000 float radius = 50 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file double3 xformOp:rotateZYX = (-0, 0, -0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (35.02676, -56.856171, 21.829468) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] } def SphereLight "SphereLight_02" ( prepend apiSchemas = ["ShapingAPI"] kind = "model" ) { float intensity = 30000 float radius = 50 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file double3 xformOp:rotateZYX = (-0, 0, -0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (-52.752319, 105.505402, -52.753021) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] } def SphereLight "SphereLight_03" ( prepend apiSchemas = ["ShapingAPI"] kind = "model" ) { float intensity = 30000 float radius = 50 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file double3 xformOp:rotateZYX = (-0, 0, -0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (99.220299, -3.516879, -95.703514) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] } def SphereLight "SphereLight_00" ( prepend apiSchemas = ["ShapingAPI"] kind = "model" ) { float intensity = 30000 float radius = 50 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file double3 xformOp:rotateZYX = (-0, 0, -0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (-107.755989, 13.481207, 94.274811) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] } def Mesh "Cube" { int[] faceVertexCounts = [4, 4, 4, 4, 4, 4] int[] faceVertexIndices = [0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5] normal3f[] normals = [(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1), (1, 0, 0), (1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)] ( interpolation = "faceVarying" ) point3f[] points = [(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)] float2[] primvars:st = [(1, 0), (0, 0), (0, 1), (1, 1), (1, 0), (1, 1), (0, 1), (0, 0), (1, 0), (0, 0), (0, 1), (1, 1), (1, 0), (0, 0), (0, 1), (1, 1), (1, 0), (1, 1), (0, 1), (0, 0), (1, 0), (1, 1), (0, 1), (0, 0)] ( interpolation = "faceVarying" ) uniform token subdivisionScheme = "none" double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } }
omniverse-code/kit/exts/omni.kit.menu.file/data/tests/sphere.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (0, 0, 0) } dictionary Right = { double3 position = (-50000, 0, -1.1102230246251565e-11) double radius = 500 } dictionary Top = { double3 position = (-4.329780281177466e-12, 50000, 1.1102230246251565e-11) double radius = 500 } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } int refinementOverrideImplVersion = 0 dictionary renderSettings = { float3 "rtx:debugView:pixelDebug:textColor" = (0, 1e18, 0) float3 "rtx:dynamicDiffuseGI:probeCounts" = (6, 6, 6) float3 "rtx:dynamicDiffuseGI:probeGridOrigin" = (-210, -250, -10) float3 "rtx:dynamicDiffuseGI:volumeSize" = (600, 440, 300) float3 "rtx:fog:fogColor" = (0.75, 0.75, 0.75) float3 "rtx:iray:environment_dome_ground_position" = (0, 0, 0) float3 "rtx:iray:environment_dome_ground_reflectivity" = (0, 0, 0) float3 "rtx:iray:environment_dome_rotation_axis" = (0, 1, 0) float3 "rtx:lightspeed:material:overrideAlbedo" = (0.5, 0.5, 0.5) float3 "rtx:lightspeed:material:overrideEmissiveColor" = (0.5, 0.5, 0.5) float3 "rtx:post:backgroundZeroAlpha:backgroundDefaultColor" = (0, 0, 0) float3 "rtx:post:colorcorr:contrast" = (1, 1, 1) float3 "rtx:post:colorcorr:gain" = (1, 1, 1) float3 "rtx:post:colorcorr:gamma" = (1, 1, 1) float3 "rtx:post:colorcorr:offset" = (0, 0, 0) float3 "rtx:post:colorcorr:saturation" = (1, 1, 1) float3 "rtx:post:colorgrad:blackpoint" = (0, 0, 0) float3 "rtx:post:colorgrad:contrast" = (1, 1, 1) float3 "rtx:post:colorgrad:gain" = (1, 1, 1) float3 "rtx:post:colorgrad:gamma" = (1, 1, 1) float3 "rtx:post:colorgrad:lift" = (0, 0, 0) float3 "rtx:post:colorgrad:multiply" = (1, 1, 1) float3 "rtx:post:colorgrad:offset" = (0, 0, 0) float3 "rtx:post:colorgrad:whitepoint" = (1, 1, 1) float3 "rtx:post:lensDistortion:lensFocalLengthArray" = (10, 30, 50) float3 "rtx:post:lensFlares:anisoFlareFalloffX" = (450, 475, 500) float3 "rtx:post:lensFlares:anisoFlareFalloffY" = (10, 10, 10) float3 "rtx:post:lensFlares:cutoffPoint" = (2, 2, 2) float3 "rtx:post:lensFlares:haloFlareFalloff" = (10, 10, 10) float3 "rtx:post:lensFlares:haloFlareRadius" = (75, 75, 75) float3 "rtx:post:lensFlares:isotropicFlareFalloff" = (50, 50, 50) float3 "rtx:post:tonemap:whitepoint" = (1, 1, 1) float3 "rtx:raytracing:inscattering:singleScatteringAlbedo" = (0.9, 0.9, 0.9) float3 "rtx:raytracing:inscattering:transmittanceColor" = (0.5, 0.5, 0.5) float3 "rtx:sceneDb:ambientLightColor" = (0.1, 0.1, 0.1) } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def Sphere "Sphere" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double radius = 50 custom bool refinementEnableOverride = 1 custom int refinementLevel = 2 double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } }
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/PACKAGE-LICENSES/omni.kit.stage.mdl_converter-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/config/extension.toml
[package] version = "1.0.1" authors = ["NVIDIA"] title = "USD Material MDL Export" description="The ability to export USD Material to MDL" readme = "docs/README.md" repository = "" category = "USD" feature = true keywords = ["usd", "mdl", "export", "stage"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" # icon = "data/icon.png" [dependencies] "omni.appwindow" = {} "omni.kit.commands" = {} "omni.kit.context_menu" = {} "omni.kit.pip_archive" = {} "omni.usd" = {} "omni.mdl.usd_converter" = {} "omni.kit.window.filepicker" = {} "omni.kit.widget.filebrowser" = {} [[python.module]] name = "omni.kit.stage.mdl_converter" [[test]] args = [] dependencies = [] stdoutFailPatterns.include = [] stdoutFailPatterns.exclude = []
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/stage_mdl_converter_extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["StageMdlConverterExtension"] from pxr import Sdf import omni.ext import omni.usd import omni.kit.context_menu from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.window.filepicker import FilePickerDialog from omni.kit.window.popup_dialog.message_dialog import MessageDialog import os import omni.ui as ui import asyncio import carb class AskForOverrideDialog(MessageDialog): WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self._style = self._style.copy() # self._style["Background"]["background_color"] = ui.color("#00000000") # self._style["Background"]["border_color"] = ui.color("#00000000") class WarningDialog(MessageDialog): WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class StageMdlConverterExtension(omni.ext.IExt): def on_startup(self, ext_id): app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() self._stage_menu = ext_manager.subscribe_to_extension_enable( on_enable_fn=lambda _: self._register_stage_menu(), on_disable_fn=lambda _: self._unregister_stage_menu(), ext_name="omni.kit.widget.stage", hook_name="omni.kit.stage.mdl_converter", ) self._pick_export_path_dialog = None self._override_dialog = None self._warning_dialog = None self._selected_prim = None self._current_dir = None self._current_export_path = None def on_shutdown(self): self._unregister_stage_menu() self._stage_menu = None self._stage_context_menu_export = None @staticmethod def __on_filter_mdl_files(item: FileBrowserItem) -> bool: """Used by pick folder dialog to hide all the files""" if item and not item.is_folder: _, ext = os.path.splitext(item.path) return (ext in [".mdl"]) return True def __run_export(self): """Do the actual export after we have a filename to export to""" carb.log_info(f"Picked output filename: {self._current_export_path}") asyncio.ensure_future(omni.mdl.usd_converter.usd_to_mdl(self._current_export_path, self._selected_prim)) def __on_ok_override(self, popup): """Called when the the user confirmed to override""" carb.log_info(f"Confirmed to override selected filename: {self._current_export_path}") popup.hide() self.__run_export() def __on_cancel_override(self, popup): """Called when the the user rejected to override""" carb.log_info(f"Rejected to override selected filename: {self._current_export_path}") popup.hide() self._pick_export_path_dialog.refresh_current_directory() self._pick_export_path_dialog.show(path=self._current_export_path) def __on_ok_warning(self, popup): """Called when the the user closes warning dialog""" popup.hide() def __on_apply_filename(self, filename: str, dir: str): """Called when the user press "Export" in the pick filename dialog""" # don't accept as long as no filename is selected if not filename or not dir: return # add the file extension if missing if len(filename) < 5 or filename[-4:] != '.mdl': filename = filename + '.mdl' self._current_dir = dir # add a trailing slash for the client library if(dir[-1] != os.sep): dir = dir + os.sep self._current_export_path = omni.client.combine_urls(dir, filename) self._pick_export_path_dialog.hide() # ask for override or run export directly if os.path.exists(self._current_export_path): carb.log_info(f"WARNING: selected filename already exists: {self._current_export_path}") if self._override_dialog != None: self._override_dialog.destroy() self._override_dialog = AskForOverrideDialog( title = "Confirm override...", message = "The selected file already exists. Do you want to replace it?", ok_label = "Yes", cancel_label = "No", ok_handler = self.__on_ok_override, cancel_handler = self.__on_cancel_override ) # self._override_dialog.build_ui() self._override_dialog.show() else: self.__run_export() def _register_stage_menu(self): """Called when "omni.kit.widget.stage" is loaded""" def on_export(objects: dict): """Called from the context menu""" # keep the selected prim prims = objects.get("prim_list", None) if not prims or len(prims) > 1: return if len(prims) == 1: theprim = prims[0] stage = theprim.GetStage() (status, message) = omni.mdl.usd_converter.is_shader_resolved(stage, theprim) if not status: carb.log_warn(message) if self._warning_dialog != None: self._warning_dialog.destroy() self._warning_dialog = WarningDialog( title = "Convert Material to MDL", message = "WARNING: " + message, disable_cancel_button=True, ok_handler = self.__on_ok_warning, ) self._warning_dialog.show() return if not omni.mdl.usd_converter.is_material_bound_to_prim(stage, theprim): # Material not bound, display warning dialog and do not proceed carb.log_warn(f"Material is not bound to any prim, can not convert") if self._warning_dialog != None: self._warning_dialog.destroy() self._warning_dialog = WarningDialog( title = "Convert Material to MDL", message = "WARNING: Material is not bound to any prim, can not convert", disable_cancel_button=True, ok_handler = self.__on_ok_warning, ) self._warning_dialog.show() return self._selected_prim = prims[0] """Open Pick Folder dialog to add compounds""" if self._pick_export_path_dialog is None: self._pick_export_path_dialog = FilePickerDialog( "Convert Material to MDL and Export As...", allow_multi_selection=False, apply_button_label="Export", click_apply_handler=self.__on_apply_filename, item_filter_options=["MDL Files (*.mdl)"], item_filter_fn=self.__on_filter_mdl_files, # OM-61553: Use the selected material prim name as the default filename current_filename=self._selected_prim.GetName(), current_directory=self._current_dir ) if self._pick_export_path_dialog is not None: self._pick_export_path_dialog.refresh_current_directory() self._pick_export_path_dialog.set_filename(self._selected_prim.GetName()) self._pick_export_path_dialog.show(path=self._current_export_path) # Add context menu to omni.kit.widget.stage context_menu = omni.kit.context_menu.get_instance() if context_menu: menu = { "name": "Export to MDL", "glyph": "menu_save.svg", "show_fn": [context_menu.is_material, context_menu.is_one_prim_selected], "onclick_fn": on_export, "appear_after": "Save Selected", } self._stage_context_menu_export = omni.kit.context_menu.add_menu(menu, "MENU", "omni.kit.widget.stage") def _unregister_stage_menu(self): """Called when "omni.kit.widget.stage" is unloaded""" if self._pick_export_path_dialog: self._pick_export_path_dialog.destroy() self._pick_export_path_dialog = None if self._override_dialog: self._override_dialog.destroy() self._override_dialog = None if self._warning_dialog: self._warning_dialog.destroy() self._warning_dialog = None self._stage_context_menu_export = None
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/__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 .stage_mdl_converter_extension import *
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/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_mdl_converter import *
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/tests/test_mdl_converter.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.kit.stage.mdl_converter import * from pxr import Sdf from pxr import Usd from pxr import UsdGeom import omni.kit.test class Test(omni.kit.test.AsyncTestCase): async def test_mdl_converter(self): """Testing omni.kit.stage.mdl_converter""" self.assertEqual(True, True)
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/docs/CHANGELOG.md
# CHANGELOG The ability to export USD Material to MDL. ## [1.0.1] - 2022-05-31 - Changed "Export Selected" to "Save Selected" ## [1.0.0] - 2022-02-10 ### Added
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/docs/README.md
# USD Material MDL Export. This extension adds a context menu item "Export to MDL" to the stage window. It shows when right-clicking a (single) selected material node. When the new menu item is chosen, the user is prompted for a destination MDL filename. The selected USD material is then converted to an MDL material and saved to the selected destination in a new MDL module. ## Issues and limitation - The USD material needs to be bound to geometry in order to be fully available to the renderer and ready for export. - Resources that are exported with the material are not overridden if files with the name exists already. Instead, new filenames are generated for those resources. This also applies when exporting a USD material to the same MDL file multiple times. ## Screenshot
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/docs/index.rst
omni.kit.stage.mdl_converter ############################ .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.kit.capture/PACKAGE-LICENSES/omni.kit.capture-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.capture/config/extension.toml
[package] category = "Rendering" changelog = "docs/CHANGELOG.md" description = "An extension to capture Kit viewport into images and videos." icon = "data/icon.svg" preview_image = "data/preview.png" readme = "docs/README.md" title = "Kit Image and Video Capture" version = "0.5.1" [dependencies] "omni.usd" = {} "omni.timeline" = {} "omni.ui" = {} "omni.videoencoding" = {} "omni.kit.viewport.utility" = {} "omni.kit.renderer.capture" = { optional=true } [[python.module]] name = "omni.kit.capture" [[test]] dependencies = [ "omni.kit.renderer.capture", "omni.kit.window.viewport", ] waiver = "extension is being deprecated" unreliable = true