file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/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.test/omni/graph/test/tests/test_reparent_graph.py
"""Tests reparenting workflows""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd # ====================================================================== class TestReparentGraph(ogts.OmniGraphTestCase): """Run tests that exercises the reparenting of graph and checks that fabric is cleaned up properly this is separate from test_rename_and_reparent.py tests because of different settings need via OmniGraphDefaultTestCase in order for legacy prims to be added to fabric. """ async def test_reparent_fabric(self): """Test basic reparenting a graph back away and then back to original parent.""" flags = [] world_graph_key = '"/World/ActionGraph"' xform_graph_key = '"/World/Xform/ActionGraph"' # Load the test scene which has /World/ActionGraph and /World/Xform (result, error) = await ogts.load_test_file("TestReparentGraph.usda", use_caller_subdirectory=True) self.assertTrue(result, error) # Verify that fabric has "/World/ActionGraph" and not "/World/Xform/ActionGraph" self.assertEqual(len(og.get_compute_graph_contexts()), 1) ctx = og.get_compute_graph_contexts()[0] post_load_fabric = og.OmniGraphInspector().as_json(ctx, flags=flags) self.assertTrue(post_load_fabric.find(world_graph_key) >= 0) self.assertTrue(post_load_fabric.find(xform_graph_key) == -1) # Reparent the graph to the Xform omni.kit.commands.execute("MovePrim", path_from="/World/ActionGraph", path_to="/World/Xform/ActionGraph") await omni.kit.app.get_app().next_update_async() # Verify that fabric no longer has "/World/ActionGraph" and now has "/World/Xform/ActionGraph" self.assertEqual(len(og.get_compute_graph_contexts()), 1) ctx = og.get_compute_graph_contexts()[0] post_reparent_to_xform_fabric = og.OmniGraphInspector().as_json(ctx, flags=flags) self.assertTrue(post_reparent_to_xform_fabric.find(world_graph_key) == -1) self.assertTrue(post_reparent_to_xform_fabric.find(xform_graph_key) >= 0)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_abi_attribute.py
"""Runs tests on the ABIs in the Python bindings""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import usdrt from pxr import Sdf, Usd # ============================================================================================================== class TestAttributePythonBindings(ogts.OmniGraphTestCase): async def test_abi(self): """Tests that the bindings for omni.graph.core.Attribute operate as expected""" interface = og.Attribute ogts.validate_abi_interface( interface, instance_methods=[ "connect", "connectEx", "connectPrim", "deprecation_message", "disconnect", "disconnectPrim", "get_all_metadata", "get_array", "get_attribute_data", "get_disable_dynamic_downstream_work", "get_downstream_connection_count", "get_downstream_connections_info", "get_downstream_connections", "get_extended_type", "get_handle", "get_metadata_count", "get_metadata", "get_name", "get_node", "get_path", "get_port_type", "get_resolved_type", "get_type_name", "get_union_types", "get_upstream_connection_count", "get_upstream_connections_info", "get_upstream_connections", "get", "is_array", "is_compatible", "is_connected", "is_deprecated", "is_dynamic", "is_runtime_constant", "is_valid", "register_value_changed_callback", "set_default", "set_disable_dynamic_downstream_work", "set_metadata", "set_resolved_type", "set", "update_attribute_value", ], static_methods=[ "ensure_port_type_in_name", "get_port_type_from_name", "remove_port_type_from_name", "write_complete", ], properties=[ "gpu_ptr_kind", "is_optional_for_compute", ], constants=[ ("resolved_prefix", str), ], ) # TODO: Now that we've confirmed the functions exist we also need to confirm that they work # -------------------------------------------------------------------------------------------------------------- async def test_constants(self): """Test that the constants in the Attribute interface work as expected""" self.assertEqual(og.Attribute.resolved_prefix, "__resolved_") # -------------------------------------------------------------------------------------------------------------- async def test_properties(self): """Test that the properties in the Attribute interface work as expected""" (_, (node,), _, _) = og.Controller.edit( "/TestGraph", {og.Controller.Keys.CREATE_NODES: ("TestNode", "omni.graph.test.PerturbPointsGpu")} ) attr_points = og.Controller.attribute("inputs:points", node) self.assertEqual(attr_points.gpu_ptr_kind, og.PtrToPtrKind.NA) attr_points.gpu_ptr_kind = og.PtrToPtrKind.GPU self.assertEqual(attr_points.gpu_ptr_kind, og.PtrToPtrKind.GPU) self.assertFalse(attr_points.is_optional_for_compute) attr_points.is_optional_for_compute = True self.assertTrue(attr_points.is_optional_for_compute) # -------------------------------------------------------------------------------------------------------------- async def test_static_methods(self): """Test that the static methods of the Attribute interface work as expected""" interface = og.Attribute p_in = og.AttributePortType.INPUT p_out = og.AttributePortType.OUTPUT p_state = og.AttributePortType.STATE # -------------------------------------------------------------------------------------------------------------- # Test Attribute.ensure_port_type_in_name # Test data is a list of (expected_output, name_input, port_type, is_bundle) test_data = [ ("inputs:attr", "inputs:attr", p_in, False), ("outputs:attr", "outputs:attr", p_out, False), ("state:attr", "state:attr", p_state, False), ("inputs:attr", "inputs:attr", p_in, True), ("outputs_attr", "outputs_attr", p_out, True), ("state_attr", "state_attr", p_state, True), ("inputs:attr", "attr", p_in, False), ("outputs:attr", "attr", p_out, False), ("state:attr", "attr", p_state, False), ("inputs:attr", "attr", p_in, True), ("outputs_attr", "attr", p_out, True), ("state_attr", "attr", p_state, True), ("inputs:attr:first", "inputs:attr:first", p_in, False), ("outputs:attr:first", "outputs:attr:first", p_out, False), ("state:attr:first", "state:attr:first", p_state, False), ("inputs:attr:first", "inputs:attr:first", p_in, True), ("outputs_attr_first", "outputs_attr_first", p_out, True), ("state_attr_first", "state_attr_first", p_state, True), ] for (expected, original, port_type, is_bundle) in test_data: msg = f"ensure_port_type_in_name({expected}, {original}, {port_type}, {is_bundle})" self.assertEqual(expected, interface.ensure_port_type_in_name(original, port_type, is_bundle), msg) # -------------------------------------------------------------------------------------------------------------- # Test Attribute.get_port_type_from_name # Test data is a list of (expected_result, name_input) test_data = [ (og.AttributePortType.INPUT, "inputs:attr"), (og.AttributePortType.OUTPUT, "outputs:attr"), (og.AttributePortType.STATE, "state:attr"), (og.AttributePortType.INPUT, "inputs:attr"), (og.AttributePortType.OUTPUT, "outputs_attr"), (og.AttributePortType.STATE, "state_attr"), (og.AttributePortType.UNKNOWN, "input:attr"), ] for (expected, original) in test_data: msg = f"get_port_type_from_name({expected}, {original})" self.assertEqual(expected, interface.get_port_type_from_name(original), msg) # -------------------------------------------------------------------------------------------------------------- # Test Attribute.remove_port_type_from_name # Test data is a list of (expected_output, name_input, port_type, is_bundle) test_data = [ ("attr", "inputs:attr", False), ("attr", "outputs:attr", False), ("attr", "state:attr", False), ("attr", "inputs:attr", True), ("attr", "outputs_attr", True), ("attr", "state_attr", True), ("attr", "attr", False), ("attr", "attr", False), ("attr", "attr", False), ("attr", "attr", True), ("attr", "attr", True), ("attr", "attr", True), ("attr:first", "inputs:attr:first", False), ("attr:first", "outputs:attr:first", False), ("attr:first", "state:attr:first", False), ("attr:first", "inputs:attr:first", True), ("attr_first", "outputs_attr_first", True), ("attr_first", "state_attr_first", True), ("input:attr", "input:attr", False), ("input:attr", "input:attr", True), ("output:attr", "output:attr", False), ("output_attr", "output_attr", True), ("attr", "attr", False), ("attr", "attr", True), ] for (expected, original, is_bundle) in test_data: msg = f"remove_port_type_from_name({expected}, {original}, {is_bundle})" self.assertEqual(expected, interface.remove_port_type_from_name(original, is_bundle), msg) # -------------------------------------------------------------------------------------------------------------- # Test Attribute.write_complete # There's no easy way to judge that this worked as expected so instead just confirm that it returns okay (_, (node,), _, _) = og.Controller.edit( "/TestGraph", {og.Controller.Keys.CREATE_NODES: ("TestNode", "omni.graph.test.TestAllDataTypes")} ) attrs = [ og.Controller.attribute(name, node) for name in ["outputs:a_bool", "outputs:a_float", "outputs:a_double"] ] self.assertTrue(all(attr.is_valid() for attr in attrs)) interface.write_complete(attrs) interface.write_complete(tuple(attrs)) # -------------------------------------------------------------------------------------------------------------- async def test_target_attribute_setting(self): """Tests various forms of setting an attribute with a target type""" (_, (node,), _, _) = og.Controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: ("TestNode", "omni.graph.nodes.GetPrimPaths"), og.Controller.Keys.CREATE_PRIMS: [("/World/Prim1", "Xform"), ("/World/Prim2", "Xform")], }, ) attr = og.Controller.attribute("inputs:prims", node) # string og.Controller.set(attr, "/World/Prim1") self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim1")]) # Sdf.Path og.Controller.set(attr, Sdf.Path("/World/Prim2")) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim2")]) # usdrt.Sdf.Path og.Controller.set(attr, usdrt.Sdf.Path("/World/Prim1")) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim1")]) # string list og.Controller.set(attr, ["/World/Prim1", "/World/Prim2"]) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim1"), usdrt.Sdf.Path("/World/Prim2")]) # Sdf.Path list og.Controller.set(attr, [Sdf.Path("/World/Prim2"), Sdf.Path("/World/Prim1")]) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim2"), usdrt.Sdf.Path("/World/Prim1")]) # usdrt.Sdf.Path list og.Controller.set(attr, [usdrt.Sdf.Path("/World/Prim1"), usdrt.Sdf.Path("/World/Prim2")]) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim1"), usdrt.Sdf.Path("/World/Prim2")]) # empty list og.Controller.set(attr, []) self.assertEqual(og.Controller.get(attr), []) # mixed list og.Controller.set(attr, [Sdf.Path("/World/Prim2"), "/World/Prim1"]) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim2"), usdrt.Sdf.Path("/World/Prim1")]) # graph target path og.Controller.set(attr, og.INSTANCING_GRAPH_TARGET_PATH) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path(og.INSTANCING_GRAPH_TARGET_PATH)]) # validate non-sdf paths throw omni.kit.commands.set_logging_enabled(False) with self.assertRaises(og.OmniGraphError): og.Controller.set(attr, 5) with self.assertRaises(og.OmniGraphError): og.Controller.set(attr, "!a non valid sdf path") with self.assertRaises(og.OmniGraphError): og.Controller.set(attr, ["/World/Prim1", 5]) with self.assertRaises(og.OmniGraphError): og.Controller.set(attr, (usdrt.Sdf.Path("/World/Prim1"), usdrt.Sdf.Path("/World/Prim2"))) omni.kit.commands.set_logging_enabled(True) # -------------------------------------------------------------------------------------------------------------- async def test_objectlookup_attribute_with_paths(self): """Tests that og.Controller.attribute works with both strings and Sdf.Path objects for all types""" (_, (node,), _, _) = og.Controller.edit( "/TestGraph", {og.Controller.Keys.CREATE_NODES: ("TestNode", "omni.graph.test.TestAllDataTypes")} ) for attr in node.get_attributes(): if attr.get_port_type() not in ( og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ): continue path = attr.get_path() self.assertEquals(attr, og.Controller.attribute(str(path))) self.assertEquals(attr, og.Controller.attribute(Sdf.Path(path))) # -------------------------------------------------------------------------------------------------------------- async def test_objectlookup_usd_object_from_attributes(self): """Tests that og.ObjectLookup finds the correct usd object from an attribute""" controller = og.Controller(update_usd=True) keys = controller.Keys (_, (node,), _, _) = controller.edit( "/TestGraph", {keys.CREATE_NODES: ("TestNode", "omni.graph.test.TestAllDataTypes")} ) for attr in node.get_attributes(): port_type = attr.get_port_type() if port_type not in ( og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ): continue # the exception is bundle outputs. They are neither attributes nor relationships. attribute_type = og.Controller.attribute_type(attr) if ( port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT and attribute_type.role == og.AttributeRole.BUNDLE ): with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(attr) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_relationship(attr) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_property(attr) continue # everything else is an attribute or relationship path = attr.get_path() usd_property = og.ObjectLookup.usd_property(attr) self.assertTrue(usd_property.IsValid()) self.assertEqual(usd_property, og.ObjectLookup.usd_property(Sdf.Path(path))) self.assertEqual(usd_property, og.ObjectLookup.usd_property(str(path))) # validate the property is a relationship or an attribute and that the corresponding inverse calls fail for item in [attr, Sdf.Path(path), str(path)]: if isinstance(usd_property, Usd.Relationship): self.assertEqual(usd_property, og.ObjectLookup.usd_relationship(item)) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(item) else: self.assertEqual(usd_property, og.ObjectLookup.usd_attribute(item)) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_relationship(item)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_subgraphs.py
"""Tests relating to management of OmniGraph graphs and subgraphs""" import tempfile from pathlib import Path import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit import omni.usd class TestOmniGraphSubgraphs(ogts.OmniGraphTestCase): async def test_execution_subgraph_in_push_graph(self): """Verify the push evaluator ticks the execution subgraph""" controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() (graph, _, _, _) = controller.edit("/World/TestGraph") subgraph_path = "/World/TestGraph/exec_sub" graph.create_subgraph(subgraph_path, evaluator="execution") subgraph = graph.get_subgraph(subgraph_path) self.assertTrue(subgraph.is_valid()) controller.edit( subgraph, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("FlipFlop", "omni.graph.action.FlipFlop"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: ("Prim1", {"attrBool": ("bool", False)}), keys.CONNECT: [ ("OnTick.outputs:tick", "FlipFlop.inputs:execIn"), ("FlipFlop.outputs:a", "Set.inputs:execIn"), ("FlipFlop.outputs:b", "Set.inputs:execIn"), ("FlipFlop.outputs:isA", "Set.inputs:value"), ], keys.SET_VALUES: [ ("Set.inputs:primPath", "/Prim1"), ("Set.inputs:name", "attrBool"), ("Set.inputs:usePath", True), ("OnTick.inputs:onlyPlayback", False), ], }, ) await og.Controller.evaluate() sub_ff_node = subgraph_path + "/FlipFlop" sub_flipflop_node = subgraph.get_node(sub_ff_node) self.assertTrue(sub_flipflop_node.is_valid()) # Check the flip-flop is being toggled and that attribs are being flushed to USD ff_state_0 = og.Controller.get(controller.attribute("outputs:isA", sub_ff_node)) self.assertEqual(stage.GetPropertyAtPath("/Prim1.attrBool").Get(), ff_state_0) await og.Controller.evaluate() ff_state_1 = og.Controller.get(controller.attribute("outputs:isA", sub_ff_node)) self.assertNotEqual(ff_state_0, ff_state_1) self.assertEqual(stage.GetPropertyAtPath("/Prim1.attrBool").Get(), ff_state_1) # -------------------------------------------------------------------------------------------------------------- async def test_multiple_schema_root_graphs(self): """Check that a configuration with more than one root level graph can be created, saved, and loaded. This test creates three root-level graphs and then executes all of them to confirm that they are working properly. Each graph is a simple addition sequence, where one is an action graph to confirm that different graphs can use different evaluators. Const1 ---v Add ---> SimpleData Const2 ---^ OnTick --> Counter """ keys = og.Controller.Keys (graph_1, (const_nodea_1, const_nodeb_1, _, simple_data_node_1), _, _) = og.Controller.edit( "/Graph1", { keys.CREATE_NODES: [ ("ConstA", "omni.graph.nodes.ConstantInt"), ("ConstB", "omni.graph.nodes.ConstantInt"), ("Add", "omni.graph.nodes.Add"), ("SimpleData", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("ConstA.inputs:value", "Add.inputs:a"), ("ConstB.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "SimpleData.inputs:a_int"), ], keys.SET_VALUES: [ ("ConstA.inputs:value", 3), ("ConstB.inputs:value", 7), ], }, ) simple_data_node_1_path = simple_data_node_1.get_prim_path() graph_1_path = graph_1.get_path_to_graph() (graph_2, (const_nodea_2, const_nodeb_2, _, simple_data_node_2), _, _) = og.Controller.edit( "/Graph2", { keys.CREATE_NODES: [ ("ConstA", "omni.graph.nodes.ConstantInt"), ("ConstB", "omni.graph.nodes.ConstantInt"), ("Add", "omni.graph.nodes.Add"), ("SimpleData", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("ConstA.inputs:value", "Add.inputs:a"), ("ConstB.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "SimpleData.inputs:a_int"), ], keys.SET_VALUES: [ ("ConstA.inputs:value", 33), ("ConstB.inputs:value", 77), ], }, ) simple_data_node_2_path = simple_data_node_2.get_prim_path() graph_2_path = graph_2.get_path_to_graph() (graph_3, (ontick_node, counter_node), _, _) = og.Controller.edit( { "graph_path": "/Graph3", "evaluator_name": "execution", }, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Counter", "omni.graph.action.Counter"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Counter.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ], }, ) counter_node_path = counter_node.get_prim_path() graph_3_path = graph_3.get_path_to_graph() # ============================================================================================================== # OM-52190 specifies work that will prevent the need for this temporary setting. Without it, the values being # set onto the attributes will not be part of USD, and hence will not be saved out to the file, # causing the second half of the test to fail. stage = omni.usd.get_context().get_stage() stage.GetPrimAtPath(const_nodea_1.get_prim_path()).GetAttribute("inputs:value").Set(3) stage.GetPrimAtPath(const_nodeb_1.get_prim_path()).GetAttribute("inputs:value").Set(7) stage.GetPrimAtPath(const_nodea_2.get_prim_path()).GetAttribute("inputs:value").Set(33) stage.GetPrimAtPath(const_nodeb_2.get_prim_path()).GetAttribute("inputs:value").Set(77) stage.GetPrimAtPath(ontick_node.get_prim_path()).GetAttribute("inputs:onlyPlayback").Set(False) # ============================================================================================================== await og.Controller.evaluate([graph_1, graph_2, graph_3]) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_1)).get(), 10) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_2)).get(), 110) self.assertTrue(og.Controller(("state:count", counter_node)).get() > 0) with tempfile.TemporaryDirectory() as tmpdirname: await omni.kit.app.get_app().next_update_async() # save the file tmp_file_path = Path(tmpdirname) / "tmp.usda" result = omni.usd.get_context().save_as_stage(str(tmp_file_path)) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload the file back (result, error) = await ogts.load_test_file(str(tmp_file_path)) self.assertTrue(result, error) graph_1 = og.get_graph_by_path(graph_1_path) graph_2 = og.get_graph_by_path(graph_2_path) graph_3 = og.get_graph_by_path(graph_3_path) simple_data_node_1 = og.get_node_by_path(simple_data_node_1_path) simple_data_node_2 = og.get_node_by_path(simple_data_node_2_path) counter_node = og.get_node_by_path(counter_node_path) self.assertIsNotNone(simple_data_node_1) self.assertIsNotNone(simple_data_node_2) self.assertIsNotNone(counter_node) await og.Controller.evaluate([graph_1, graph_2, graph_3]) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_1)).get(), 10) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_2)).get(), 110) self.assertTrue(og.Controller(("state:count", counter_node)).get() > 0)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_commands.py
"""Tests for the various OmniGraph commands""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.usd class TestOmniGraphCommands(ogts.OmniGraphTestCase): # ---------------------------------------------------------------------- async def test_disable_node_command(self): # The basic idea of the test is as follows: # We load up the TestTranslatingCube.usda file, which has a cube # that continually moves in X. We make sure first the # node is working, and then we disable the node. Once we do # that, we make sure cube no longer move as the node should be # disabled. (result, error) = await ogts.load_test_file("TestTranslatingCube.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = og.get_graph_by_path("/World/moveX") # make sure the box and the attribute we expect are there. usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") translate_attr = cube_prim.GetAttribute("xformOp:translate") self.assertTrue(translate_attr.IsValid()) # !!make a copy as the above is a reference of the data, that will change the next frame!! translate = translate_attr.Get() t0 = translate[0] # wait 1 frame await omni.kit.app.get_app().next_update_async() # get the updated cube position and make sure it moved translate = translate_attr.Get() t1 = translate[0] diff = abs(t1 - t0) self.assertGreater(diff, 0.1) # disable the node subtract_node = graph.get_node("/World/moveX/subtract") # we're piggy backing off this test to also test that the inputs and outputs of this node are # properly categorized (so this part is separate from the main test) input_attr = subtract_node.get_attribute("inputs:a") self.assertEqual(input_attr.get_port_type(), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) output_attr = subtract_node.get_attribute("outputs:out") self.assertEqual(output_attr.get_port_type(), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) og.cmds.DisableNode(node=subtract_node) # wait another frame, but this time make sure there is no moving of the cube await omni.kit.app.get_app().next_update_async() translate = translate_attr.Get() diff = abs(translate[0] - t1) self.assertEqual(diff, 0, 0.01) # ---------------------------------------------------------------------- async def verify_example_graph_disabled(self): """ basic idea behind this test: load up the translating cubes sample. The file is set initially such that the graph is disabled. We'll run the command to enable and disable the graph a bunch of times, each time checking the position of the moving cube. """ graph = og.get_all_graphs()[0] self.assertTrue(graph.is_disabled()) translate_attr = og.Controller.usd_attribute("/World/Cube.xformOp:translate") # initial position of cube should have x = 0.0. Since the graph is initially # disabled, this should remain the case: translate = translate_attr.Get() self.assertAlmostEqual(translate[0], 0.0, places=1) og.cmds.EnableGraph(graph=graph) self.assertFalse(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -1.0, places=1) omni.kit.undo.undo() self.assertTrue(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -1.0, places=1) omni.kit.undo.redo() self.assertFalse(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -2.0, places=1) og.cmds.DisableGraph(graph=graph) self.assertTrue(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -2.0, places=1) omni.kit.undo.undo() self.assertFalse(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -3.0, places=1) omni.kit.undo.redo() self.assertTrue(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -3.0, places=1) # ---------------------------------------------------------------------- async def verify_example_graph_rename(self): """ This test checks if renaming a graph will update the scene properly and keep the USD scene, the graph, and the fabric are in sync throughout two different renaming commands and their undos. """ graph_path = "/World/moveX" renamed_path = f"{graph_path}Renamed" graph = og.Controller.graph(graph_path) self.assertTrue(graph.is_valid()) usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") translate_attr = cube_prim.GetAttribute("xformOp:translate") self.assertTrue(translate_attr.IsValid()) # verify graph updates at the beginning await og.Controller.evaluate() translate = og.Controller.get(og.Controller.attribute(f"{graph_path}/compose.outputs:double3")) self.assertAlmostEqual(translate[0], -3.0, places=1) # Rename using MovePrimCommand omni.kit.commands.execute("MovePrim", path_from=graph_path, path_to=renamed_path) await omni.kit.app.get_app().next_update_async() graph = og.Controller.graph(graph_path) self.assertTrue(graph is None or not graph.is_valid()) graph = og.Controller.graph(renamed_path) self.assertTrue(graph.is_valid()) # verify graph update after rename translate = og.Controller.get(og.Controller.attribute(f"{renamed_path}/compose.outputs:double3")) self.assertAlmostEqual(translate[0], -4.0, places=1) # verify graph update after undo omni.kit.undo.undo() await omni.kit.app.get_app().next_update_async() graph = og.Controller.graph(renamed_path) self.assertTrue(graph is None or not graph.is_valid()) graph = og.Controller.graph(graph_path) self.assertTrue(graph.is_valid()) translate = og.Controller.get(og.Controller.attribute(f"{graph_path}/compose.outputs:double3")) self.assertAlmostEqual(translate[0], -5.0, places=1) # ---------------------------------------------------------------------- async def test_rename_graph_command(self): (result, error) = await ogts.load_test_file("TestTranslatingCube.usda", use_caller_subdirectory=True) self.assertTrue(result, error) await self.verify_example_graph_rename() # ---------------------------------------------------------------------- async def test_set_attr_command_v2(self): (result, error) = await ogts.load_test_file("TestTranslatingCube.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = og.get_graph_by_path("/World/moveX") subtract_node = graph.get_node("/World/moveX/subtract") b_attr = subtract_node.get_attribute("inputs:b") og.cmds.SetAttr(attr=b_attr, value=8.8) value = og.Controller.get(b_attr) self.assertAlmostEqual(value, 8.8, places=2) # Test is flaky. Disable this part for now to see if it's to blame # omni.kit.undo.undo() # value = og.Controller.get(multiplier_attr) # self.assertAlmostEqual(value, old_value, places=2) # omni.kit.undo.redo() # value = og.Controller.get(multiplier_attr) # self.assertAlmostEqual(value, 8.8, places=2)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_listener.py
"""Tests for OmniGraph Usd Listener """ import tempfile from pathlib import Path import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd # ====================================================================== class TestOmniGraphUsdListener(ogts.OmniGraphTestCase): """Test for omni graph usd listener""" async def test_reparent_target_of_path_attribute(self): """Listener is required to update attributes with role set to path, when its target changes location""" controller = og.Controller() keys = og.Controller.Keys (_, create_nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [("ConstantPath", "omni.graph.nodes.ConstantPath")], keys.CREATE_PRIMS: [("/Cube", "Cube"), ("/Xform", "Xform")], }, ) constant_path_node = create_nodes[0] value_attribute = constant_path_node.get_attribute("inputs:value") value_attribute.set("/Cube") # MovePrim command in this case will cause 'didAddNonInertPrim' and 'didRemoveNonInertPrim' flags to be # populated and reparenting takes place omni.kit.commands.execute("MovePrim", path_from="/Cube", path_to="/Xform/Cube") value = value_attribute.get() self.assertEqual(value, "/Xform/Cube") with tempfile.TemporaryDirectory() as tmp_dir_name: await omni.kit.app.get_app().next_update_async() # save tmp_file_path = Path(tmp_dir_name) / "tmp.usda" result = omni.usd.get_context().save_as_stage(str(tmp_file_path)) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload (result, error) = await ogts.load_test_file(str(tmp_file_path)) self.assertTrue(result, error) constant_path_node = og.get_node_by_path("/TestGraph/ConstantPath") value_attribute = constant_path_node.get_attribute("inputs:value") self.assertEqual(value_attribute.get(), "/Xform/Cube") async def test_rename_target_of_path_attribute(self): """Listener is required to update attributes with role set to path, when its target changes path""" controller = og.Controller() keys = og.Controller.Keys (_, create_nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [("ConstantPath", "omni.graph.nodes.ConstantPath")], keys.CREATE_PRIMS: [("/Cube", "Cube")], }, ) constant_path_node = create_nodes[0] value_attribute = constant_path_node.get_attribute("inputs:value") value_attribute.set("/Cube") for src_dst in (("/Cube", "/Cube1"), ("/Cube1", "/Cube2"), ("/Cube2", "/Cube3")): omni.kit.commands.execute("MovePrim", path_from=src_dst[0], path_to=src_dst[1]) self.assertEqual(value_attribute.get(), src_dst[1]) with tempfile.TemporaryDirectory() as tmp_dir_name: await omni.kit.app.get_app().next_update_async() # save tmp_file_path = Path(tmp_dir_name) / "tmp.usda" result = omni.usd.get_context().save_as_stage(str(tmp_file_path)) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload (result, error) = await ogts.load_test_file(str(tmp_file_path)) self.assertTrue(result, error) constant_path_node = og.get_node_by_path("/TestGraph/ConstantPath") value_attribute = constant_path_node.get_attribute("inputs:value") self.assertEqual(value_attribute.get(), src_dst[1]) async def test_extended_path_type(self): """Resolve extended type to path and confirm that has been subscribed to the listener""" class TestExtendedPathABIPy: @staticmethod def compute(db): return True @staticmethod def get_node_type() -> str: return "omni.graph.tests.TestExtendedPathABIPy" @staticmethod def initialize_type(node_type): node_type.add_extended_input( "inputs:extended_input", "path,token", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) return True og.register_node_type(TestExtendedPathABIPy, 1) controller = og.Controller() keys = og.Controller.Keys (_, create_nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [("TestExtendedPath", "omni.graph.tests.TestExtendedPathABIPy")], keys.CREATE_PRIMS: [("/Cube", "Cube")], }, ) extended_node = create_nodes[0] extended_input = extended_node.get_attribute("inputs:extended_input") # set resolved type to path extended_input.set_resolved_type(og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.PATH)) self.assertEqual(extended_input.get_resolved_type().role, og.AttributeRole.PATH) extended_input.set("/Cube") self.assertEqual(extended_input.get(), "/Cube") omni.kit.commands.execute("MovePrim", path_from="/Cube", path_to="/Cube1") value = extended_input.get() self.assertEqual(value, "/Cube1")
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_import_nodes.py
import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.usd from pxr import Gf, UsdGeom class TestImportNodes(ogts.OmniGraphTestCase): TEST_GRAPH_PATH = "/World/TestGraph" async def test_import_time_samples(self): await self._test_import_time_samples_impl("omni.graph.nodes.ReadPrimsV2") async def test_import_time_samples_legacy(self): await self._test_import_time_samples_impl("omni.graph.nodes.ReadPrims") async def _test_import_time_samples_impl(self, read_prims_node_type: str): """Verify that time sample data is correctly imported""" (result, error) = await ogts.load_test_file("TestUSDTimeCode.usda", use_caller_subdirectory=True) self.assertTrue(result, f"{error}") controller = og.Controller() keys = og.Controller.Keys (_, nodes, cube, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ReadPrimsBundle", "omni.graph.nodes.ReadPrimsBundle"), ("ReadAttr", "omni.graph.nodes.ReadPrimAttribute"), ("ExtractRPB", "omni.graph.nodes.ExtractBundle"), ("ExtractRP", "omni.graph.nodes.ExtractBundle"), ("ExtractPrimRPB", "omni.graph.nodes.ExtractPrim"), ("ExtractPrimRP", "omni.graph.nodes.ExtractPrim"), ("ReadPrims", read_prims_node_type), ("Const", "omni.graph.nodes.ConstantDouble"), ("Const2", "omni.graph.nodes.ConstantDouble"), ], keys.CREATE_PRIMS: [ ("/World/Cube2", "Cube"), ], keys.SET_VALUES: [ ("ReadAttr.inputs:usePath", True), ("ReadAttr.inputs:primPath", "/World/Cube"), ("ExtractPrimRPB.inputs:primPath", "/World/Cube"), ("ExtractPrimRP.inputs:primPath", "/World/Cube"), ("ReadAttr.inputs:name", "size"), ("ReadAttr.inputs:usdTimecode", 0), ("ReadPrimsBundle.inputs:usdTimecode", 0), ("ReadPrims.inputs:usdTimecode", 0), ], keys.CONNECT: [ ("ReadPrimsBundle.outputs_primsBundle", "ExtractPrimRPB.inputs:prims"), ("ExtractPrimRPB.outputs_primBundle", "ExtractRPB.inputs:bundle"), ("ReadPrims.outputs_primsBundle", "ExtractPrimRP.inputs:prims"), ("ExtractPrimRP.outputs_primBundle", "ExtractRP.inputs:bundle"), ], }, ) stage = omni.usd.get_context().get_stage() input_prim_prop = stage.GetPropertyAtPath("/TestGraph/ReadPrimsBundle.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=input_prim_prop, target="/World/Cube") input_prim_prop = stage.GetPropertyAtPath("/TestGraph/ReadPrims.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=input_prim_prop, target="/World/Cube") # evaluate so dynamic attributes are created await controller.evaluate() # connect the size attribute so it gets updated controller.edit( "/TestGraph", { keys.CONNECT: [ ("ExtractRPB.outputs:size", "Const.inputs:value"), ("ExtractRP.outputs:size", "Const2.inputs:value"), ] }, ) cs = 10 cube_size = cube[0].GetProperty("size") cube_size.Set(cs) await controller.evaluate() out_from_read_attr = nodes[1].get_attribute("outputs:value") out_from_read_prims_bundle = nodes[2].get_attribute("outputs:size") out_from_read_prims = nodes[3].get_attribute("outputs:size") self.assertTrue(out_from_read_attr.get() == 100) self.assertTrue(out_from_read_prims_bundle.get() == 100) self.assertTrue(out_from_read_prims.get() == 100) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("ReadAttr.inputs:usdTimecode", 25), ("ReadPrimsBundle.inputs:usdTimecode", 25), ("ReadPrims.inputs:usdTimecode", 25), ] }, ) await controller.evaluate() self.assertTrue(out_from_read_attr.get() == 50) self.assertTrue(out_from_read_prims_bundle.get() == 50) self.assertTrue(out_from_read_prims.get() == 50) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("ReadAttr.inputs:usdTimecode", 50), ("ReadPrimsBundle.inputs:usdTimecode", 50), ("ReadPrims.inputs:usdTimecode", 50), ] }, ) await controller.evaluate() self.assertTrue(out_from_read_attr.get() == 1) self.assertTrue(out_from_read_prims_bundle.get() == 1) self.assertTrue(out_from_read_prims.get() == 1) # now check that if we change the targets, the values correctly update controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("ReadAttr.inputs:primPath", "/World/Cube2"), ("ExtractPrimRPB.inputs:primPath", "/World/Cube2"), ("ExtractPrimRP.inputs:primPath", "/World/Cube2"), ] }, ) input_prim_prop = stage.GetPropertyAtPath("/TestGraph/ReadPrimsBundle.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=input_prim_prop, target="/World/Cube2") input_prim_prop = stage.GetPropertyAtPath("/TestGraph/ReadPrims.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=input_prim_prop, target="/World/Cube2") await controller.evaluate() self.assertTrue(out_from_read_attr.get() == cs) self.assertTrue(out_from_read_prims_bundle.get() == cs) self.assertTrue(out_from_read_prims.get() == cs) async def test_import_matrix_and_bbox(self): await self._test_import_matrix_and_bbox_impl("omni.graph.nodes.ReadPrimsV2") async def test_import_matrix_and_bbox_legacy(self): await self._test_import_matrix_and_bbox_impl("omni.graph.nodes.ReadPrims") async def _test_import_matrix_and_bbox_impl(self, read_prims_node_type: str): # Verify that bounding box and matrix are correctly computed controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1)) UsdGeom.Xformable(cube).AddTranslateOp() (_, nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ReadPrims", read_prims_node_type), ("ExtractPrim", "omni.graph.nodes.ExtractPrim"), ("ExtractBundle", "omni.graph.nodes.ExtractBundle"), ("Inv", "omni.graph.nodes.OgnInvertMatrix"), ("Const0", "omni.graph.nodes.ConstantDouble3"), ("Const1", "omni.graph.nodes.ConstantDouble3"), ], keys.SET_VALUES: [ ("ReadPrims.inputs:pathPattern", "/World/Cube"), ("ExtractPrim.inputs:primPath", "/World/Cube"), ], keys.CONNECT: [ ("ReadPrims.outputs_primsBundle", "ExtractPrim.inputs:prims"), ("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"), ], }, ) if read_prims_node_type == "omni.graph.nodes.ReadPrims": controller.edit("/TestGraph", {keys.SET_VALUES: [("ReadPrims.inputs:useFindPrims", True)]}) extract_bundle = nodes[2] # creates dynamic attributes await controller.evaluate() # connect the matrix controller.edit("/TestGraph", {keys.CONNECT: ("ExtractBundle.outputs:worldMatrix", "Inv.inputs:matrix")}) # get initial output await controller.evaluate() # We did not ask for BBox self.assertFalse(extract_bundle.get_attribute_exists("outputs:bboxMinCorner")) self.assertFalse(extract_bundle.get_attribute_exists("outputs:bboxMaxCorner")) self.assertFalse(extract_bundle.get_attribute_exists("outputs:bboxTransform")) # but we should have the default matrix mat_attr = extract_bundle.get_attribute("outputs:worldMatrix") mat = mat_attr.get() self.assertTrue((mat == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).all()) # move the cube, check the new matrix pos = cube.GetAttribute("xformOp:translate") pos.Set((2, 2, 2)) await controller.evaluate() mat = mat_attr.get() self.assertTrue((mat == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 2, 2, 1]).all()) # now ask for bbox, and check its value controller.edit( "/TestGraph", { keys.SET_VALUES: ("ReadPrims.inputs:computeBoundingBox", True), }, ) await controller.evaluate() self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxMinCorner")) self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxMaxCorner")) self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxTransform")) # connect the bbox controller.edit( "/TestGraph", { keys.CONNECT: [ ("ExtractBundle.outputs:bboxMinCorner", "Const0.inputs:value"), ("ExtractBundle.outputs:bboxMaxCorner", "Const1.inputs:value"), ] }, ) await controller.evaluate() bbox_min = extract_bundle.get_attribute("outputs:bboxMinCorner") bbox_max = extract_bundle.get_attribute("outputs:bboxMaxCorner") bbox_min_val = bbox_min.get() bbox_max_val = bbox_max.get() self.assertTrue((bbox_min_val == [-0.5, -0.5, -0.5]).all()) self.assertTrue((bbox_max_val == [0.5, 0.5, 0.5]).all()) # then resize the cube, and check new bbox ext = cube.GetAttribute("extent") ext.Set([(-10, -10, -10), (10, 10, 10)]) await controller.evaluate() bbox_min_val = bbox_min.get() bbox_max_val = bbox_max.get() self.assertTrue((bbox_min_val == [-10, -10, -10]).all()) self.assertTrue((bbox_max_val == [10, 10, 10]).all()) async def test_readomnigraphvalue_tuple(self): """Test ReadOmniGraphValue by reading from a constant node (tuple)""" test_value = Gf.Vec3d(1.0, 2.0, 3.0) controller = og.Controller() keys = og.Controller.Keys (graph, (var_node, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var", "omni.graph.nodes.ConstantDouble3"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Var.inputs:value", test_value), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Var"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v[0], test_value[0]) self.assertEqual(v[1], test_value[1]) self.assertEqual(v[2], test_value[2]) # try editing value test_value = Gf.Vec3d(4.0, 5.0, 6.0) og.Controller.attribute("inputs:value", var_node).set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v[0], test_value[0]) self.assertEqual(v[1], test_value[1]) self.assertEqual(v[2], test_value[2]) async def test_readomnigraphvalue_single(self): """Test ReadOmniGraphValue by reading from a constant node (single)""" test_value = 1337 controller = og.Controller() keys = og.Controller.Keys (graph, (var_node, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var", "omni.graph.nodes.ConstantInt"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Var.inputs:value", test_value), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Var"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_value) # try editing value test_value = 42 og.Controller.attribute("inputs:value", var_node).set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_value) async def test_readomnigraphvalue_string(self): """Test ReadOmniGraphValue by reading from a constant node (string)""" test_value = "test value" controller = og.Controller() keys = og.Controller.Keys (graph, (var_node, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var", "omni.graph.nodes.ConstantString"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Var.inputs:value", test_value), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Var"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_value) # try editing value test_value = "test value 2" og.Controller.attribute("inputs:value", var_node).set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_value) async def test_readomnigraphvalue_array(self): """Test ReadOmniGraphValue by reading from a constant node (array)""" test_values = [1.0, 2.0, 3.0] controller = og.Controller() keys = og.Controller.Keys (graph, (val0, val1, val2, _, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Val0", "omni.graph.nodes.ConstantHalf"), ("Val1", "omni.graph.nodes.ConstantHalf"), ("Val2", "omni.graph.nodes.ConstantHalf"), ("Array", "omni.graph.nodes.MakeArray"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.CONNECT: [ ("Val0.inputs:value", "Array.inputs:a"), ("Val1.inputs:value", "Array.inputs:b"), ("Val2.inputs:value", "Array.inputs:c"), ], keys.SET_VALUES: [ ("Array.inputs:arraySize", 3), ("Val0.inputs:value", test_values[0]), ("Val1.inputs:value", test_values[1]), ("Val2.inputs:value", test_values[2]), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Array"), ("Get.inputs:name", "outputs:array"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v[0], test_values[0]) self.assertEqual(v[1], test_values[1]) self.assertEqual(v[2], test_values[2]) # # try editing value test_values = [4.0, 5.0, 6.0] og.Controller.attribute("inputs:value", val0).set(test_values[0]) og.Controller.attribute("inputs:value", val1).set(test_values[1]) og.Controller.attribute("inputs:value", val2).set(test_values[2]) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v[0], test_values[0]) self.assertEqual(v[1], test_values[1]) self.assertEqual(v[2], test_values[2]) async def test_readomnigraphvalue_tuple_array(self): """Test ReadOmniGraphValue by reading from a constant node (array of tuple)""" test_values = [Gf.Vec4f(1.0, 2.0, 3.0, 4.0), Gf.Vec4f(5.0, 6.0, 7.0, 8.0)] controller = og.Controller() keys = og.Controller.Keys (graph, (val0, val1, _, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Val0", "omni.graph.nodes.ConstantFloat4"), ("Val1", "omni.graph.nodes.ConstantFloat4"), ("Array", "omni.graph.nodes.MakeArray"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.CONNECT: [ ("Val0.inputs:value", "Array.inputs:a"), ("Val1.inputs:value", "Array.inputs:b"), ], keys.SET_VALUES: [ ("Array.inputs:arraySize", 2), ("Val0.inputs:value", test_values[0]), ("Val1.inputs:value", test_values[1]), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Array"), ("Get.inputs:name", "outputs:array"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) array = out_controller.get() self.assertEqual(array[0][0], test_values[0][0]) self.assertEqual(array[0][1], test_values[0][1]) self.assertEqual(array[0][2], test_values[0][2]) self.assertEqual(array[0][3], test_values[0][3]) self.assertEqual(array[1][0], test_values[1][0]) self.assertEqual(array[1][1], test_values[1][1]) self.assertEqual(array[1][2], test_values[1][2]) self.assertEqual(array[1][3], test_values[1][3]) # # try editing value test_values = [Gf.Vec4f(1.0, 2.0, 3.0, 4.0), Gf.Vec4f(5.0, 6.0, 7.0, 8.0)] og.Controller.attribute("inputs:value", val0).set(test_values[0]) og.Controller.attribute("inputs:value", val1).set(test_values[1]) await controller.evaluate(graph) array = out_controller.get() self.assertEqual(array[0][0], test_values[0][0]) self.assertEqual(array[0][1], test_values[0][1]) self.assertEqual(array[0][2], test_values[0][2]) self.assertEqual(array[0][3], test_values[0][3]) self.assertEqual(array[1][0], test_values[1][0]) self.assertEqual(array[1][1], test_values[1][1]) self.assertEqual(array[1][2], test_values[1][2]) self.assertEqual(array[1][3], test_values[1][3]) async def test_readomnigraphvalue_any(self): """Test ReadOmniGraphValue by reading from a constant node (any)""" test_value = 42 controller = og.Controller() keys = og.Controller.Keys (graph, (var_node, _, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var", "omni.graph.nodes.ConstantInt"), ("ToString", "omni.graph.nodes.ToString"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.CONNECT: [ ("Var.inputs:value", "ToString.inputs:value"), ], keys.SET_VALUES: [ ("Var.inputs:value", test_value), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/ToString"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_value) # try editing value test_value = 1234 og.Controller.attribute("inputs:value", var_node).set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_value) async def test_readomnigraphvalue_prim(self): """Test ReadOmniGraphValue by reading from a prim""" test_value = 555.0 controller = og.Controller() keys = og.Controller.Keys # use ReadPrimAttribute node to cache the attribute into Fabric (graph, _, (prim,), _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadPrim", "omni.graph.nodes.ReadPrimAttribute"), ], keys.CREATE_PRIMS: ("/World/Float", {"myfloat": ("float", test_value)}), keys.SET_VALUES: [ ("ReadPrim.inputs:usePath", True), ("ReadPrim.inputs:primPath", "/World/Float"), ("ReadPrim.inputs:name", "myfloat"), ], }, ) await controller.evaluate(graph) (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Get.inputs:path", "/World/Float"), ("Get.inputs:name", "myfloat"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_value) # try editing value test_value = 42.0 prim.GetProperty("myfloat").Set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_value) async def test_readomnigraphvalue_change_attribute(self): """Test ReadOmniGraphValue if attribute name is changed at runtime""" test_values = [42, 360] controller = og.Controller() keys = og.Controller.Keys (graph, (_, _, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var0", "omni.graph.nodes.ConstantInt"), ("Var1", "omni.graph.nodes.ConstantInt"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Var0.inputs:value", test_values[0]), ("Var1.inputs:value", test_values[1]), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Var0"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_values[0]) # try changing path og.Controller.attribute("inputs:path", get_node).set(f"{self.TEST_GRAPH_PATH}/Var1") await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_values[1]) async def test_readomnigraphvalue_invalid(self): """Test ReadOmniGraphValue by reading something that is not in Fabric""" controller = og.Controller() keys = og.Controller.Keys (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.CREATE_PRIMS: ("/World/Cube", "Cube"), keys.SET_VALUES: [ ("Get.inputs:path", "/World/Cube"), ("Get.inputs:name", "xformOp:translate"), ], }, ) get_node.clear_old_compute_messages() with ogts.ExpectedError(): await controller.evaluate(graph) self.assertEqual(len(get_node.get_compute_messages(og.WARNING)), 1)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_execution_framework.py
"""Basic tests of the execution framework with OG""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.kit.undo import omni.usd import omni.usd.commands from pxr import OmniGraphSchemaTools, Sdf # ====================================================================== class SimpleGraphScene: def __init__(self): self.graph = None self.nodes = None # ====================================================================== def create_simple_graph(): """Create a scene containing a PushGraph with a TestExecutionTask.""" scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("TestNode1", "omni.graph.test.TestExecutionTask"), ("TestNode2", "omni.graph.test.TestExecutionTask"), ("TestNode3", "omni.graph.test.TestExecutionTask"), ("TestNode4", "omni.graph.test.TestExecutionTask"), ], }, ) return scene # ====================================================================== def create_concurrency_graph(): """Create a scene containing a PushGraph with a TestConcurrency.""" scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("TestNode1", "omni.graph.test.TestConcurrency"), ("TestNode2", "omni.graph.test.TestConcurrency"), ("TestNode3", "omni.graph.test.TestConcurrency"), ("TestNode4", "omni.graph.test.TestConcurrency"), ], og.Controller.Keys.SET_VALUES: [ ("TestNode1.inputs:expected", 4), ("TestNode2.inputs:expected", 4), ("TestNode3.inputs:expected", 4), ("TestNode4.inputs:expected", 4), ("TestNode1.inputs:timeOut", 100), ("TestNode2.inputs:timeOut", 100), ("TestNode3.inputs:timeOut", 100), ("TestNode4.inputs:timeOut", 100), ], }, ) return scene # ====================================================================== def create_isolate_graph(): """Create a scene containing a PushGraph with TestIsolate, TestSerial, and TestConcurrency nodes.""" scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("TC0", "omni.graph.test.TestConcurrency"), ("TC1", "omni.graph.test.TestConcurrency"), ("TC2", "omni.graph.test.TestConcurrency"), ("TC3", "omni.graph.test.TestConcurrency"), ("TC4", "omni.graph.test.TestConcurrency"), ("TI0", "omni.graph.test.TestIsolate"), ("TI1", "omni.graph.test.TestIsolate"), ("TI2", "omni.graph.test.TestIsolate"), ("TS0", "omni.graph.test.TestSerial"), ("TS1", "omni.graph.test.TestSerial"), ("TS2", "omni.graph.test.TestSerial"), ("TS3", "omni.graph.test.TestSerial"), ("TS4", "omni.graph.test.TestSerial"), ], og.Controller.Keys.SET_VALUES: [ ("TC0.inputs:expected", 5), ("TC1.inputs:expected", 5), ("TC2.inputs:expected", 5), ("TC3.inputs:expected", 5), ("TC4.inputs:expected", 5), ("TC0.inputs:timeOut", 100), ("TC1.inputs:timeOut", 100), ("TC2.inputs:timeOut", 100), ("TC3.inputs:timeOut", 100), ("TC4.inputs:timeOut", 100), ], }, ) return scene # ====================================================================== def create_cyclic_graph(evaluator_name: str): """Create a scene containing a graph with cycles.""" # 4 cycles exist, which are made up of: # 1. Nodes 8 and 9. # 2. Nodes 11 and 12. # 3. Nodes 11, 13, and 15. # 4. Nodes 11, 13, 14, and 15. # Note that we also use a mix of serial- and parallel-scheduled # nodes for this test graph, just for fun :) scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( {"graph_path": "/World/TestGraph", "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("Node0", "omni.graph.test.TestCyclesSerial"), ("Node1", "omni.graph.test.TestCyclesParallel"), ("Node2", "omni.graph.test.TestCyclesParallel"), ("Node3", "omni.graph.test.TestCyclesSerial"), ("Node4", "omni.graph.test.TestCyclesSerial"), ("Node5", "omni.graph.test.TestCyclesParallel"), ("Node6", "omni.graph.test.TestCyclesSerial"), ("Node7", "omni.graph.test.TestCyclesParallel"), ("Node8", "omni.graph.test.TestCyclesParallel"), ("Node9", "omni.graph.test.TestCyclesParallel"), ("Node10", "omni.graph.test.TestCyclesParallel"), ("Node11", "omni.graph.test.TestCyclesParallel"), ("Node12", "omni.graph.test.TestCyclesParallel"), ("Node13", "omni.graph.test.TestCyclesParallel"), ("Node14", "omni.graph.test.TestCyclesSerial"), ("Node15", "omni.graph.test.TestCyclesSerial"), ("Node16", "omni.graph.test.TestCyclesSerial"), ], og.Controller.Keys.CONNECT: [ ("Node0.outputs:a", "Node4.inputs:a"), ("Node4.outputs:a", "Node5.inputs:a"), ("Node5.outputs:a", "Node2.inputs:a"), ("Node5.outputs:b", "Node6.inputs:a"), ("Node2.outputs:a", "Node3.inputs:a"), ("Node6.outputs:a", "Node3.inputs:b"), ("Node1.outputs:a", "Node2.inputs:b"), ("Node0.outputs:b", "Node8.inputs:a"), ("Node8.outputs:a", "Node9.inputs:a"), ("Node9.outputs:a", "Node8.inputs:b"), ("Node9.outputs:b", "Node7.inputs:a"), ("Node3.outputs:a", "Node7.inputs:b"), ("Node0.outputs:c", "Node10.inputs:a"), ("Node10.outputs:a", "Node11.inputs:a"), ("Node11.outputs:a", "Node12.inputs:a"), ("Node12.outputs:a", "Node11.inputs:b"), ("Node11.outputs:b", "Node16.inputs:a"), ("Node11.outputs:c", "Node13.inputs:a"), ("Node13.outputs:a", "Node14.inputs:a"), ("Node14.outputs:a", "Node15.inputs:a"), ("Node13.outputs:b", "Node15.inputs:b"), ("Node15.outputs:a", "Node11.inputs:c"), ("Node0.outputs:d", "Node0.inputs:d"), ("Node5.outputs:c", "Node5.inputs:c"), ("Node10.outputs:b", "Node10.inputs:b"), ("Node14.outputs:b", "Node14.inputs:b"), ], }, ) return scene # ====================================================================== def create_single_node_cyclic_graph(evaluator_name: str): """Create a scene containing a graph with single-node cycles""" scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( {"graph_path": "/World/TestGraph", "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("Node0", "omni.graph.test.TestCyclesSerial"), ("Node1", "omni.graph.test.TestCyclesParallel"), ], og.Controller.Keys.CONNECT: [ ("Node0.outputs:a", "Node0.inputs:a"), ("Node0.outputs:a", "Node1.inputs:a"), ("Node1.outputs:b", "Node1.inputs:b"), ], }, ) return scene # ====================================================================== class TestExecutionFrameworkSanity(ogts.OmniGraphTestCase): """Execution Framework Unit Tests""" async def test_execution_task(self): """Validate that execution framework is executing nodes in the graph.""" scene = create_simple_graph() # Verify starting condition. for node in scene.nodes: self.assertFalse(og.Controller(("outputs:result", node)).get()) # Execute the update once and we want explicitly to execute entire app update pipeline. await omni.kit.app.get_app().next_update_async() # Verify all nodes were executed with EF. for node in scene.nodes: self.assertTrue(og.Controller(("outputs:result", node)).get()) async def test_parallel_execution(self): """Validate that nodes are executed concurrently.""" scene = create_concurrency_graph() def _check_all_reached_concurrency(scene): result = True for node in scene.nodes: result = result and og.Controller(("outputs:result", node)).get() return result # Verify starting condition. self.assertFalse(_check_all_reached_concurrency(scene)) # First executions are forced to be run in isolation. await omni.kit.app.get_app().next_update_async() self.assertFalse(_check_all_reached_concurrency(scene)) # Now we should be getting parallel execution. await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_reached_concurrency(scene)) await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_reached_concurrency(scene)) await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_reached_concurrency(scene)) async def test_on_demand_execution_task(self): """Validate that execution framework is executing nodes in the graph.""" scene = create_simple_graph() # Verify starting condition. for node in scene.nodes: self.assertFalse(og.Controller(("outputs:result", node)).get()) # Execute given graph explicitly/on-demand. await og.Controller.evaluate(scene.graph) # Verify all nodes were executed with EF. for node in scene.nodes: self.assertTrue(og.Controller(("outputs:result", node)).get()) async def test_isolate_execution(self): """Check that nodes with the "usd-write" scheduling hint get executed in isolation.""" scene = create_isolate_graph() def _check_all_successful(scene): result = True for node in scene.nodes: result = result and og.Controller(("outputs:result", node)).get() return result # Verify starting condition. self.assertFalse(_check_all_successful(scene)) # First executions are forced to be run in isolation. await omni.kit.app.get_app().next_update_async() # In subsequent executions each node gets executed per # its scheduling hint. Should not get any conflicts. await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_successful(scene)) await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_successful(scene)) await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_successful(scene)) async def test_cycling_push_graph(self): """Check that cycles in push graphs correctly get ignored during execution.""" scene = create_cyclic_graph("push") # Set of node indices that will evaluate. node_indices_that_evaluate = {0, 1, 2, 3, 4, 5, 6, 10} # Get all state counters. state_cnt_attrs = [node.get_attribute("state:count") for node in scene.nodes] # For each tick, only the nodes in the index list should get evaluated; # all other nodes either lie within a cycle or downstream of a cycle, and # thus will be ignored. for i in range(4): await omni.kit.app.get_app().next_update_async() for j, state_cnt_attr in enumerate(state_cnt_attrs): self.assertEqual(state_cnt_attr.get(), i + 1 if j in node_indices_that_evaluate else 0) async def test_cycling_pull_graph(self): """Check that cycles in pull graphs correctly get ignored during execution.""" scene = create_cyclic_graph("dirty_push") # Set of node indices that will evaluate when node 0 is dirtied. node_indices_that_evaluate = {0, 1, 2, 3, 4, 5, 6, 10} # Get all state counters. state_cnt_attrs = [node.get_attribute("state:count") for node in scene.nodes] # Trigger a graph evaluation by adding/removing a connection between nodes 0 and 4. # Only the nodes in the index list should get evaluated; all other nodes either lie # within a cycle or downstream of a cycle, and thus will be ignored. for i in range(4): if i % 2 == 0: og.Controller.connect( scene.nodes[0].get_attribute("outputs:d"), scene.nodes[4].get_attribute("inputs:d") ) else: og.Controller.disconnect( scene.nodes[0].get_attribute("outputs:d"), scene.nodes[4].get_attribute("inputs:d") ) await omni.kit.app.get_app().next_update_async() for j, state_cnt_attr in enumerate(state_cnt_attrs): self.assertEqual(state_cnt_attr.get(), i + 1 if j in node_indices_that_evaluate else 0) async def test_push_graph_with_single_node_cycles(self): """Check that single-node cycles in push graphs do not block execution.""" scene = create_single_node_cyclic_graph("push") # Get all state counters. state_cnt_attrs = [node.get_attribute("state:count") for node in scene.nodes] # Check that all nodes get executed each tick. for i in range(4): await omni.kit.app.get_app().next_update_async() for state_cnt_attr in state_cnt_attrs: self.assertEqual(state_cnt_attr.get(), i + 1) async def test_pull_graph_with_single_node_cycles(self): """Check that single-node cycles in pull graphs do not block execution.""" scene = create_single_node_cyclic_graph("dirty_push") # Get all state counters. state_cnt_attrs = [node.get_attribute("state:count") for node in scene.nodes] # Trigger a graph evaluation by adding/removing an extra connection between nodes # 0 and 1. All nodes should execute. for i in range(4): if i % 2 == 0: og.Controller.connect( scene.nodes[0].get_attribute("outputs:c"), scene.nodes[1].get_attribute("inputs:c") ) else: og.Controller.disconnect( scene.nodes[0].get_attribute("outputs:c"), scene.nodes[1].get_attribute("inputs:c") ) await omni.kit.app.get_app().next_update_async() for state_cnt_attr in state_cnt_attrs: self.assertEqual(state_cnt_attr.get(), i + 1) async def test_partitioning_with_instancing(self): """ Check that injection of either a NodeDefLambda or NodeGraphDef into the OG execution graph backend continues to work with instancing. """ # Run the test against both test partition passes. partition_pass_settings = [ "/app/omni.graph.test/enableTestNodeDefLambdaPass", "/app/omni.graph.test/enableTestNodeGraphDefPass", ] for si, pps in enumerate(partition_pass_settings): with og.Settings.temporary(pps, True): # Run the test over push and dirty_push evaluator types. Once partitioning # is supported by the Action Graph executor, we should be able to also # test the "execution" evaluator here as well. evaluator_names = [ "push", "dirty_push", # "execution", ] for evaluator_name in evaluator_names: # Create our graph, which will contain a ReadVariable and # WriteVariable node. graph_path = "/World/TestGraph" (graph, (read_variable_node, write_variable_node), _, _) = og.Controller.edit( {"graph_path": graph_path, "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("WriteVariable", "omni.graph.core.WriteVariable"), ], og.Controller.Keys.CREATE_VARIABLES: [ ("in_int_var", og.Type(og.BaseDataType.INT)), ("out_int_var", og.Type(og.BaseDataType.INT)), ], og.Controller.Keys.CONNECT: [ ("ReadVariable.outputs:value", "WriteVariable.inputs:value"), ], og.Controller.Keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "in_int_var"), ("WriteVariable.inputs:variableName", "out_int_var"), ], }, ) # Create the custom counter attribute on both nodes so # that they get picked up by the partition pass. og.Controller.create_attribute( read_variable_node, "outputs:test_counter_attribute", og.Type(og.BaseDataType.INT, 1, 0, og.AttributeRole.NONE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) og.Controller.create_attribute( write_variable_node, "outputs:test_counter_attribute", og.Type(og.BaseDataType.INT, 1, 0, og.AttributeRole.NONE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) # Get some attributes/variables that we'll need for the test. in_var = graph.find_variable("in_int_var") rn_out_value = read_variable_node.get_attribute("outputs:value") wn_in_value = write_variable_node.get_attribute("inputs:value") wn_out_value = write_variable_node.get_attribute("outputs:value") out_var = graph.find_variable("out_int_var") rn_cnt = read_variable_node.get_attribute("outputs:test_counter_attribute") wn_cnt = write_variable_node.get_attribute("outputs:test_counter_attribute") # Create 3 graph instances, each with unique "in_int_var" values # and "out_int_var" set to zero. num_prims = 3 prim_ids = [None] * num_prims prim_paths = [None] * num_prims prims = [None] * num_prims stage = omni.usd.get_context().get_stage() graph_context = graph.get_default_graph_context() for i in range(0, num_prims): prim_ids[i] = i prim_paths[i] = f"/World/Prim_{i}" prims[i] = stage.DefinePrim(prim_paths[i]) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_paths[i], graph_path) prims[i].CreateAttribute("graph:variable:in_int_var", Sdf.ValueTypeNames.Int).Set(i) prims[i].CreateAttribute("graph:variable:out_int_var", Sdf.ValueTypeNames.Int).Set(0) # When we evaluate the graph we should see that (a) the counter attribute on the # authoring node gets ticked (which is handled directly by the partition passes, # thus letting us know that they actually went through successfully/weren't just # no-ops), and (b) the out_int_var variable gets successfully written out to with # the value listed on the in_int_var variable. await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() for i in range(0, num_prims): expected_value = i self.assertEqual(in_var.get(graph_context, instance_path=prim_paths[i]), expected_value) # Note that the instanced nodes (and thus the attributes we're looking up) # need not be ordered according to the iteration index, e.g., instance with # index 0 may correspond to the prim at the i == 2 index in the prim_paths # list This is why we perform the subsequent 3 checks as shown below. self.assertIn(rn_out_value.get(instance=i), prim_ids) self.assertIn(wn_in_value.get(instance=i), prim_ids) self.assertIn(wn_out_value.get(instance=i), prim_ids) self.assertEqual(out_var.get(graph_context, instance_path=prim_paths[i]), expected_value) if ( evaluator_name == "push" ): # Needed because PushGraphs have some special vectorization going on? if si == 0: self.assertEqual(rn_cnt.get(), 2) self.assertEqual(wn_cnt.get(), 2) self.assertEqual(rn_cnt.get(instance=i), 0) self.assertEqual(wn_cnt.get(instance=i), 0) else: self.assertEqual(rn_cnt.get(), 0) self.assertEqual(wn_cnt.get(), 0) if i == 0: self.assertEqual(rn_cnt.get(instance=i), 2) self.assertEqual(wn_cnt.get(instance=i), 2) else: self.assertEqual(rn_cnt.get(instance=i), 0) self.assertEqual(wn_cnt.get(instance=i), 0) else: if si == 0: self.assertEqual(rn_cnt.get(), 6) self.assertEqual(wn_cnt.get(), 6) self.assertEqual(rn_cnt.get(instance=i), 0) self.assertEqual(wn_cnt.get(instance=i), 0) else: self.assertEqual(rn_cnt.get(), 0) self.assertEqual(wn_cnt.get(), 0) if i == 0: self.assertEqual(rn_cnt.get(instance=i), 6) self.assertEqual(wn_cnt.get(instance=i), 6) else: self.assertEqual(rn_cnt.get(instance=i), 0) self.assertEqual(wn_cnt.get(instance=i), 0) # Delete all prims in the stage. for i in range(0, num_prims): stage.RemovePrim(prim_paths[i]) graph.remove_variable(in_var) graph.remove_variable(out_var) stage.RemovePrim(graph_path) await omni.kit.app.get_app().next_update_async() async def test_constant_node_removal(self): """ Check that we do not include constant OG nodes in the execution graph backend for push and action graphs, and that doing so does not impact graph computation to yield incorrect results. """ stage = omni.usd.get_context().get_stage() # Run the test over each evaluator type. evaluator_names = [ "push", "dirty_push", "execution", ] for evaluator_name in evaluator_names: # Create our test graph. graph_path = "/World/TestGraph" test_prim_path = "/World/TestPrim" (graph, (constant_double0_node, constant_double1_node, add_node, _, _, _), _, _) = og.Controller.edit( {"graph_path": graph_path, "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("ConstantDouble0", "omni.graph.nodes.ConstantDouble"), ("ConstantDouble1", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ("OnTick", "omni.graph.action.OnTick"), ("WritePrimAttribute", "omni.graph.nodes.WritePrimAttribute"), ("WriteVariable", "omni.graph.core.WriteVariable"), ], og.Controller.Keys.CREATE_PRIMS: ( test_prim_path, { "value": ("double", 0), }, ), og.Controller.Keys.CREATE_VARIABLES: [ ("out_double_var", og.Type(og.BaseDataType.DOUBLE)), ], og.Controller.Keys.CONNECT: [ ("ConstantDouble0.inputs:value", "Add.inputs:a"), ("ConstantDouble1.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "WritePrimAttribute.inputs:value"), ("Add.outputs:sum", "WriteVariable.inputs:value"), ("OnTick.outputs:tick", "WritePrimAttribute.inputs:execIn"), ("WritePrimAttribute.outputs:execOut", "WriteVariable.inputs:execIn"), ], og.Controller.Keys.SET_VALUES: [ ("ConstantDouble0.inputs:value", 5.0), ("ConstantDouble1.inputs:value", 1.0), ("OnTick.inputs:onlyPlayback", False), ("WritePrimAttribute.inputs:name", "value"), ("WritePrimAttribute.inputs:primPath", "/World/TestPrim"), ("WriteVariable.inputs:variableName", "out_double_var"), ], }, ) out_double_var = graph.find_variable("out_double_var") inputs_value_attr_0 = constant_double0_node.get_attribute("inputs:value") inputs_value_attr_1 = constant_double1_node.get_attribute("inputs:value") outputs_sum_attr = add_node.get_attribute("outputs:sum") # Check that the summation is correctly computed, and that the # ConstantDouble nodes aren't computed. await omni.kit.app.get_app().next_update_async() self.assertAlmostEqual(outputs_sum_attr.get(), 6.0, places=2) if evaluator_name in ("push", "execution"): self.assertEqual(constant_double0_node.get_compute_count(), 0) self.assertEqual(constant_double1_node.get_compute_count(), 0) else: self.assertEqual(constant_double0_node.get_compute_count(), 1) self.assertEqual(constant_double1_node.get_compute_count(), 1) # Check that this still holds if we alter attributes on the nodes. inputs_value_attr_0.set(8) inputs_value_attr_1.set(2) await omni.kit.app.get_app().next_update_async() self.assertAlmostEqual(outputs_sum_attr.get(), 10.0, places=2) if evaluator_name in ("push", "execution"): self.assertEqual(constant_double0_node.get_compute_count(), 0) self.assertEqual(constant_double1_node.get_compute_count(), 0) else: self.assertEqual(constant_double0_node.get_compute_count(), 2) self.assertEqual(constant_double1_node.get_compute_count(), 2) # Next, instance the graph 3 times and perform similar checks as before. graph_context = graph.get_default_graph_context() num_graph_instances = 3 graph_instance_ids = [None] * num_graph_instances graph_instance_paths = [None] * num_graph_instances graph_instances = [None] * num_graph_instances for i in range(0, num_graph_instances): graph_instance_ids[i] = i graph_instance_paths[i] = f"/World/GraphInstance_{i}" graph_instances[i] = stage.DefinePrim(graph_instance_paths[i]) OmniGraphSchemaTools.applyOmniGraphAPI(stage, graph_instance_paths[i], graph_path) graph_instances[i].CreateAttribute("graph:variable:out_double_var", Sdf.ValueTypeNames.Double).Set(0) inputs_value_attr_0.set(1) inputs_value_attr_1.set(3) await omni.kit.app.get_app().next_update_async() for i in range(0, num_graph_instances): # TODO: Instanced "execution" type graphs aren't getting updated here # for some reason, needs a bit more investigation... if evaluator_name == "execution": self.assertEqual(out_double_var.get(graph_context, instance_path=graph_instance_paths[i]), 0.0) else: self.assertEqual(out_double_var.get(graph_context, instance_path=graph_instance_paths[i]), 4.0) if evaluator_name in ("push", "execution"): self.assertEqual(constant_double0_node.get_compute_count(), 0) self.assertEqual(constant_double1_node.get_compute_count(), 0) else: self.assertEqual(constant_double0_node.get_compute_count(), 6) self.assertEqual(constant_double1_node.get_compute_count(), 6) # Delete all prims in the stage. for i in range(0, num_graph_instances): stage.RemovePrim(graph_instance_paths[i]) stage.RemovePrim(test_prim_path) stage.RemovePrim(graph_path) await omni.kit.app.get_app().next_update_async()
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_bundles.py
"""Tests exercising bundles in OmniGraph""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit # ====================================================================== class TestOmniGraphBundles(ogts.OmniGraphTestCase): async def test_get_prims_use_target_prims(self): controller = og.Controller() keys = og.Controller.Keys graph_path = "/World/Graph" (graph, (_, get_prims), (surface1, surface2, surface3), _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ReadPrims", "omni.graph.nodes.ReadPrims"), ("GetPrims", "omni.graph.nodes.GetPrims"), ], keys.CREATE_PRIMS: [ ("/Surface1", "Cube"), ("/Surface2", "Cube"), ("/Surface3", "Cube"), ], keys.CONNECT: [ ("ReadPrims.outputs_primsBundle", "GetPrims.inputs:bundle"), ], }, ) stage = omni.usd.get_context().get_stage() context = graph.get_default_graph_context() bundle = context.get_output_bundle(get_prims, "outputs_bundle") omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(graph_path + "/ReadPrims.inputs:prims"), targets=[surface1.GetPath(), surface2.GetPath(), surface3.GetPath()], ) # get two prims omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(graph_path + "/GetPrims.inputs:prims"), targets=[surface1.GetPath(), surface2.GetPath()], ) graph.evaluate() self.assertEqual(bundle.get_child_bundle_count(), 2) # switch back to default to get all omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(graph_path + "/GetPrims.inputs:prims"), targets=[], ) graph.evaluate() self.assertEqual(bundle.get_child_bundle_count(), 3) async def test_bundle_child_producer_consumer(self): controller = og.Controller() keys = og.Controller.Keys graph_path = "/World/Graph" (graph, (_, child_producer_node, child_consumer_node), (surface1, surface2), _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ReadPrims", "omni.graph.nodes.ReadPrims"), ("BundleChildProducer", "omni.graph.test.BundleChildProducerPy"), ("BundleChildConsumer", "omni.graph.test.BundleChildConsumerPy"), ], keys.CREATE_PRIMS: [ ("/Surface1", "Cube"), ("/Surface2", "Cube"), ], keys.CONNECT: [ ("ReadPrims.outputs_primsBundle", "BundleChildProducer.inputs:bundle"), ("BundleChildProducer.outputs_bundle", "BundleChildConsumer.inputs:bundle"), ], }, ) stage = omni.usd.get_context().get_stage() omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(graph_path + "/ReadPrims.inputs:prims"), target=surface1.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(graph_path + "/ReadPrims.inputs:prims"), target=surface2.GetPath(), ) graph.evaluate() self.assertEqual(child_producer_node.get_attribute("outputs:numChildren").get(), 2) self.assertEqual(child_consumer_node.get_attribute("outputs:numChildren").get(), 1) self.assertEqual(child_consumer_node.get_attribute("outputs:numSurfaces").get(), 2) graph.evaluate() self.assertEqual(child_producer_node.get_attribute("outputs:numChildren").get(), 2) self.assertEqual(child_consumer_node.get_attribute("outputs:numChildren").get(), 1) self.assertEqual(child_consumer_node.get_attribute("outputs:numSurfaces").get(), 2) async def __test_input_bundle_validity(self, bundle_properties_name): """Test if connecting/disconnecting invalidates the database and reinitializes BundleContents for input bundle""" controller = og.Controller() keys = og.Controller.Keys # Disconnected input bundle should be invalid (graph, (_, bundle_properties), _, _) = controller.edit( "/World/Graph", { keys.CREATE_NODES: [ ("BundleConstructor", "omni.graph.nodes.BundleConstructor"), ("BundleProperties", f"omni.graph.test.{bundle_properties_name}"), ], }, ) graph.evaluate() self.assertFalse(bundle_properties.get_attribute("outputs:valid").get()) # Connected input bundle should be valid (graph, _, _, _) = controller.edit( "/World/Graph", { keys.CONNECT: [ ("BundleConstructor.outputs_bundle", "BundleProperties.inputs:bundle"), ], }, ) graph.evaluate() self.assertTrue(bundle_properties.get_attribute("outputs:valid").get()) # ---------------------------------------------------------------------- async def test_is_input_bundle_valid_cpp(self): """Test if connecting/disconnecting invalidates the database and reinitializes BundleContents for input bundle for C++""" await self.__test_input_bundle_validity("BundleProperties") # ---------------------------------------------------------------------- async def test_is_input_bundle_valid_py(self): """Test if connecting/disconnecting invalidates the database and reinitializes BundleContents for input bundle for Python""" await self.__test_input_bundle_validity("BundlePropertiesPy") async def __test_producer_consumer_bundle_change_tracking(self, producer_name, consumer_name): controller = og.Controller() keys = og.Controller.Keys # +--------------------+ +---------------------+ # | | | | # | Bundle Producer --------> Bundle Consumer | # | | | | # +--------------------+ +---------------------+ # (make changes) (recompute if input changed) (graph, (producer_node, consumer_node), _, _) = controller.edit( "/World/Graph", { keys.CREATE_NODES: [ ("BundleProducer", f"omni.graph.test.{producer_name}"), ("BundleConsumer", f"omni.graph.test.{consumer_name}"), ], keys.CONNECT: [ ("BundleProducer.outputs_bundle", "BundleConsumer.inputs:bundle"), ], }, ) context = graph.get_context() producer_bundle = context.get_output_bundle(producer_node, "outputs_bundle") consumer_bundle = context.get_output_bundle(consumer_node, "outputs_bundle") # First evaluation is necessary. graph.evaluate() self.assertTrue(consumer_node.get_attribute("outputs:hasOutputBundleChanged").get()) # Next evaluation producer did not create any data. graph.evaluate() self.assertFalse(consumer_node.get_attribute("outputs:hasOutputBundleChanged").get()) # Create a child at the producer, then check if consumer recomputes. producer_bundle.create_child_bundle("surface0") graph.evaluate() self.assertTrue(consumer_node.get_attribute("outputs:hasOutputBundleChanged").get()) self.assertEqual(consumer_bundle.get_child_bundle_count(), 1) # Next evaluation producer did not create any data. graph.evaluate() self.assertFalse(consumer_node.get_attribute("outputs:hasOutputBundleChanged").get()) # ---------------------------------------------------------------------- async def test_producer_consumer_bundle_change_tracking_cpp(self): await self.__test_producer_consumer_bundle_change_tracking("BundleProducer", "BundleConsumer") # ---------------------------------------------------------------------- async def test_producer_consumer_bundle_change_tracking_py(self): await self.__test_producer_consumer_bundle_change_tracking("BundleProducerPy", "BundleConsumerPy") # ---------------------------------------------------------------------- async def test_bundle_to_target_connection(self): """Backwards compatibility test to open a USD file where node with a bundle and target is connected. This test is to check if the connection from USD file is properly deserialized. """ (result, error) = await ogts.load_test_file("TestBundleToTargetConnection.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph_path = "/World/PushGraph" controller = og.Controller() graph = controller.graph(graph_path) await controller.evaluate(graph) node = controller.node(f"{graph_path}/test_node_bundle_to_target_connection_01") attr = controller.attribute("inputs:target", node) connections = attr.get_upstream_connections() self.assertEqual(len(connections), 1) self.assertEqual( connections[0].get_path(), f"{graph_path}/test_node_bundle_to_target_connection/outputs_bundle" )
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_controller_api.py
# noqa PLC0302 """Basic tests of the controller classes in omni.graph.core""" import omni.graph.core.tests as ogts # ============================================================================================================== class TestControllerApi(ogts.OmniGraphTestCase): """Run a simple set of unit tests that exercise the API of the controller. Tests are formatted in such a way that the documentation can be extracted directly from the running code, to ensure it stays up to date. """ # -------------------------------------------------------------------------------------------------------------- async def test_controller_api(self): """Contrived test that exercises the entire API of the Controller, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-controller-XX pairs. """ # begin-controller-boilerplate import omni.graph.core as og keys = og.Controller.Keys # Usually handy to keep this name short as it is used often controller = og.Controller() # end-controller-boilerplate # begin-controller-as-static og.Controller.edit("/World/MyGraph", {keys.CREATE_NODES: ("MyClassNode", "omni.graph.tutorials.SimpleData")}) og.Controller.edit("/World/MyGraph", {keys.SET_VALUES: ("/World/MyGraph/MyClassNode.inputs:a_bool", False)}) # end-controller-as-static # begin-controller-as-object controller.edit("/World/MyGraph", {keys.CREATE_NODES: ("MyNode", "omni.graph.tutorials.SimpleData")}) controller.edit("/World/MyGraph", {keys.SET_VALUES: ("MyNode.inputs:a_bool", False)}) # end-controller-as-object # begin-controller-remember (graph, nodes, prims, name_to_path_map) = og.Controller.edit( "/World/MyGraph", {keys.CREATE_NODES: ("KnownNode", "omni.graph.tutorials.SimpleData")} ) assert not prims # graph = og.Graph # the newly created or existing graph, here the one at the path "/World/MyGraph" # nodes = list[og.Node] # the list of nodes created, here [the node named "KnownNode"] # prims = list[Usd.Prim] # the list of prims created via the keys.CREATE_PRIMS directive, here [] # name_to_path_map = dict[str, str] # the map of short names to full paths created, here {"KnownNode": "/World/MyGraph/KnownNode"} # You can use the node directly to find the attribute og.Controller.edit(graph, {keys.SET_VALUES: (("inputs:a_bool", nodes[0]), False)}) # You can pass in the map so that the short name of the node can be used to find the attribute og.Controller.edit(graph, {keys.SET_VALUES: ("KnownNode.inputs:a_bool", False)}, name_to_path_map) # end-controller-remember # For later use og.Controller.connect("/World/MyGraph/MyClassNode.outputs:a_bool", "/World/MyGraph/KnownNode.inputs:a_bool") # begin-controller-access-type await og.Controller.evaluate() await controller.evaluate() # end-controller-access-type # begin-controller-evaluate # This version evaluates all graphs asynchronously await og.Controller.evaluate() # This version evaluates the graph defined by the controller object synchronously controller.evaluate_sync() # This version evaluates the single named graph synchronously og.Controller.evaluate_sync(graph) # end-controller-evaluate # begin-controller-attr-construct controller = og.Controller(og.Controller.attribute("/World/MyGraph/MyNode.inputs:a_bool")) if controller.get(): print("This should not be hit as the value was already set to False") if og.Controller.get(og.Controller.attribute("/World/MyGraph/MyNode.inputs:a_bool")): print("Similarly, this is a variation of the same call that should give the same result") # end-controller-attr-construct self.assertFalse(controller.get()) # begin-controller-big-edit # Keywords are shown for the edit arguments, however they are not required (graph, nodes, prims, name_to_path_map) = og.Controller.edit( # First parameter is a graph reference, created if it doesn't already exist. # See omni.graph.core.GraphController.create_graph() for more options graph_id="/World/MyGraph", # Second parameter is a dictionary edit_commands={ # Delete a node or list of nodes that already existed in the graph # See omni.graph.core.GraphController.delete_nodes() for more options keys.DELETE_NODES: ["MyNode"], # Create new nodes in the graph - the resulting og.Nodes are returned in the "nodes" part of the tuple # See omni.graph.core.GraphController.create_node() for more options keys.CREATE_NODES: [ ("src", "omni.graph.tutorials.SimpleData"), ("dst", "omni.graph.tutorials.SimpleData"), ], # Create new (dynamic) attributes on some nodes. # See omni.graph.core.NodeController.create_attribute() for more options keys.CREATE_ATTRIBUTES: [ ("src.inputs:dyn_float", "float"), ("dst.inputs:dyn_any", "any"), ], # Create new prims in the stage - the resulting Usd.Prims are returned in the "prims" part of the tuple # See omni.graph.core.GraphController.create_prims() for more options keys.CREATE_PRIMS: [ ("Prim1", {"attrFloat": ("float", 2.0)}), ("Prim2", {"attrBool": ("bool", True)}), ], # Expose on of the prims to OmniGraph by creating a USD import node to read it as a bundle. # The resulting node is in the "nodes" part of the tuple, after any native OmniGraph node types. # See omni.graph.core.GraphController.expose_prims() for more options keys.EXPOSE_PRIMS: [(og.Controller.PrimExposureType.AS_BUNDLE, "Prim1", "Prim1Exposed")], # Connect a source output to a destination input to create a flow of data between the two nodes # See omni.graph.core.GraphController.connect() for more options keys.CONNECT: [("src.outputs:a_int", "dst.inputs:a_int")], # Disconnect an already existing connection. # See omni.graph.core.GraphController.disconnect() for more options keys.DISCONNECT: [ ("/World/MyGraph/MyClassNode.outputs:a_bool", "/World/MyGraph/KnownNode.inputs:a_bool") ], # Define an attribute's value (inputs and state attributes only - outputs are computed) # See omni.graph.core.DataView.set() for more options keys.SET_VALUES: [("src.inputs:a_int", 5)], # Create graph-local variable values # See omni.graph.core.GraphController.create_variables() for more options keys.CREATE_VARIABLES: [("a_float_var", og.Type(og.BaseDataType.FLOAT)), ("a_bool_var", "bool")], }, # Parameters from here down could also be saved as part of the object and reused repeatedly if you had # created a controller rather than calling edit() as a class method path_to_object_map=None, # Saved object-to-path map, bootstraps any created as part of the call update_usd=True, # Immediately echo the changes to the underlying USD undoable=True, # If False then do not remember previous state - useful for writing tests allow_exists_node=False, # If True then silently succeed requests to create already existing nodes allow_exists_prim=False, # If True then silently succeed requests to create already existing prims ) # end-controller-big-edit # -------------------------------------------------------------------------------------------------------------- async def test_object_lookup_api(self): """Contrived test that exercises the entire API of the ObjectLookup, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-object-lookup-XX pairs. """ # begin-object-lookup-boilerplate import omni.graph.core as og import omni.usd from pxr import OmniGraphSchema, Sdf keys = og.Controller.Keys # Note that when you extract the parameters this way it is important to have the trailing "," in the node # and prim tuples so that Python doesn't try to interpret them as single objects. (graph, (node,), (prim,), _) = og.Controller.edit( "/World/MyGraph", { keys.CREATE_NODES: ("MyNode", "omni.graph.test.TestAllDataTypes"), keys.CREATE_PRIMS: ("MyPrim", {"myFloat": ("float", 0)}), keys.CREATE_VARIABLES: ("MyVariable", "float"), }, ) assert prim.IsValid() attribute = node.get_attribute("inputs:a_bool") relationship_attribute = node.get_attribute("inputs:a_target") attribute_type = attribute.get_resolved_type() node_type = node.get_node_type() variable = graph.get_variables()[0] stage = omni.usd.get_context().get_stage() # end-object-lookup-boilerplate # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-graph # Look up the graph directly from itself (to simplify code) assert graph == og.Controller.graph(graph) # Look up the graph by path assert graph == og.Controller.graph("/World/MyGraph") # Look up the graph by Usd Prim graph_prim = stage.GetPrimAtPath("/World/MyGraph") assert graph == og.Controller.graph(graph_prim) # Look up by a Usd Schema object graph_schema = OmniGraphSchema.OmniGraph(graph_prim) assert graph == og.Controller.graph(graph_schema) # Look up the graph by SdfPath path = Sdf.Path("/World/MyGraph") assert graph == og.Controller.graph(path) # Look up a list of graphs by passing a list of any of the above for new_graph in og.Controller.graph([graph, "/World/MyGraph", path]): assert graph == new_graph # end-object-lookup-graph # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-node # Look up the node directly from itself (to simplify code) assert node == og.Controller.node(node) # Look up the node by path assert node == og.Controller.node("/World/MyGraph/MyNode") # Look up the node by partial path and graph. # The graph parameter can be any of the ones supported by og.Controller.graph() assert node == og.Controller.node(("MyNode", graph)) # Look up the node by SdfPath node_path = Sdf.Path("/World/MyGraph/MyNode") assert node == og.Controller.node(node_path) # Look up the node from its underlying USD prim backing, if it exists node_prim = stage.GetPrimAtPath("/World/MyGraph/MyNode") assert node == og.Controller.node(node_prim) # Look up a list of nodes by passing a list of any of the above for new_node in og.Controller.node([node, "/World/MyGraph/MyNode", ("MyNode", graph), node_path, node_prim]): assert node == new_node # end-object-lookup-node # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-attribute # Look up the attribute directly from itself (to simplify code) assert attribute == og.Controller.attribute(attribute) # Look up the attribute by path assert attribute == og.Controller.attribute("/World/MyGraph/MyNode.inputs:a_bool") # Look up the attribute by SdfPath assert attribute == og.Controller.attribute(Sdf.Path("/World/MyGraph/MyNode.inputs:a_bool")) # Look up the attribute by name and node assert attribute == og.Controller.attribute(("inputs:a_bool", node)) # These can chain, so you can also look up the attribute by name and node, where node is further looked up by # relative path and graph assert attribute == og.Controller.attribute(("inputs:a_bool", ("MyNode", graph))) # Look up the attribute by SdfPath attr_path = Sdf.Path("/World/MyGraph/MyNode.inputs:a_bool") assert attribute == og.Controller.attribute(attr_path) # Look up the attribute through its Usd counterpart stage = omni.usd.get_context().get_stage() node_prim = stage.GetPrimAtPath("/World/MyGraph/MyNode") usd_attribute = node_prim.GetAttribute("inputs:a_bool") assert attribute == og.Controller.attribute(usd_attribute) # Look up a list of attributes by passing a list of any of the above for new_attribute in og.Controller.attribute( [ attribute, "/World/MyGraph/MyNode.inputs:a_bool", Sdf.Path("/World/MyGraph/MyNode.inputs:a_bool"), ("inputs:a_bool", node), ("inputs:a_bool", ("MyNode", graph)), attr_path, usd_attribute, ] ): assert attribute == new_attribute # end-object-lookup-attribute # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-attribute-type attribute_type = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION) # Look up the attribute type by OGN type name assert attribute_type == og.Controller.attribute_type("pointf[3][]") # Look up the attribute type by SDF type name assert attribute_type == og.Controller.attribute_type("point3f[]") # Look up the attribute type directly from itself (to simplify code) assert attribute_type == og.Controller.attribute_type(attribute_type) # Look up the attribute type from the attribute with that type point_attribute = og.Controller.attribute(("inputs:a_pointf_3_array", node)) assert attribute_type == og.Controller.attribute_type(point_attribute) # Look up the attribute type from the attribute data whose attribute has that type (most commonly done with # attributes that have extended types or attributes belonging to bundles) point_attribute_data = point_attribute.get_attribute_data() assert attribute_type == og.Controller.attribute_type(point_attribute_data) # end-object-lookup-attribute-type # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-node-type node_type = node.get_node_type() # Look up the node type directly from itself (to simplify code) assert node_type == og.Controller.node_type(node_type) # Look up the node type from the string that uniquely identifies it assert node_type == og.Controller.node_type("omni.graph.test.TestAllDataTypes") # Look up the node type from the node with that type assert node_type == og.Controller.node_type(node) # Look up the node type from the USD Prim backing a node of that type assert node_type == og.Controller.node_type(node_prim) # Look up a list of node types by passing a list of any of the above for new_node_type in og.Controller.node_type( [ node_type, "omni.graph.test.TestAllDataTypes", node, node_prim, ] ): assert node_type == new_node_type # end-object-lookup-node-type # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-prim # Look up the prim directly from itself (to simplify code) assert node_prim == og.Controller.prim(node_prim) # Look up the prim from the prim path as a string assert node_prim == og.Controller.prim("/World/MyGraph/MyNode") # Look up the prim from the Sdf.Path pointing to the prim assert node_prim == og.Controller.prim(node_path) # Look up the prim from the OmniGraph node for which it is the backing assert node_prim == og.Controller.prim(node) # Look up the prim from the (node_path, graph) tuple defining the OmniGraph node for which it is the backing assert node_prim == og.Controller.prim(("MyNode", graph)) # Look up the prim from an OmniGraph graph assert graph_prim == og.Controller.prim(graph) # Look up a list of prims by passing a list of any of the above for new_prim in og.Controller.prim( [ node_prim, "/World/MyGraph/MyNode", node_path, node, ("MyNode", graph), ] ): assert node_prim == new_prim # end-object-lookup-prim # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-usd-attribute # USD attributes can be looked up with the same parameters as for looking up an OmniGraph attribute # Look up the USD attribute directly from itself (to simplify code) assert usd_attribute == og.Controller.usd_attribute(usd_attribute) # Look up the USD attribute by path assert usd_attribute == og.Controller.usd_attribute("/World/MyGraph/MyNode.inputs:a_bool") # Look up the USD attribute by name and node assert usd_attribute == og.Controller.usd_attribute(("inputs:a_bool", node)) # These can chain, so you can also look up the USD attribute by name and node, where node is further looked up by # relative path and graph assert usd_attribute == og.Controller.usd_attribute(("inputs:a_bool", ("MyNode", graph))) # Look up the USD attribute by SdfPath attr_path = Sdf.Path("/World/MyGraph/MyNode.inputs:a_bool") assert usd_attribute == og.Controller.usd_attribute(attr_path) # Look up the USD attribute through its OmniGraph counterpart assert usd_attribute == og.Controller.usd_attribute(attribute) # Look up a list of attributes by passing a list of any of the above for new_usd_attribute in og.Controller.usd_attribute( [ usd_attribute, "/World/MyGraph/MyNode.inputs:a_bool", ("inputs:a_bool", node), ("inputs:a_bool", ("MyNode", graph)), attr_path, attribute, ] ): assert usd_attribute == new_usd_attribute # end-object-lookup-usd-attribute # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-usd-relationship # USD relationships can be looked up with the same parameters as for looking up an OmniGraph attribute. This applies # when the attribute is backed by a USD relationship instead of a USD attribute. usd_relationship = node_prim.GetRelationship("inputs:a_target") # Look up the USD relationship directly from itself (to simplify code) assert usd_relationship == og.Controller.usd_relationship(usd_relationship) # Look up the USD relationship by path assert usd_relationship == og.Controller.usd_relationship("/World/MyGraph/MyNode.inputs:a_target") # Look up the USD relationship by name and node assert usd_relationship == og.Controller.usd_relationship(("inputs:a_target", node)) # These can chain, so you can also look up the USD relationship by name and node, where node is further looked up by # relative path and graph assert usd_relationship == og.Controller.usd_relationship(("inputs:a_target", ("MyNode", graph))) # Look up the USD attribute by SdfPath relationship_path = Sdf.Path("/World/MyGraph/MyNode.inputs:a_target") assert usd_relationship == og.Controller.usd_relationship(relationship_path) # Look up the USD attribute through its OmniGraph counterpart assert usd_relationship == og.Controller.usd_relationship(relationship_attribute) # Look up a list of relationship by passing a list of any of the above for new_usd_relationship in og.Controller.usd_relationship( [ usd_relationship, "/World/MyGraph/MyNode.inputs:a_target", ("inputs:a_target", node), ("inputs:a_target", ("MyNode", graph)), relationship_path, relationship_attribute, ] ): assert usd_relationship == new_usd_relationship # end-object-lookup-usd-relationship # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-usd-property # USD properties can be looked up with the same parameters as for looking up an OmniGraph attribute. A property # is useful when it is not known ahead of time whether an og.Attribute is backed by a USD attribute or a USD relationship. # Look up the USD property directly from itself (to simplify code) assert usd_relationship == og.Controller.usd_property(usd_relationship) assert usd_attribute == og.Controller.usd_property(usd_attribute) # Look up the USD property by path assert usd_relationship == og.Controller.usd_property("/World/MyGraph/MyNode.inputs:a_target") assert usd_attribute == og.Controller.usd_property("/World/MyGraph/MyNode.inputs:a_bool") # Look up the USD property by name and node assert usd_relationship == og.Controller.usd_property(("inputs:a_target", node)) assert usd_attribute == og.Controller.usd_property(usd_attribute) # These can chain, so you can also look up the USD property by name and node, where node is further looked up by # relative path and graph assert usd_relationship == og.Controller.usd_property(("inputs:a_target", ("MyNode", graph))) assert usd_attribute == og.Controller.usd_property(("inputs:a_bool", ("MyNode", graph))) # Look up the USD property by SdfPath assert usd_relationship == og.Controller.usd_property(relationship_path) assert usd_attribute == og.Controller.usd_property(attr_path) # Look up the USD property through its OmniGraph counterpart assert usd_relationship == og.Controller.usd_property(relationship_attribute) assert usd_attribute == og.Controller.usd_property(usd_attribute) # Look up a list of properties by passing a list of any of the above for new_usd_property in og.Controller.usd_property( [ usd_relationship, usd_attribute, "/World/MyGraph/MyNode.inputs:a_target", "/World/MyGraph/MyNode.inputs:a_bool", ("inputs:a_target", node), ("inputs:a_bool", node), ("inputs:a_target", ("MyNode", graph)), ("inputs:a_bool", ("MyNode", graph)), relationship_path, attr_path, relationship_attribute, usd_attribute, ] ): assert new_usd_property in (usd_relationship, usd_attribute) # end-object-lookup-usd-property # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-variable # Look up the variable directly from itself (to simplify code) assert variable == og.Controller.variable(variable) # Look up the variable from a tuple with the variable name and the graph to which it belongs assert variable == og.Controller.variable((graph, "MyVariable")) # Look up the variable from a path string pointing directly to it assert variable == og.Controller.variable(variable.source_path) # Look up the variable from an Sdf.Path pointing directly to it variable_path = Sdf.Path(variable.source_path) assert variable == og.Controller.variable(variable_path) # Look up a list of variables by passing a list of any of the above for new_variable in og.Controller.variable( [ variable, (graph, "MyVariable"), variable.source_path, variable_path, ] ): assert variable == new_variable # end-object-lookup-variable # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-utilities # Look up the path to an attribute given any of the types an attribute lookup recognizes for attribute_spec in [ attribute, "/World/MyGraph/MyNode.inputs:a_bool", ("inputs:a_bool", node), ("inputs:a_bool", ("MyNode", graph)), attr_path, usd_attribute, ]: assert attribute.get_path() == og.Controller.attribute_path(attribute_spec) # Look up the path to a node given any of the types a node lookup recognizes for node_spec in [node, "/World/MyGraph/MyNode", ("MyNode", graph), node_path, node_prim]: assert node.get_prim_path() == og.Controller.node_path(node_spec) # Look up the path to a prim given any of the types a prim lookup recognizes for prim_spec in [node_prim, "/World/MyGraph/MyNode", node_path, node, ("MyNode", graph)]: assert node_prim.GetPrimPath() == og.Controller.prim_path(prim_spec) # Look up the path to a prim given any of the types a graph lookup recognizes graph_path = graph.get_path_to_graph() for graph_spec in [graph, graph_path, Sdf.Path(graph_path)]: assert graph_path == og.Controller.prim_path(graph_spec) # Look up a list of paths to prims given a list of any of the types a prim lookup recognizes for new_path in og.Controller.prim_path( [node_prim, "/World/MyGraph/MyNode", node_path, node, ("MyNode", graph)] ): assert node_prim.GetPrimPath() == new_path # Separate the graph name from the node name in a full path to a node assert (graph, "MyNode") == og.Controller.split_graph_from_node_path("/World/MyGraph/MyNode") # Separate the graph name from the node name in an Sdf.Path to a node assert (graph, "MyNode") == og.Controller.split_graph_from_node_path(node_path) # end-object-lookup-utilities # -------------------------------------------------------------------------------------------------------------- async def test_graph_controller_api(self): """Contrived test that exercises the entire API of the GraphController, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-graph-controller-XX pairs. """ # begin-graph-controller-boilerplate import omni.graph.core as og import omni.kit from pxr import Sdf node_type_name = "omni.graph.test.TestAllDataTypes" node_type = og.Controller.node_type(node_type_name) # end-graph-controller-boilerplate # begin-graph-controller-init # Explanation of the non-default values in the constructor controller = og.GraphController( update_usd=False, # Only update Fabric when paths are added are removed, do not propagate to USD undoable=False, # Do not save information on changes for later undo (most applicable to testing) # If a node specification in og.GraphController.create_node() exists then silently succeed instead of # raising an exception allow_exists_node=True, # If a prim specification in og.GraphController.create_prim() exists then silently succeed instead of # raising an exception allow_exists_prim=True, ) assert controller is not None # The default values are what is assumed when class methods are called. Where they apply to any of the # functions they can also be passed to the class method functions to specify non-default values. # end-graph-controller-init # begin-graph-controller-create_graph # Simple method of creating a graph just passes the desire prim path to it. This creates a graph using all # of the default parameters. graph = og.GraphController.create_graph("/World/MyGraph") assert graph.is_valid() # If you want to customize the type of graph then instead of passing just a path you can pass a dictionary # graph configuration values. See the developer documentation of omni.graph.core.GraphController.create_graph # for details on what each parameter means action_graph = og.GraphController.create_graph( { "graph_path": "/World/MyActionGraph", "node_name": "MyActionGraph", "evaluator_name": "execution", "is_global_graph": True, "backed_by_usd": True, "fc_backing_type": og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, "evaluation_mode": og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC, } ) # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-create_graph # begin-graph-controller-create_node # Creates a new node in an existing graph. # The two mandatory parameters are node path and node type. The node path can be any of the types recognized # by the omni.graph.core.ObjectLookup.node_path() method and the node type can be any of the types recognized # by the omni.graph.core.ObjectLookup.node_type() method. node_by_path = og.GraphController.create_node( node_id="/World/MyGraph/MyNode", node_type_id=node_type_name, ) assert node_by_path.is_valid() node_by_name = og.GraphController.create_node( node_id=("MyNodeByName", graph), node_type_id=node_type, ) assert node_by_name.is_valid() node_by_sdf_path = Sdf.Path("/World/MyGraph/MyNodeBySdf") node_by_sdf = og.GraphController.create_node(node_id=node_by_sdf_path, node_type_id=node_by_name) assert node_by_sdf.is_valid() # Also accepts the "update_usd", "undoable", and "allow_exists_node" shared construction parameters # end-graph-controller-create_node # begin-graph-controller-create_prim # Creates a new prim on the USD stage # You can just specify the prim path to get a default prim type with no attributes. The prim_path argument # can accept any value accepted by omni.graph.core.ObjectLookup.prim_path prim_empty = og.GraphController.create_prim(prim_path="/World/MyEmptyPrim") assert prim_empty.IsValid() # You can add a prim type if you want the prim to be a specific type, including schema types prim_cube = og.GraphController.create_prim(prim_path=Sdf.Path("/World/MyCube"), prim_type="Cube") assert prim_cube.IsValid() # You can also populate the prim with some attributes and values using the attribute_values parameter, which # accepts a dictionary of Name:(Type,Value). An attribute named "Name" will be created with type "Type" # (specified in either USD or SDF type format), and initial value "Value" (specified in any format compatible # with the Usd.Attribute.Set() function). The names do not have to conform to the usual OGN standards of # starting with one of the "inputs", "outputs", or "state" namespaces, though they can. The "Type" value is # restricted to the USD-native types, so things like "any", "bundle", and "execution" are not allowed. prim_with_values = og.GraphController.create_prim( prim_path="/World/MyValuedPrim", attribute_values={ "someFloat": ("float", 3.0), "inputs:float3": ("float3", [1.0, 2.0, 3.0]), "someFloat3": ("float[3]", [4.0, 5.0, 6.0]), "someColor": ("color3d", [0.5, 0.6, 0.2]), }, ) assert prim_with_values.IsValid() # Also accepts the "undoable" and "allow_exists_prim" shared construction parameters # end-graph-controller-create_prim # begin-graph-controller-create_variable # To construct a variable the graph must be specified, along with the name and type of variable. # The variable type can only be an omni.graph.core.Type or a string representing one of those types. float_variable = og.GraphController.create_variable(graph_id=graph, name="FloatVar", var_type="float") assert float_variable.valid color3_type = og.Type(og.BaseDataType.FLOAT, 3, role=og.AttributeRole.COLOR) color3_variable = og.GraphController.create_variable(graph_id=graph, name="Color3Var", var_type=color3_type) assert color3_variable.valid # Also accepts the "undoable" shared construction parameter # end-graph-controller-create_variable # begin-graph-controller-delete_node # To delete a node you can pass in a node_id, as accepted by omni.graph.core.ObjectLookup.node, or a node # name and a graph_id as accepted by omni.graph.core.ObjectLookup.graph. og.GraphController.delete_node(node_by_sdf) # The undo flag was the global default so this operation is undoable omni.kit.undo.undo() # HOWEVER, you must get the node reference back as it may have been altered by the undo node_by_sdf = og.Controller.node(node_by_sdf_path) # Try it a different way og.GraphController.delete_node(node_id="MyNodeBySdf", graph_id=graph) # If you do not know if the node exists or not you can choose to ignore that case and silently succeed og.GraphController.delete_node(node_id=node_by_sdf_path, ignore_if_missing=True) # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-delete_node # begin-graph-controller-expose_prim # USD prims cannot be directly visible in OmniGraph so instead you must expose them through an import or # export node. See the documentation of the function for details on the different ways you can expose a prim # to OmniGraph. # A prim is exposed as a new OmniGraph node of a given type where the exposure process creates the node and # the necessary links to the underlying prim. The OmniGraph node can then be used as any others might. # The prim_id can accept any type accepted by omni.graph.core.ObjectLookup.prim() and the node_path_id can # accept any type accepted by omni.graph.core.ObjectLookup.node_path() exposed_empty = og.GraphController.expose_prim( exposure_type=og.GraphController.PrimExposureType.AS_BUNDLE, prim_id="/World/MyEmptyPrim", node_path_id="/World/MyActionGraph/MyEmptyNode", ) assert exposed_empty is not None exposed_cube = og.GraphController.expose_prim( exposure_type=og.GraphController.PrimExposureType.AS_ATTRIBUTES, prim_id=prim_cube, node_path_id=("MyCubeNode", action_graph), ) assert exposed_cube is not None # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-expose_prim # begin-graph-controller-connect # Once you have more than one node in a graph you will want to connect them so that the results of one node's # computation can be passed on to another for further computation - the true power of OmniGraph. The connection # sends data from the attribute in "src_spec" and sends it to the attribute in "dst_spec". Both of those # parameters can accept anything accepted by omni.graph.core.ObjectLookup.attribute og.GraphController.connect( src_spec=("outputs:a_bool", ("MyNode", graph)), dst_spec="/World/MyGraph/MyNodeByName/outputs:a_bool", ) # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-connect # begin-graph-controller-disconnect # As part of wiring the nodes together you may also want to break connections, either to make a new connection # elsewhere or just to leave the attributes unconnected. The disconnect method is a mirror of the connect # method, taking the same parameters and breaking any existing connection between them. It is any error to try # to disconnect two unconnected attributes. og.GraphController.disconnect( src_spec=("outputs:a_bool", ("MyNode", graph)), dst_spec="/World/MyGraph/MyNodeByName/outputs:a_bool", ) omni.kit.undo.undo() # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-disconnect # begin-graph-controller-disconnect_all # Sometimes you don't know or don't care what an attribute is connected to, you just want to remove all of its # connections, both coming to and going from it. The single attribute_spec parameter tells which attribute is to # be disconnected, accepting any value accepted by omni.graph.ObjectLookup.attribute og.GraphController.disconnect_all(attribute_spec=("outputs:a_bool", ("MyNode", graph))) # As this just disconnects "all" if an attribute is not connected to anything it will silently succeed og.GraphController.disconnect_all(attribute_spec=("outputs:a_bool", ("MyNode", graph))) # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-disconnect_all # begin-graph-controller-set_variable_default_value # After creation a graph variable will have zeroes as its default value. You may want to set some other default # so that when the graph is instantiated a second time the defaults are non-zero. The variable_id parameter # accepts anything accepted by omni.graph.core.ObjectLookup.variable() and the value must be a data type # compatible with the type of the (already existing) variable # For example you might have a color variable that you wish to initialize in all subsequent graphs to red og.GraphController.set_variable_default_value(variable_id=(graph, "Color3Var"), value=(1.0, 0.0, 0.0)) # end-graph-controller-set_variable_default_value # begin-graph-controller-get_variable_default_value # If you are using variables to configure your graphs you probably want to know what the default values are, # especially if someone else created them. You can read the default for a given variable, where the variable_id # parameter accepts anything accepted by omni.graph.core.ObjectLookup.variable(). color_default = og.GraphController.get_variable_default_value(variable_id=color3_variable) assert color_default == (1.0, 0.0, 0.0) # end-graph-controller-get_variable_default_value # -------------------------------------------------------------------------------------------------------------- async def test_node_controller_api(self): """Contrived test that exercises the entire API of the NodeController, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-node-controller-XX pairs. """ # begin-node-controller-boilerplate import omni.graph.core as og keys = og.Controller.Keys (_, (node,), _, _) = og.Controller.edit( "/World/MyGraph", { keys.CREATE_NODES: ("MyNode", "omni.graph.test.TestAllDataTypes"), }, ) assert node.is_valid() # end-node-controller-boilerplate # begin-node-controller-init # The NodeController constructor only recognizes one parameter controller = og.NodeController( update_usd=False, # Only update Fabric when attributes are added or removed, do not propagate to USD ) assert controller is not None # end-node-controller-init # begin-node-controller-create_attribute # Creating new, or "dynamic", attributes on a node requires the same information you would find in a .ogn # description of the attribute. The mandatory pieces are "node" on which it is to be created, accepting # anything accepted by omni.graph.core.ObjectLookup.node, the name of the attribute not including the port # namespace (i.e. without the "inputs:", "outputs:", or "state:" prefix, though you can leave it on if you # prefer), the type "attr_type" of the attribute, accepting anything accepted by # omni.graph.core.ObjectLookup.attribute_type. # The default here is to create an input attribute of type float float_attr = og.NodeController.create_attribute(node, "theFloat", "float") assert float_attr.is_valid() # Using the namespace is okay, but redundant double_attr = og.NodeController.create_attribute("/World/MyGraph/MyNode", "inputs:theDouble", "double") assert double_attr.is_valid() # Unless you want a non-default port type, in which case it will be extracted from the name int_attr = og.NodeController.create_attribute(node, "outputs:theInt", og.Type(og.BaseDataType.INT)) assert int_attr.is_valid() # ...or you can just specify the port explicitly and omit the namespace int2_attr = og.NodeController.create_attribute( node, "theInt2", "int2", attr_port=og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) assert int2_attr.is_valid() # The default will set an initial value on your attribute, though it is not remembered in the future float_1_attr = og.NodeController.create_attribute(node, "the1Float", "float", attr_default=1.0) assert float_1_attr.is_valid() # Mismatching between an explicit namespace and a port type will result in a duplicated namespace so be careful error_attr = og.NodeController.create_attribute(node, "outputs:theError", "float") assert error_attr.get_path() == "/World/MyGraph/MyNode.inputs:outputs:theError" assert error_attr.is_valid() # Lastly the special "extended" types of attributes (any or union) can be explicitly specified through # the "attr_extended_type" parameter. When this is anything other than the default then the "attr_type" # parameter will be ignored in favor of the extended type definition, however it must still be a legal type. # This simplest type of extended attribute is "any", whose value can be any legal type. union_attr = og.NodeController.create_attribute( node, "theAny", attr_type="float", attr_extended_type=og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) assert union_attr.is_valid() # Note that with any extended type the "default" is invalid and will be ignored any_other_attr = og.NodeController.create_attribute( node, "theOtherAny", "token", default=5, attr_extended_type=og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) assert any_other_attr.is_valid() # If you want a more restricted set of types you can instead use the extended union type. When specifying # that type it will be a 2-tuple where the second value is a list of types accepted by the union. For example # this attribute will accept either doubles or floats as value types. (See the documentation on extended # attribute types for more information on how types are resolved.) union_attr = og.NodeController.create_attribute( node, "theUnion", "token", attr_extended_type=(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, ["double", "float"]), ) assert union_attr.is_valid() # Also accepts the "undoable" shared construction parameter # end-node-controller-create_attribute # begin-node-controller-remove_attribute # Dynamic attributes are a powerful method of reconfiguring a node at runtime, and as such you will also want # to remove them. The "attribute" parameter accepts anything accepted by # omni.graph.core.ObjectLookup.attribute(). (The "node" parameter, while still functional, is only there for # historical reasons and can be ignored.) og.NodeController.remove_attribute(error_attr) og.NodeController.remove_attribute(("inputs:theUnion", node)) # Also accepts the "undoable" shared construction parameter # end-node-controller-remove_attribute # begin-node-controller-safe_node_name # This is a utility you can use to ensure a node name is safe for use in the USD backing prim. Normally # OmniGraph will take care of this for you but if you wish to dynamically create nodes using USD names you can # use this to confirm that your name is safe for use as a prim. assert og.NodeController.safe_node_name("omni.graph.node.name") == "omni_graph_node_name" # There is also an option to use a shortened name rather than replacing dots with underscores assert og.NodeController.safe_node_name("omni.graph.node.name", abbreviated=True) == "name" # end-node-controller-safe_node_name # -------------------------------------------------------------------------------------------------------------- async def test_data_view_api(self): """Contrived test that exercises the entire API of the DataView, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-data-view-XX pairs. """ # begin-data-view-boilerplate import omni.graph.core as og keys = og.Controller.Keys (_, (node, any_node,), _, _) = og.Controller.edit( "/World/MyGraph", { keys.CREATE_NODES: [ ("MyNode", "omni.graph.test.TestAllDataTypes"), ("MyAnyNode", "omni.graph.tutorials.ExtendedTypes"), ], keys.SET_VALUES: [ ("MyNode.inputs:a_int", 3), ], }, ) int_attr = og.Controller.attribute("inputs:a_int", node) union_attr = og.Controller.attribute("inputs:floatOrToken", any_node) float_array_attr = og.Controller.attribute("outputs:a_float_array", node) double_array_attr = og.Controller.attribute("outputs:a_double_array", node) # end-data-view-boilerplate # begin-data-view-init # The DataView constructor can take a number of parameters, mostly useful if you intend to make repeated # calls with the same configuration. # The most common parameter is the attribute on which you will operate. The parameter accepts anything # accepted by omni.graph.core.ObjectLookup.attribute() per_attr_view = og.DataView(attribute=int_attr) assert per_attr_view # Subsequent calls to per_attr_view functions will always apply to "int_attr" # You can also force USD and undo configurations, as per other classes like omni.graph.core.NodeController do_now = og.DataView(update_usd=False, undoable=False) assert do_now is not None # To keep memory operations on a single device you can configure the DataView to always use the GPU gpu_view = og.DataView(on_gpu=True, gpu_ptr_kind=og.PtrToPtrKind.CPU) # You can retrieve the GPU pointer kind (i.e. where the memory pointing to GPU arrays lives) assert gpu_view.gpu_ptr_kind == og.PtrToPtrKind.CPU # And if you are working with an instanced graph you can isolate the DataView to a single instance. Also # handy for looping through different instances. instance_view = og.DataView(instance=1) assert instance_view is not None # end-data-view-init # begin-data-view-get # Reading the value of an attribute is the most common operation you'll want to use. assert og.DataView.get(attribute=int_attr) == 3 # If you've already configured the attribute you don't need to specify it, and you can reuse it assert per_attr_view.get() == 3 assert per_attr_view.get() == 3 # As a special case, when you have array attributes that you want to write on you can specify an array size # when you get the reference with the "reserved_element_count" parameter array_to_write = og.DataView.get(attribute=float_array_attr) assert len(array_to_write) == 2 array_to_write = og.DataView.get(attribute=float_array_attr, reserved_element_count=5) assert len(array_to_write) == 5 # Only valid on GPU array attributes is the "return_type" argument. Normally array values are returned in # numpy wrappers, however you can get the data as raw pointers as well if you want to handle processing of # the data yourself or cast it to some other library type. This also illustrates how you can use the # pre-configured constructed GPU view to get specific attribute values on the GPU. raw_array = gpu_view.get(attribute=double_array_attr, return_type=og.WrappedArrayType.RAW) # The return value is omni.graph.core.DataWrapper, which describes its device-specific data and configuration assert raw_array.gpu_ptr_kind == og.PtrToPtrKind.CPU # Also accepts overrides to the global parameters "on_gpu", "gpu_ptr_kind", and "instance" # end-data-view-get # begin-data-view-get_array_size # An array size may be set without actually allocating space for it. In the case of very large arrays this can # be quite useful. The get_array_size function lets you find the number of elements that will be in the array # if you request the data, either on GPU or CPU. assert og.DataView.get_array_size(float_array_attr) == 5 # Also accepts overrides to the global parameter "instance" # end-data-view-get_array_size # begin-data-view-set # The counterpart to getting values is of course setting them. Normally through this interface you will be # setting values on input attributes, or sometimes state attributes, relying on the generated database to # provide the interface for setting output values as part of your node's compute function. # The "attribute" parameter accepts anything accepted by omni.graph.core.ObjectLookup.attribute(), and the # "value" parameter must be a legal value for the attribute type. og.DataView.set(attribute=int_attr, value=5) assert og.DataView.get(int_attr) == 5 # An optional "update_usd" argument does what you'd expect, preventing the update of the USD backing value # for the attribute you just set. await og.Controller.evaluate() og.DataView.set(int_attr, value=10, update_usd=False) usd_attribute = og.ObjectLookup.usd_attribute(int_attr) assert usd_attribute.Get() != 10 # The values being set are flexible as well, with the ability to use a dictionary format so that you can set # the type for any of the extended attributes. og.DataView.set(union_attr, value={"type": "float", "value": 3.5}) assert og.DataView.get(union_attr) == 3.5 # Also accepts overrides to the global parameters "on_gpu", "gpu_ptr_kind", and "instance" # end-data-view-set # begin-data-view-context # Sometimes you are calling unknown code and you want to ensure USD updates are performed the way you want # them. The DataView class provides a method that returns a contextmanager for just such a purpose. with og.DataView.force_usd_update(False): int_view = og.DataView(int_attr) int_view.set(value=20) # The USD value does not update, even though normally the default is to update assert usd_attribute.Get() != 20 with og.DataView.force_usd_update(True): int_view = og.DataView(int_attr) int_view.set(value=30) # The USD value updates assert usd_attribute.Get() == 30 # end-data-view-context
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_node_type_forwarding.py
"""Tests that exercise node type forwarding using real node types as examples""" import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts # ============================================================================================================== class TestNodeTypeForwarding(ogts.OmniGraphTestCase): async def test_simple_forward(self): """Test that a simple forwarding using a known hardcoded forwarding works properly""" old_type = "omni.graph.nodes.ComposeTuple2" new_type = "omni.graph.nodes.MakeVector2" new_extension = "omni.graph.nodes" interface = ogu.get_node_type_forwarding_interface() self.assertEqual(interface.find_forward(old_type, 1), (new_type, 1, new_extension)) keys = og.Controller.Keys (_, (node,), _, _) = og.Controller.edit("/TestGraph", {keys.CREATE_NODES: ("ForwardedNode", old_type)}) self.assertEqual(node.get_node_type().get_node_type(), new_type) # -------------------------------------------------------------------------------------------------------------- async def test_runtime_forward(self): """Test that a forwarding that is added at runtime works properly""" old_type = "omni.graph.nodes.MakeVector2" new_type = "omni.graph.nodes.MakeVector3" new_extension = "omni.graph.nodes" interface = ogu.get_node_type_forwarding_interface() interface.define_forward(old_type, 1, new_type, 1, new_extension) self.assertEqual(interface.find_forward(old_type, 1), (new_type, 1, new_extension)) keys = og.Controller.Keys (graph, (node,), _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: ("ForwardedNode", old_type), }, ) # Make sure the node type was properly forwarded self.assertEqual(node.get_node_type().get_node_type(), new_type) # Remove the forwarding and check that the same creation type now yields the original unforwarded node type interface.remove_forward(old_type, 1) (_, (new_node,), _, _) = og.Controller.edit( graph, { keys.CREATE_NODES: ("RegularNode", old_type), }, ) self.assertEqual(new_node.get_node_type().get_node_type(), old_type)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_simple.py
"""Basic tests of the compute graph""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.kit.undo import omni.usd import omni.usd.commands class TestOmniGraphSimple(ogts.OmniGraphTestCase): """Run a simple unit test that exercises graph functionality""" # ---------------------------------------------------------------------- async def test_undo_dangling_connections(self): # If a dangling connection (see previous test) is created by an undoable # command, the connection should be restored if the command is undone. (_, (src_node, dest_node), _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("src", "omni.graph.tutorials.SimpleData"), ("dest", "omni.graph.tutorials.SimpleData"), ], og.Controller.Keys.CONNECT: [("src.outputs:a_float", "dest.inputs:a_float")], }, ) src_attr = src_node.get_attribute("outputs:a_float") dest_attr = dest_node.get_attribute("inputs:a_float") # Check that the connection is there, on both sides. self.assertEqual(len(src_attr.get_downstream_connections()), 1, "Check initial connection, src side.") self.assertEqual(len(dest_attr.get_upstream_connections()), 1, "Check initial connection, dest side.") # Delete the src prim and confirm that the connection is gone. omni.kit.commands.execute("DeletePrims", paths=[src_node.get_prim_path()]) self.assertEqual(len(dest_attr.get_upstream_connections()), 0, "Check no connection after deletion.") # Undo the deletion. omni.kit.undo.undo() # Wait a couple of ticks for OG to restore everything. for _ in range(2): await omni.kit.app.get_app().next_update_async() # Check that the connection has been restored. src_attr = og.Controller.attribute("/World/PushGraph/src.outputs:a_float") conns = src_attr.get_downstream_connections() self.assertEqual(len(conns), 1, "Check connection exists after undo, src side.") self.assertEqual(conns[0], dest_attr, "Check connection is correct after undo, src side.") conns = dest_attr.get_upstream_connections() self.assertEqual(len(conns), 1, "Check connection exists after undo, dest side.") self.assertEqual(conns[0], src_attr, "Check connection is correct after undo, dest side.") # Redo the deletion. omni.kit.undo.redo() self.assertEqual(len(dest_attr.get_upstream_connections()), 0, "Check no connection after redo.") # Undo the redo. omni.kit.undo.undo() # Wait a couple of ticks for OG to restore everything. for _ in range(2): await omni.kit.app.get_app().next_update_async() # Check that the connection has been restored. src_attr = og.Controller.attribute("/World/PushGraph/src.outputs:a_float") conns = src_attr.get_downstream_connections() self.assertEqual(len(conns), 1, "Check connection exists after undo of redo, src side.") self.assertEqual(conns[0], dest_attr, "Check connection is correct after undo of redo, src side.") conns = dest_attr.get_upstream_connections() self.assertEqual(len(conns), 1, "Check connection exists after undo of redo, dest side.") self.assertEqual(conns[0], src_attr, "Check connection is correct after undo of redo, src side.") # ---------------------------------------------------------------------- async def test_disconnect(self): """ Check that after a disconnection, we find the default value at input runtime location, and that the output still has a correct value """ (_, _, _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("src", "omni.graph.tutorials.SimpleData"), ("dest", "omni.graph.tutorials.SimpleData"), ], og.Controller.Keys.CONNECT: [("src.outputs:a_float", "dest.inputs:a_float")], }, ) dst_attr = og.Controller.attribute("/World/PushGraph/dest.inputs:a_float") src_attr = og.Controller.attribute("/World/PushGraph/src.outputs:a_float") await og.Controller.evaluate() # since both attribute are connected, they now have the same value: the compute result self.assertEqual(dst_attr.get(), 1) self.assertEqual(src_attr.get(), 1) # do the disconnect src_attr.disconnect(dst_attr, True) # we get back the default on the input, the output still has the compute result self.assertEqual(dst_attr.get(), 0) self.assertEqual(src_attr.get(), 1) # ---------------------------------------------------------------------- async def test_unknown_type(self): """ Basic idea of test: Load up an existing file that has an unknown type, and make sure that we are not creating a node for it. """ (result, error) = await ogts.load_test_file("TestNodeWithUnknownType.usda", use_caller_subdirectory=True) self.assertTrue(result, error) await omni.kit.app.get_app().next_update_async() graph = og.Controller.graph("/World/Graph") unknown_node = graph.get_node("/World/Graph/SomeUnknownNode") self.assertFalse(unknown_node.is_valid()) # ---------------------------------------------------------------------- async def test_file_format_upgrade(self): """ Basic idea of test: Register a file format upgrade callback. Load up file with bad node type name, and fix it as part of the file format upgrade. """ def my_test_pre_load_file_format_upgrade_callback(_old_format_version, _new_format_version, _graph): usd_context = omni.usd.get_context() stage = usd_context.get_stage() subtract_double_node_prim = stage.GetPrimAtPath("/World/innerPushGraph/test_node_subtract_double_c_") self.assertTrue(subtract_double_node_prim.IsValid()) node_type_attr = subtract_double_node_prim.GetAttribute("node:type") node_type_attr.Set("omni.graph.test.SubtractDoubleC") handle = og.register_pre_load_file_format_upgrade_callback(my_test_pre_load_file_format_upgrade_callback) try: (result, error) = await ogts.load_test_file("TestBadNodeTypeName.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = og.get_graph_by_path("/World/innerPushGraph") # make sure the box and the attribute we expect are there. node = graph.get_node("/World/innerPushGraph/test_node_subtract_double_c_") self.assertTrue(node.is_valid()) self.assertEqual(node.get_node_type().get_node_type(), "omni.graph.test.SubtractDoubleC") finally: og.deregister_pre_load_file_format_upgrade_callback(handle) # ---------------------------------------------------------------------- async def test_controller_on_initialize(self): # Basic idea of test: here we have a test node that uses the og.Controller at initialize # Time. There was a bug that made this not possible. We test for a clean open here without # errors. See https://nvidia.slack.com/archives/CN05UCXT5/p1614278655049700 for details (result, error) = await ogts.load_test_file("TestInitWithController.usda", use_caller_subdirectory=True) self.assertTrue(result, error) # ---------------------------------------------------------------------- async def test_is_compatible(self): """ Test Attribute.is_compatible() for extended and simple types. `is_compatible` is verified for a representitive sample of connection combinations, bad_connections are connections that should be rejected, ok_connections are connections that should be approved. Note that this test is meant to take into account (and test!) the auto-conversion mechanism """ controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("TupleA", "omni.tutorials.TupleData"), ("ArrayA", "omni.graph.tutorials.ArrayData"), ("TupleArrayA", "omni.graph.tutorials.TupleArrays"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ("TupleB", "omni.tutorials.TupleData"), ("ArrayB", "omni.graph.tutorials.ArrayData"), ("TupleArrayB", "omni.graph.tutorials.TupleArrays"), ("ExtendedA", "omni.graph.tutorials.ExtendedTypes"), ("ExtendedB", "omni.graph.tutorials.ExtendedTypes"), ] }, ) await controller.evaluate(graph) # Helper for doing verification on a list of connection specs between 2 nodes def verify_connections(connections, should_work): for src, dest in connections: src_node, src_attr = src.split(".", 1) dest_node, dest_attr = dest.split(".", 1) src_attrib = controller.node(src_node, graph).get_attribute(src_attr) dest_attrib = controller.node(dest_node, graph).get_attribute(dest_attr) if should_work: self.assertTrue( src_attrib.is_compatible(dest_attrib), f"{src_node}.{src_attr} is compatible with {dest_node}.{dest_attr}", ) else: self.assertFalse( src_attrib.is_compatible(dest_attrib), f"{src_node}.{src_attr} is not compatible with {dest_node}.{dest_attr}", ) # Test simple connections ok_connections = [ ("SimpleA.outputs:a_int", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_int", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:a_int", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_int", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_int"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_float"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_double"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:unsigned:a_uint64"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:unsigned:a_uint64"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_int"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:unsigned:a_uint64"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_float"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_double"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:unsigned:a_uint"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_half", "SimpleB.inputs:a_half"), ] bad_connections = [ ("SimpleA.outputs:a_bool", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_bool", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_float", "SimpleB.inputs:unsigned:a_uint"), ("SimpleA.outputs:a_int", "SimpleB.inputs:unsigned:a_uint64"), ("SimpleA.outputs:a_half", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_half"), # FIXME: What about input -> output? # ('SimpleB.inputs:a_float', 'SimpleA.outputs:a_float') ] verify_connections(ok_connections, True) verify_connections(bad_connections, False) # Test tuple connections ok_connections = [ ("TupleA.outputs:a_float2", "TupleB.inputs:a_double2"), ("TupleA.outputs:a_int2", "TupleB.inputs:a_int2"), ("TupleA.outputs:a_float2", "TupleB.inputs:a_float2"), ("TupleA.outputs:a_double3", "TupleB.inputs:a_double3"), ("TupleA.outputs:a_float3", "TupleB.inputs:a_float3"), ] bad_connections = [ ("TupleA.outputs:a_double2", "TupleB.inputs:a_double3"), ("TupleA.outputs:a_half2", "TupleB.inputs:a_float2"), ("TupleA.outputs:a_half2", "SimpleB.inputs:a_half"), ("TupleA.outputs:a_double3", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_double", "TupleB.inputs:a_double3"), ] verify_connections(ok_connections, True) verify_connections(bad_connections, False) # Test array connections ok_connections = [ ("ArrayA.outputs:result", "ArrayB.inputs:original"), ("ArrayA.outputs:negativeValues", "ArrayB.inputs:gates"), ] bad_connections = [ ("ArrayA.outputs:result", "ArrayB.inputs:gates"), ("ArrayA.outputs:result", "TupleB.inputs:a_float3"), ] verify_connections(ok_connections, True) verify_connections(bad_connections, False) # Test tuple-array connections ok_connections = [("TupleArrayA.inputs:a", "TupleArrayB.inputs:b")] bad_connections = [ ("TupleArrayA.inputs:a", "ArrayB.inputs:original"), ("TupleArrayA.outputs:result", "TupleArrayB.inputs:a"), ] verify_connections(ok_connections, True) verify_connections(bad_connections, False) # Test 'any' and enum connections ok_connections = [ ("ExtendedA.outputs:doubledResult", "ExtendedB.inputs:tuple"), ("ExtendedA.outputs:flexible", "ExtendedB.inputs:floatOrToken"), ("ExtendedA.outputs:tuple", "TupleB.inputs:a_double3"), ("ExtendedA.outputs:flexible", "ExtendedB.inputs:flexible"), ] verify_connections(ok_connections, True) # incompatible enum connections bad_connections = [ ("ExtendedA.outputs:flexible", "SimpleB.inputs:a_double"), ("SimpleB.outputs:a_double", "ExtendedA.inputs:flexible"), ] verify_connections(bad_connections, False) # Wire up ExtendedA in order to resolve doubledResult to be token, and verify the check fails # also resolve outputs:tuple to be int[2], and verify the check fails controller.edit( "/TestGraph", { keys.CONNECT: [ ("SimpleA.outputs:a_token", "ExtendedA.inputs:floatOrToken"), ("TupleA.outputs:a_int2", "ExtendedA.inputs:tuple"), # FIXME: Do I need to connect the output in order to resolve the type? ("ExtendedA.outputs:doubledResult", "SimpleB.inputs:a_token"), ] }, ) ok_connections = [("TupleA.outputs:a_float2", "ExtendedA.inputs:tuple")] verify_connections(ok_connections, True) bad_connections = [ ("ExtendedA.outputs:doubledResult", "SimpleB.inputs:a_float"), ("ExtendedA.inputs:floatOrToken", "SimpleB.inputs:a_float"), ("SimpleB.inputs:a_float", "ExtendedA.inputs:floatOrToken"), ] verify_connections(bad_connections, False) # ---------------------------------------------------------------------- async def test_simple_converted_connections(self): """ Test conversions between simple types. `simple_converted_connections` tests a representitive sample of connection combinations of different types, and makes sure the expected values are actually retrieved """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ], "connect": [ ("SimpleA.outputs:a_double", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_int", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_int"), ], "set_values": [ ("SimpleA.inputs:a_double", 10.5), ("SimpleA.inputs:a_int", 11), ("SimpleA.inputs:a_int64", 12), ("SimpleA.inputs:a_float", 13.5), ], }, ) await controller.evaluate() simple_b_node = nodes[1] # A.input.a_double (10.5) -> A.output.a_double (11.5) -> B.input.a_float(11.5) -> B.output.a_float(12.5) self.assertEqual(simple_b_node.get_attribute("outputs:a_float").get(), 12.5) # A.input.a_int64 (12) -> A.output.a_int64 (13) -> B.input.a_double(13.0) -> B.output.a_double(14.0) self.assertEqual(simple_b_node.get_attribute("outputs:a_double").get(), 14.0) # A.input.a_float (13.5) -> A.output.a_float (14.5) -> B.input.a_int(14) -> B.output.a_int(15) self.assertEqual(simple_b_node.get_attribute("outputs:a_int").get(), 15) # A.input.a_int (11) -> A.output.a_int (12) -> B.input.a_bool(True) -> B.output.a_bool(False) self.assertFalse(simple_b_node.get_attribute("outputs:a_bool").get()) # ---------------------------------------------------------------------- async def test_tuple_converted_connections(self): """ Test conversions between tuple types. `tuple_converted_connections` tests a representitive sample of connection combinations of different types, and makes sure the expected values are actually retrieved """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [("TupleA", "omni.tutorials.TupleData"), ("TupleB", "omni.tutorials.TupleData")], "connect": [ ("TupleA.outputs:a_double2", "TupleB.inputs:a_float2"), ("TupleA.outputs:a_int2", "TupleB.inputs:a_double2"), ("TupleA.outputs:a_float2", "TupleB.inputs:a_int2"), ("TupleA.outputs:a_float3", "TupleB.inputs:a_double3"), ("TupleA.outputs:a_double3", "TupleB.inputs:a_float3"), ], "set_values": [ ("TupleA.inputs:a_double2", (10.5, 11.5)), ("TupleA.inputs:a_int2", (13, 14)), ("TupleA.inputs:a_float2", (15.5, 16.5)), ("TupleA.inputs:a_float3", (17.5, 18.5, 19.5)), ("TupleA.inputs:a_double3", (20.5, 21.5, 22.5)), ], }, ) await controller.evaluate() tuple_b_node = nodes[1] # A.input.a_double2 (10.5,11.5) -> A.output.a_double2 (11.5,12.5) # -> B.input.a_float2(11.5, 12.5) -> B.output.a_float2(12.5,13.5) self.assertTrue((tuple_b_node.get_attribute("outputs:a_float2").get() == (12.5, 13.5)).all()) # A.input.a_int2 (13,14) -> A.output.a_int2 (14,15) # -> B.input.a_double2(14.0, 15.0) -> B.output.a_double2(15.0, 16.0) self.assertTrue((tuple_b_node.get_attribute("outputs:a_double2").get() == (15.0, 16.0)).all()) # A.input.a_float2 (15.5, 16.5) -> A.output.a_float2 (16.5, 17.5) # -> B.input.a_int2(16, 17) -> B.output.a_int2(17, 18) self.assertTrue((tuple_b_node.get_attribute("outputs:a_int2").get() == (17, 18)).all()) # A.input.a_float3 (17.5, 18.5, 19.5) -> A.output.a_float3 (18.5, 19.5, 20.5) # -> B.input.a_double3(18.5, 19.5, 20.5) -> B.output.a_double3(19.5, 20.5, 21.5) self.assertTrue((tuple_b_node.get_attribute("outputs:a_double3").get() == (19.5, 20.5, 21.5)).all()) # A.input.a_double3 (20.5,21.5,22.5) -> A.output.a_double3 (21.5,22.5, 23.5) # -> B.input.a_float3(21.5,22.5, 23.5) -> B.output.a_float3(22.5, 23.5, 24.5) self.assertTrue((tuple_b_node.get_attribute("outputs:a_float3").get() == (22.5, 23.5, 24.5)).all()) # ---------------------------------------------------------------------- async def test_converted_runtime_connections(self): """ Test conversions of runtime attributes ie. when the actual type of the attribute is not listed in the list of accepted input types, but a conversion exits """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [ ("Simple", "omni.graph.tutorials.SimpleData"), ("Extended", "omni.graph.tutorials.ExtendedTypes"), ], "connect": [("Simple.outputs:a_double", "Extended.inputs:floatOrToken")], "set_values": [ ("Simple.inputs:a_double", 1.5), ("Simple.inputs:a_int", 2), ("Simple.inputs:a_float", 3.5), ], }, ) await controller.evaluate() ext_node = nodes[1] # Simple.in.a_double (1.5) -> Simple.out.a_double (2.5) -> Extended.floatOrToken (2.5) -> Extended.doubled (5.0) val = ext_node.get_attribute("outputs:doubledResult").get() self.assertTrue(val == 5.0) # ---------------------------------------------------------------------- async def test_converted_prefered_runtime_connections(self): """ Test that the proper conversion of runtime attribute is chosen when several are available """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [ ("Simple", "omni.graph.tutorials.SimpleData"), ("A", "omni.graph.nodes.ATan2"), ("A2", "omni.graph.nodes.ATan2"), ], "connect": [("Simple.outputs:a_int", "A.inputs:a"), ("Simple.outputs:a_int64", "A2.inputs:a")], }, ) t = nodes[1].get_attribute("inputs:a").get_resolved_type().base_type self.assertTrue(t == og.BaseDataType.FLOAT) t = nodes[2].get_attribute("inputs:a").get_resolved_type().base_type self.assertTrue(t == og.BaseDataType.DOUBLE) # ---------------------------------------------------------------------- async def test_converted_coupled_attributes(self): """ Tests that the conversion for coupled attribute type resolution works """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [ ("Mul", "omni.graph.nodes.Multiply"), ("Double", "omni.graph.nodes.ConstantDouble"), ("Float", "omni.graph.nodes.ConstantFloat"), ], "connect": [("Double.inputs:value", "Mul.inputs:a"), ("Float.inputs:value", "Mul.inputs:b")], "set_values": [("Double.inputs:value", 5.0), ("Float.inputs:value", 10.0)], }, ) await controller.evaluate() out = nodes[0].get_attribute("outputs:product") # the first pin is used to determine the output type base_type = out.get_resolved_type().base_type self.assertTrue(base_type == og.BaseDataType.DOUBLE) # check that the node executed correctly val = out.get() self.assertTrue(val == 50)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_compound_subgraphs.py
# noqa PLC0302 from typing import List import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts import omni.usd from pxr import Sdf COMPOUND_SUBGRAPH_NODE_TYPE = "omni.graph.nodes.CompoundSubgraph" DEFAULT_SUBGRAPH_NAME = "Subgraph" # ----------------------------------------------------------------------------- class TestCompoundSubgraphs(ogts.OmniGraphTestCase): """Tests functionality using subgraph-style compound nodes""" _test_graph_path = "/World/TestGraph" # ------------------------------------------------------------------------- async def setUp(self): await super().setUp() omni.kit.commands.set_logging_enabled(False) # ------------------------------------------------------------------------- async def tearDown(self): omni.timeline.get_timeline_interface().stop() await super().tearDown() omni.kit.commands.set_logging_enabled(True) # ------------------------------------------------------------------------- def _get_input_attributes(self, node: og.Node) -> List[og.Attribute]: return [ attr for attr in node.get_attributes() if attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ] # ------------------------------------------------------------------------- def _get_output_attributes(self, node: og.Node) -> List[og.Attribute]: return [ attr for attr in node.get_attributes() if attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ] # ------------------------------------------------------------------------- async def test_compound_subgraph_placeholder_node(self): """Validation For the placeholder node used for compound subgraph nodes""" controller = og.Controller(update_usd=True) keys = controller.Keys (_, (node,), _, _) = controller.edit( self._test_graph_path, {keys.CREATE_NODES: ("PlaceHolder", COMPOUND_SUBGRAPH_NODE_TYPE)} ) self.assertTrue(node.is_valid()) self.assertTrue(node.is_compound_node()) def is_input_or_output(attr): return attr.get_port_type() in [ og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ] self.assertEqual(0, len(list(filter(is_input_or_output, node.get_attributes())))) stage = omni.usd.get_context().get_stage() self.assertTrue(stage.GetPrimAtPath(f"{node.get_prim_path()}/{DEFAULT_SUBGRAPH_NAME}").IsValid()) # ------------------------------------------------------------------------ async def test_create_compound_subgraph_command(self): """Validates the create compound subgraph command, including undo and redo""" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, _, _, _) = controller.edit(self._test_graph_path, {keys.CREATE_NODES: ("Add", "omni.graph.nodes.Add")}) # create a compound subgraph with the default name stage = omni.usd.get_context().get_stage() # validate the node is created ogu.cmds.CreateCompoundSubgraph(graph=graph, node_name="Node1", subgraph_name=DEFAULT_SUBGRAPH_NAME) node = graph.get_node(f"{self._test_graph_path}/Node1") subgraph_path = f"{node.get_prim_path()}/{DEFAULT_SUBGRAPH_NAME}" self.assertTrue(node.is_valid()) self.assertTrue(stage.GetPrimAtPath(subgraph_path).IsValid()) omni.kit.undo.undo() node = graph.get_node(f"{self._test_graph_path}/Node1") self.assertFalse(node.is_valid()) self.assertFalse(stage.GetPrimAtPath(subgraph_path).IsValid()) omni.kit.undo.redo() node = graph.get_node(f"{self._test_graph_path}/Node1") self.assertTrue(node.is_valid()) self.assertTrue(stage.GetPrimAtPath(subgraph_path).IsValid()) # validate with a different subgraph name subgraph2_name = f"{DEFAULT_SUBGRAPH_NAME}_02" ogu.cmds.CreateCompoundSubgraph(graph=graph, node_name="Node2", subgraph_name=subgraph2_name) node = graph.get_node(f"{self._test_graph_path}/Node2") subgraph_path = f"{node.get_prim_path()}/{subgraph2_name}" self.assertTrue(node.is_valid()) self.assertTrue(stage.GetPrimAtPath(subgraph_path).IsValid()) # ------------------------------------------------------------------------ async def test_compound_subgraph_loaded_from_file(self): """Validates that a compound node with a subgraph can be loaded and evaluated""" (result, error) = await ogts.load_test_file("TestCompoundSubgraph.usda", use_caller_subdirectory=True) self.assertTrue(result, f"{error}") # The file contains an outer graph of # [const_double] -> [compound] -> [to_string] # Followed by an inner compound containing an add node graph = og.get_graph_by_path("/World/PushGraph") self.assertTrue(graph.is_valid()) self.assertEquals(1, len(graph.get_subgraphs())) compound_node = graph.get_node("/World/PushGraph/compound") self.assertTrue(compound_node.is_valid()) self.assertTrue(compound_node.is_compound_node()) self.assertTrue(compound_node.get_node_type().is_valid()) result_node = graph.get_node("/World/PushGraph/to_string") self.assertTrue(result_node.is_valid()) output_attr = result_node.get_attribute("outputs:converted") self.assertTrue(output_attr.is_valid()) await og.Controller.evaluate(graph) self.assertEqual("20", og.Controller.get(output_attr)) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph(self): """Tests for replacing a portion of a graph with a subgraph""" compound_node_name = "Compound" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (_, _, _, add, mul, _), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("ConstDouble1", "omni.graph.nodes.ConstantDouble"), ("ConstDouble2", "omni.graph.nodes.ConstantDouble"), ("ConstDouble3", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ("Mul", "omni.graph.nodes.Multiply"), ("ToDouble", "omni.graph.nodes.ToDouble"), ], keys.CONNECT: [ ("ConstDouble1.inputs:value", "Add.inputs:a"), ("ConstDouble2.inputs:value", "Add.inputs:b"), ("ConstDouble3.inputs:value", "Mul.inputs:b"), ("Add.outputs:sum", "Mul.inputs:a"), ("Mul.outputs:product", "ToDouble.inputs:value"), ], keys.SET_VALUES: [ ("ConstDouble1.inputs:value", 1.0), ("ConstDouble2.inputs:value", 2.0), ("ConstDouble3.inputs:value", 3.0), ], }, ) # evaluate the graph with a given constant value. async def validate_graph(c1_val): # update the constant and verify the graph is still functioning c1_attr = og.Controller.attribute(f"{self._test_graph_path}/ConstDouble1.inputs:value") og.Controller.set(c1_attr, c1_val, undoable=False) await og.Controller.evaluate(graph) res_attr = og.Controller.attribute(f"{self._test_graph_path}/ToDouble.outputs:converted") self.assertEqual((c1_val + 2.0) * 3.0, og.Controller.get(res_attr)) await validate_graph(1.0) # the command will invalidate any og references to the graph ogu.cmds.ReplaceWithCompoundSubgraph( nodes=[add.get_prim_path(), mul.get_prim_path()], compound_name=compound_node_name ) # validate the replacement generated the objects we are expecting graph = og.Controller.graph(self._test_graph_path) sub_graph_path = f"{self._test_graph_path}/{compound_node_name}/{DEFAULT_SUBGRAPH_NAME}" self.assertTrue(graph.is_valid()) self.assertTrue(og.Controller.graph(sub_graph_path).is_valid()) self.assertIsNone(og.get_node_by_path(f"{self._test_graph_path}/Add")) self.assertIsNone(og.get_node_by_path(f"{self._test_graph_path}/Mul")) self.assertTrue(og.Controller.node(f"{sub_graph_path}/Add").is_valid()) self.assertTrue(og.Controller.node(f"{sub_graph_path}/Mul").is_valid()) # update the constant and verify the graph is still functioning await validate_graph(2.0) # apply an undo omni.kit.undo.undo() graph = og.Controller.graph(self._test_graph_path) sub_graph_path = f"{self._test_graph_path}/{compound_node_name}/{DEFAULT_SUBGRAPH_NAME}" self.assertTrue(graph.is_valid()) self.assertIsNone(og.get_graph_by_path(sub_graph_path)) self.assertTrue(og.Controller.node(f"{self._test_graph_path}/Add").is_valid()) self.assertTrue(og.Controller.node(f"{self._test_graph_path}/Mul").is_valid()) self.assertIsNone(og.get_node_by_path(f"{sub_graph_path}/Add")) self.assertIsNone(og.get_node_by_path(f"{sub_graph_path}/Mul")) # update the constant and verify the graph is still functioning await validate_graph(3.0) # and a redo omni.kit.undo.redo() graph = og.Controller.graph(self._test_graph_path) sub_graph_path = f"{self._test_graph_path}/{compound_node_name}/{DEFAULT_SUBGRAPH_NAME}" self.assertTrue(graph.is_valid()) self.assertTrue(og.Controller.graph(sub_graph_path).is_valid()) self.assertIsNone(og.get_node_by_path(f"{self._test_graph_path}/Add")) self.assertIsNone(og.get_node_by_path(f"{self._test_graph_path}/Mul")) self.assertTrue(og.Controller.node(f"{sub_graph_path}/Add").is_valid()) self.assertTrue(og.Controller.node(f"{sub_graph_path}/Mul").is_valid()) # update the constant and verify the graph is still functioning await validate_graph(4.0) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_input_resolved_types(self): """ Tests which inputs are exposed in a generated compound graph When all the types are resolved """ def _create_compound_graph(evaluator_name): controller = og.Controller(update_usd=True) keys = controller.Keys graph_path = f"{self._test_graph_path}_{evaluator_name}" # simple graph # [ConstDouble]->[AllTypes]->[AllTypes (via execution)] controller.edit({"graph_path": graph_path, "evaluator_name": evaluator_name}) (_, (all1, all2, _), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("AllTypes1", "omni.graph.test.TestAllDataTypes"), ("AllTypes2", "omni.graph.test.TestAllDataTypes"), ("ConstDouble", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("AllTypes1.outputs:a_execution", "AllTypes2.inputs:a_execution"), ("ConstDouble.inputs:value", "AllTypes1.inputs:a_double"), ], }, ) (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[all1.get_prim_path(), all2.get_prim_path()]) self.assertTrue(success) self.assertTrue(node.is_valid()) return self._get_input_attributes(node) # for push, expect 1 exposed input, the constant double input_ports = _create_compound_graph("push") self.assertEquals(1, len(input_ports)) self.assertEquals(og.Type(og.BaseDataType.DOUBLE), input_ports[0].get_resolved_type()) # for action graph, the execution port should also be exposed input_ports = _create_compound_graph("execution") input_types = [input_port.get_resolved_type() for input_port in input_ports] self.assertEquals(2, len(input_ports)) self.assertIn(og.Type(og.BaseDataType.DOUBLE), input_types) self.assertIn(og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION), input_types) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_input_unresolved_types(self): """ Tests the replace with compound subgraph exposes any unresolved types """ # Partially connected graph of add nodes # [Add1]->[Add2]->[Add3] # Add1 a,b are left unresolved # Add2 a is connected, b is resolved # Add3 a is connected, b is unresolved controller = og.Controller(update_usd=True) keys = controller.Keys (_, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Add1", "omni.graph.nodes.Add"), ("Add2", "omni.graph.nodes.Add"), ("Add3", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Add1.outputs:sum", "Add2.inputs:a"), ("Add2.outputs:sum", "Add3.inputs:a"), ], }, ) # manually resolve nodes[1].get_attribute("inputs:b").set_resolved_type(og.Type(og.BaseDataType.DOUBLE)) # create the subgraph (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[node.get_prim_path() for node in nodes]) self.assertTrue(success) self.assertTrue(node.is_valid()) inputs = self._get_input_attributes(node) outputs = self._get_output_attributes(node) self.assertEqual(3, len(inputs)) self.assertEqual(1, len(outputs)) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_output_types(self): """ Validates the behaviour of outputs when a compound replacement is made. If a node is a terminal node, it's outputs will be exposed """ # create a graph with two nodes that contain a near complete subset of all types def _create_compound_graph(evaluator_name): controller = og.Controller(update_usd=True) keys = controller.Keys graph_path = f"{self._test_graph_path}_{evaluator_name}" # simple graph # [AllTypes]->[AllTypes] with one connection in between controller.edit({"graph_path": graph_path, "evaluator_name": evaluator_name}) (_, (all1, all2), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("AllTypes1", "omni.graph.test.TestAllDataTypes"), ("AllTypes2", "omni.graph.test.TestAllDataTypes"), ], keys.CONNECT: [("AllTypes1.outputs:a_double", "AllTypes2.inputs:a_double")], }, ) (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[all1.get_prim_path(), all2.get_prim_path()]) self.assertTrue(success) self.assertTrue(node.is_valid()) output_types = [attr.get_resolved_type() for attr in self._get_output_attributes(node)] return output_types # in the case of a push graph, it will generate an output for each type, except execution output_types = _create_compound_graph("push") push_count = len(output_types) self.assertEqual(0, output_types.count(og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION))) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.DOUBLE))) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.INT))) # in the case of a push graph, it will generate an output for each type, except execution output_types = _create_compound_graph("execution") exec_count = len(output_types) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION))) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.DOUBLE))) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.INT))) self.assertGreater(exec_count, push_count) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_fan_in_out(self): """Validates replace with compound subgraph works with fan in/out""" controller = og.Controller(update_usd=True) keys = controller.Keys # Graph with Fan-In and Fan-Out # [OnImpulseEvent]-> |Sequence| -> [Sequence] # [OnImpulseEvent]-> | | -> [Sequence] controller.edit({"graph_path": self._test_graph_path, "evaluator_name": "execution"}) (_, (_, _, convert, _, _), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Input1", "omni.graph.action.OnImpulseEvent"), ("Input2", "omni.graph.action.OnImpulseEvent"), ("Convert", "omni.graph.action.Sequence"), ("Output1", "omni.graph.action.Sequence"), ("Output2", "omni.graph.action.Sequence"), ], keys.CONNECT: [ ("Input1.outputs:execOut", "Convert.inputs:execIn"), ("Input2.outputs:execOut", "Convert.inputs:execIn"), ("Convert.outputs:a", "Output1.inputs:execIn"), ("Convert.outputs:a", "Output2.inputs:execIn"), ], }, ) (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[convert.get_prim_path()]) self.assertTrue(success) self.assertTrue(node.is_valid()) inputs = self._get_input_attributes(node) outputs = self._get_output_attributes(node) self.assertEquals(1, len(inputs)) self.assertEquals(1, len(outputs)) self.assertEquals(2, inputs[0].get_upstream_connection_count()) self.assertEquals(2, outputs[0].get_downstream_connection_count()) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_with_constant_nodes(self): """ Validates replace with compound subgraph works with constant nodes, that use output only inputs """ controller = og.Controller(update_usd=True) keys = controller.Keys # Create a graph with a connected constant and an unconnected constant # Converting the constants to a subgraph should create outputs for both # but keep the connection in tact (_, (c1, c2, _), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Const1", "omni.graph.nodes.ConstantDouble"), ("Const2", "omni.graph.nodes.ConstantInt"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Const1.inputs:value", "Add.inputs:a"), ], }, ) (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[c1.get_prim_path(), c2.get_prim_path()]) self.assertTrue(success) self.assertTrue(node.is_valid()) outputs = self._get_output_attributes(node) self.assertEquals(2, len(outputs)) self.assertEquals(1, outputs[0].get_downstream_connection_count()) self.assertEquals(0, outputs[1].get_downstream_connection_count()) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_catches_common_errors(self): """ Validates ReplaceWithCompoundSubgraph handles typical error conditions """ controller = og.Controller(update_usd=True) keys = controller.Keys (graph1, (add1,), _, _) = controller.edit( self._test_graph_path, {keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add")]} ) (_, (add2,), _, _) = controller.edit( f"{self._test_graph_path}_2", {keys.CREATE_NODES: [("Add2", "omni.graph.nodes.Add")]} ) with ogts.ExpectedError(): # no nodes means no compound is returned (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[]) self.assertFalse(success) self.assertIsNone(node) # not all nodes from the same graph with ogts.ExpectedError(): (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[add1.get_prim_path(), add2.get_prim_path()]) self.assertFalse(success) self.assertIsNone(node) # invalid nodes with ogts.ExpectedError(): (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph( nodes=[add1.get_prim_path(), graph1.get_path_to_graph()] ) self.assertFalse(success) self.assertIsNone(node) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_with_relationship_inputs(self): """Validates ReplacewithCompoundSubgraph handles relationship inputs (bundles and targets)""" controller = og.Controller(update_usd=True) keys = controller.Keys # Graph with various types relationship inputs # [BundleConstructor] -> [BundleInspector] # [BundleInspector (with target set)] # [BundleInspector (with target unset)] # [GetGraphTargetPrim] -> [GetPrimPaths] # [GetPrimPaths (with target set)] # [GetPrimPaths (with target unset)] (_graph, _, _, _) = controller.edit( self._test_graph_path, { # create nodes that have bundle inputs and target inputs keys.CREATE_NODES: [ ("BundleCreator", "omni.graph.nodes.BundleConstructor"), ("ConnectedInspector", "omni.graph.nodes.BundleInspector"), ("SetInspector", "omni.graph.nodes.BundleInspector"), ("UnsetInspector", "omni.graph.nodes.BundleInspector"), ("GraphTargetPrim", "omni.graph.nodes.GetGraphTargetPrim"), ("ConnectedTarget", "omni.graph.nodes.GetPrimPaths"), ("SetTarget", "omni.graph.nodes.GetPrimPaths"), ("UnsetTarget", "omni.graph.nodes.GetPrimPaths"), ], keys.CONNECT: [ ("BundleCreator.outputs_bundle", "ConnectedInspector.inputs:bundle"), ("GraphTargetPrim.outputs:prim", "ConnectedTarget.inputs:prims"), ], keys.CREATE_PRIMS: [("Prim", "Cube")], keys.SET_VALUES: [ ("SetTarget.inputs:prims", f"{self._test_graph_path}/Prim"), ], }, ) # set the bundle manually stage = omni.usd.get_context().get_stage() stage.GetRelationshipAtPath(f"{self._test_graph_path}/SetInspector.inputs:bundle").SetTargets( [f"{self._test_graph_path}/Prim"] ) # Replace the bundle inspector with a compound subgraph. Use names since a conversion can make # previous node handles invalid nodes_to_replace = [ "ConnectedInspector", "SetInspector", "UnsetInspector", "ConnectedTarget", "SetTarget", "UnsetTarget", ] compounds = [] for node_name in nodes_to_replace: node = og.Controller.node(f"{self._test_graph_path}/{node_name}") (success, compound_node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[node]) self.assertTrue(success) self.assertTrue(compound_node.is_valid()) compounds.append(compound_node.get_prim_path()) def validate_result(compound_node_path, node_name, attr_name, expected_target): # make sure the inner node was created node = og.Controller.node(f"{compound_node_path}/Subgraph/{node_name}") self.assertTrue(node.is_valid()) # make sure the relationship has the expected value rel = stage.GetRelationshipAtPath(f"{node.get_prim_path()}.{attr_name}") self.assertTrue(rel.IsValid()) self.assertEquals(expected_target, rel.GetTargets()) # validate the inner node have the expected connection validate_result(compounds[0], nodes_to_replace[0], "inputs:bundle", [f"{compounds[0]}.inputs:bundle"]) validate_result(compounds[1], nodes_to_replace[1], "inputs:bundle", [f"{self._test_graph_path}/Prim"]) validate_result(compounds[2], nodes_to_replace[2], "inputs:bundle", []) validate_result(compounds[3], nodes_to_replace[3], "inputs:prims", [f"{compounds[3]}.inputs:prims"]) validate_result(compounds[4], nodes_to_replace[4], "inputs:prims", [f"{self._test_graph_path}/Prim"]) validate_result(compounds[5], nodes_to_replace[5], "inputs:prims", []) def get_input_count(node_path: str): node = og.Controller.node(node_path) self.assertTrue(node.is_valid()) return len( [ attr for attr in node.get_attributes() if attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ] ) # validate that the new compounds have the correct number of inputs. They will have an input if they were connected # via a node connection self.assertEqual(get_input_count(compounds[0]), 1) self.assertEqual(get_input_count(compounds[1]), 0) self.assertEqual(get_input_count(compounds[2]), 0) self.assertEqual(get_input_count(compounds[3]), 1) self.assertEqual(get_input_count(compounds[4]), 0) self.assertEqual(get_input_count(compounds[5]), 0) # validate the inputs have the correct target values self.assertEquals( stage.GetRelationshipAtPath(f"{compounds[0]}.inputs:bundle").GetTargets(), [f"{self._test_graph_path}/BundleCreator/outputs_bundle"], ) self.assertEquals( stage.GetRelationshipAtPath(f"{compounds[3]}.inputs:prims").GetTargets(), [f"{self._test_graph_path}/GraphTargetPrim.outputs:prim"], ) # ------------------------------------------------------------------------ async def test_promoted_bundle_inputs_retain_values(self): """Test that when a bundle input is promoted from a compound, it retains the value that was set for it""" controller = og.Controller(update_usd=True) keys = controller.Keys (_graph, (compound,), (prim,), node_map) = controller.edit( self._test_graph_path, { keys.CREATE_PRIMS: [("/World/Prim", "Cube")], keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: ("Inspector", "omni.graph.nodes.BundleInspector"), }, ) ], }, ) # Set the bundle input on the compound node path = f"{node_map['Inspector'].get_prim_path()}.inputs:bundle" print(path) rel = omni.usd.get_context().get_stage().GetRelationshipAtPath(path) self.assertTrue(rel.IsValid()) rel.SetTargets([prim.GetPath()]) # Promote the input controller.edit(self._test_graph_path, {keys.PROMOTE_ATTRIBUTES: ("Inspector.inputs:bundle", "inputs:bundle")}) # get the bundle relationship on the promoted node rel = omni.usd.get_context().get_stage().GetRelationshipAtPath(f"{compound.get_prim_path()}.inputs:bundle") self.assertTrue(rel.IsValid()) self.assertEquals(str(rel.GetTargets()[0]), str(prim.GetPath())) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_with_relationship_outputs(self): """Tests that ReplaceWithCompoundSubgraph works with relationship outputs produces errors as is is currently not supported. """ # # [BundleConstructor]->[BundleInspector] controller = og.Controller(update_usd=True) keys = controller.Keys (_graph, (bundle_constructor, _bundle_inspector), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constructor", "omni.graph.nodes.BundleConstructor"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: [ ("Constructor.outputs_bundle", "Inspector.inputs:bundle"), ], }, ) # Attempt to replace the bundle constructor with a compound subgraph. with ogts.ExpectedError(): (success, compound_node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[bundle_constructor]) self.assertFalse(success) self.assertIsNone(compound_node) # ------------------------------------------------------------------------ async def test_replace_with_subgraph_handles_target_types(self): """Tests that ReplaceWithCompoundSubgraph works with target inputs and outputs""" # Create a graph with the following setup # |--------------------| |-------------------| # [GetPrimPath]-|o-[GetPrimsAtPath]-o|-->|o-[GetPrimsPaths]-o|->[GetPrimsAtPath] # |--------------------| |-------------------| controller = og.Controller(update_usd=True) keys = controller.Keys (graph, nodes, (prim, prim1, prim2), _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("P0", "omni.graph.nodes.GetPrimPath"), ("P1", "omni.graph.nodes.GetPrimsAtPath"), ("P2", "omni.graph.nodes.GetPrimPaths"), ("P3", "omni.graph.nodes.GetPrimsAtPath"), ], keys.CONNECT: [ ("P0.outputs:primPath", "P1.inputs:path"), ("P1.outputs:prims", "P2.inputs:prims"), ("P2.outputs:primPaths", "P3.inputs:path"), ], keys.CREATE_PRIMS: [ ("/World/Prim", "Cube"), ("/World/Prim1", "Cube"), ("/World/Prim2", "Cube"), ], keys.SET_VALUES: [ ("P0.inputs:prim", "/World/Prim"), ], }, ) # save the node paths, since the nodes can become invalid on a replace call node_paths = [og.Controller.node_path(node) for node in nodes] await og.Controller.evaluate(graph) attr = og.Controller.attribute("outputs:prims", nodes[3]) self.assertEqual(str(prim.GetPath()), str(og.Controller.get(attr)[0])) # replace node with string input, path output p1 = og.Controller.node(node_paths[1]) (success, c1) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[p1]) self.assertTrue(success) self.assertTrue(c1.is_valid()) self.assertGreater(og.Controller.attribute(("inputs:path", c1)).get_upstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("inputs:path", c1)).get_downstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("outputs:prims", c1)).get_upstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("outputs:prims", c1)).get_downstream_connection_count(), 0) # evaluate with a new input and makes sure the output through the compounds is correct og.Controller.set(og.Controller.attribute(f"{node_paths[0]}/inputs:prim"), prim1.GetPath()) await og.Controller.evaluate(graph) p3 = og.Controller.node(node_paths[3]) attr = og.Controller.attribute("outputs:prims", p3) self.assertEqual(str(prim1.GetPath()), str(og.Controller.get(attr)[0])) # replace node with path input, path string output p2 = og.Controller.node(node_paths[2]) (success, c2) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[p2]) self.assertTrue(success) self.assertTrue(c2.is_valid()) self.assertGreater(og.Controller.attribute(("inputs:prims", c2)).get_upstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("inputs:prims", c2)).get_downstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("outputs:primPaths", c2)).get_upstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("outputs:primPaths", c2)).get_downstream_connection_count(), 0) # evaluate with a new input and makes sure the output through the compounds is correct og.Controller.set(og.Controller.attribute(f"{node_paths[0]}/inputs:prim"), prim2.GetPath()) await og.Controller.evaluate(graph) p3 = og.Controller.node(node_paths[3]) attr = og.Controller.attribute("outputs:prims", p3) self.assertEqual(str(prim2.GetPath()), str(og.Controller.get(attr)[0])) # ------------------------------------------------------------------------ async def test_replace_with_subgraph_in_nested_compounds_types(self): """Tests that replace with compound subgraph works with nested compounds""" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (_,), _, nodes) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "OuterCompound", { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ("Add.inputs:b", "inputs:b"), ("Add.outputs:sum", "outputs:sum"), ], }, ) ], }, ) graph_path = graph.get_path_to_graph() (success, c1) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[nodes["Add"]]) self.assertTrue(success) self.assertTrue(c1.is_valid()) compound_graph = c1.get_compound_graph_instance() self.assertTrue(compound_graph.is_valid()) self.assertTrue(compound_graph.get_node(f"{compound_graph.get_path_to_graph()}/Add").is_valid()) outer_compound = og.Controller.node(f"{graph_path}/OuterCompound") self.assertEqual(c1.get_graph().get_owning_compound_node(), outer_compound) # create an extra level of compounds by replacing the new compound with a compound # [OuterCompound] -> [C1] -> [Add] becomes # [OuterCompound] -> [C2] -> [C1] -> [Add] (success, c2) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[c1]) self.assertTrue(success) self.assertTrue(c2.is_valid()) outer_compound = og.Controller.node(f"{graph_path}/OuterCompound") self.assertEquals(c2.get_graph().get_owning_compound_node(), outer_compound) compound_graph = c2.get_compound_graph_instance() sub_graph_node = compound_graph.get_nodes()[0] self.assertTrue(sub_graph_node.is_compound_node()) self.assertTrue(sub_graph_node.get_compound_graph_instance().is_valid()) add_node = sub_graph_node.get_compound_graph_instance().get_nodes()[0] self.assertTrue(add_node.is_valid()) self.assertEqual(Sdf.Path(add_node.get_prim_path()).name, "Add") # --------------------------------------------------------------------- async def test_subgraph_with_constants_evaluates(self): """Tests that a subgraph with no inputs evaluates correctly in a push graph setup""" # Create a subgraph/graph pair with the following setup # # |--------------------------------------| # | [Constant]----->|----------| | # | [Constant]----->| Add |-----> o | ---> [Magnitude] # | |----------| | # | -------------------------------------| controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (constant1, constant2, add, abs_node), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant1", "omni.graph.nodes.ConstantDouble"), ("Constant2", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ("Abs", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Constant1.inputs:value", "Add.inputs:a"), ("Constant2.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "Abs.inputs:input"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 5.0), ("Constant2.inputs:value", 1.0), ], }, ) await og.Controller.evaluate(graph) attr = og.Controller.attribute(("outputs:magnitude", abs_node)) self.assertEqual(6.0, og.Controller.get(attr)) # push the variable nodes into a subgraph (_, compound_node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[constant1, constant2, add]) self.assertIsNotNone(compound_node) self.assertTrue(compound_node.is_valid()) # update the constant so we get different result constant = og.Controller.node(f"{compound_node.get_prim_path()}/Subgraph/Constant2") constant_attr = og.Controller.attribute(("inputs:value", constant)) og.Controller.set(constant_attr, 2.0) await og.Controller.evaluate(graph) abs_node = og.Controller.node(f"{self._test_graph_path}/Abs") attr = og.Controller.attribute(("outputs:magnitude", abs_node)) self.assertEqual(7.0, og.Controller.get(attr)) # --------------------------------------------------------------------- async def test_attribute_promotion_supports_fan_in(self): """Tests than an attribute that supports fan-in can be promoted, even if connected or already promoted""" # Creates a graph where an execution pin is both connected internally and promoted twice # |---------------------------------------------------------------| # | -------------- | # | o----------------->|o execIn | | # | o----------------->| | | # | /\-------------- | # | ----------- | | # | |execOut o|-----| | # | ----------- | # | | # |---------------------------------------------------------------| controller = og.Controller(update_usd=True) keys = controller.Keys og.Controller.edit({"graph_path": self._test_graph_path, "evaluator_name": "execution"}) (_, _, _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ("NodeA", "omni.graph.action.Counter"), ("NodeB", "omni.graph.action.Counter"), ], keys.CONNECT: [ ("NodeB.outputs:execOut", "NodeA.inputs:execIn"), ], keys.PROMOTE_ATTRIBUTES: [ ("NodeA.inputs:execIn", "execIn1"), ("NodeA.inputs:execIn", "execIn2"), ], }, ) ] }, ) compound_node = node_map["Compound"] self.assertEqual(len(self._get_input_attributes(compound_node)), 2) node_a = node_map["NodeA"] self.assertEqual(len(node_a.get_attribute("inputs:execIn").get_upstream_connections()), 3) # --------------------------------------------------------------------- async def test_attribute_promotion_rejects_fan_in(self): """Test that validates that promotion of non-fan-in attributes is rejected""" controller = og.Controller(update_usd=True) keys = controller.Keys with self.assertRaises(og.OmniGraphError): (_, _, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ("NodeA", "omni.graph.nodes.Add"), ], keys.PROMOTE_ATTRIBUTES: [ ("NodeA.inputs:a", "a1"), ("NodeA.inputs:a", "a2"), ], }, ) ] }, ) # --------------------------------------------------------------------- async def test_compound_graph_exec_ports_support_fan_in(self): """Test that validates compounds can support fan in on exec ports""" controller = og.Controller(update_usd=True) keys = controller.Keys # ------------- |----------------------------| # [OnTick]--->|Multigate o|---->|o-->[Counter]------------->o| # | o|---->| | # | o| | | # ------------- |----------------------------| og.Controller.edit({"graph_path": self._test_graph_path, "evaluator_name": "execution"}) (_, (compound, mg, _), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ("Counter", "omni.graph.action.Counter"), ], keys.PROMOTE_ATTRIBUTES: [ ("Counter.inputs:execIn", "inputs:execIn"), ("Counter.outputs:count", "outputs:count"), ], }, ), ("Multigate", "omni.graph.action.Multigate"), ("Tick", "omni.graph.action.OnTick"), ], keys.CREATE_ATTRIBUTES: [ ("Multigate.outputs:output1", og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION)), ("Multigate.outputs:output2", og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION)), ], keys.CONNECT: [ ("Tick.outputs:tick", "Multigate.inputs:execIn"), ("Multigate.outputs:output0", "Compound.inputs:execIn"), ("Multigate.outputs:output1", "Compound.inputs:execIn"), ], }, ) omni.timeline.get_timeline_interface().play() # evaluate the graph a bunch of times. The counter should update 2 of every 3 times counter = compound.get_attribute("outputs:count") for _ in range(0, 8): await omni.kit.app.get_app().next_update_async() expected_counter = int(mg.get_compute_count() / 3) * 2 + (mg.get_compute_count() % 3) self.assertGreater(og.Controller.get(counter), 0) self.assertEqual(expected_counter, og.Controller.get(counter)) # --------------------------------------------------------------------- async def test_rename_compound_subgraph(self): """Validates that a compound subgraph can be successfully renamed""" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, _, _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ( "Compound2", { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ("Add.inputs:b", "inputs:b"), ("Add.outputs:sum", "outputs:sum"), ], }, ), ], keys.PROMOTE_ATTRIBUTES: [ ("Compound2.inputs:a", "inputs:a"), ("Compound2.inputs:b", "inputs:b"), ("Compound2.outputs:sum", "outputs:sum"), ], }, ), ("Constant1", "omni.graph.nodes.ConstantDouble"), ("Constant2", "omni.graph.nodes.ConstantDouble"), ("Output", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Constant1.inputs:value", "Compound.inputs:a"), ("Constant2.inputs:value", "Compound.inputs:b"), ("Compound.outputs:sum", "Output.inputs:input"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 1.0), ("Constant2.inputs:value", 2.0), ], }, ) # iterate the paths from deepest to shallowest paths = [ node_map["Compound2"].get_prim_path(), node_map["Compound"].get_prim_path(), ] const_2_path = node_map["Constant2"].get_attribute("inputs:value").get_path() output_attr = node_map["Output"].get_attribute("outputs:magnitude").get_path() input_value = 2.0 # noqa SIM113 expected_result = 3.0 await og.Controller.evaluate(graph) self.assertEquals(expected_result, og.Controller.get(og.Controller.attribute(output_attr))) for path in paths: # rename the compound node specified by path compound = og.Controller.node(path).get_compound_graph_instance() old_name = compound.get_path_to_graph() new_name = old_name + "_renamed" omni.kit.commands.execute("RenameCompoundSubgraph", subgraph=compound, new_path=new_name) # increment the expected result input_value += 1.0 og.Controller.set(og.Controller.attribute(const_2_path), input_value) expected_result = input_value + 1.0 await og.Controller.evaluate(graph) # reload the compound node. the rename will have invalidated the node self.assertEquals(expected_result, og.Controller.get(og.Controller.attribute(output_attr))) # --------------------------------------------------------------------- async def tests_created_compounds_are_ineligible_for_delete(self): """Tests that compound subgraphs are flagged as ineligible for deletion""" controller = og.Controller(update_usd=True) keys = controller.Keys (_, (compound,), _, _) = controller.edit( self._test_graph_path, {keys.CREATE_NODES: [("Compound", {keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add")]})]}, ) subgraph_path = compound.get_compound_graph_instance().get_path_to_graph() # suppress the warning. The command will succeed regardless, but print out a warning with ogts.ExpectedError(): omni.kit.commands.execute("DeletePrims", paths=[subgraph_path]) # validate that the prim still exists stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(subgraph_path) self.assertTrue(prim.IsValid()) self.assertTrue(compound.get_compound_graph_instance().is_valid()) # --------------------------------------------------------------------- async def tests_broken_compounds_produces_error(self): """Tests that a broken compound will produce error msgs when evaluated""" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, _, _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add")], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ("Add.inputs:b", "inputs:b"), ("Add.outputs:sum", "outputs:sum"), ], }, ), ("Constant1", "omni.graph.nodes.ConstantDouble"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 1.0), ], keys.CONNECT: [ ("Constant1.inputs:value", "Compound.inputs:a"), ("Constant1.inputs:value", "Compound.inputs:b"), ], }, ) compound_path = node_map["Compound"].get_prim_path() subgraph_path = node_map["Compound"].get_compound_graph_instance().get_path_to_graph() stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(subgraph_path) self.assertTrue(prim.IsValid()) prim.SetMetadata("no_delete", False) omni.kit.commands.execute("DeletePrims", paths=[subgraph_path]) # suppress the error that is expected with ogts.ExpectedError(): await og.Controller.evaluate(graph) node = og.Controller.node(compound_path) self.assertTrue(node.is_valid()) msgs = node.get_compute_messages(og.Severity.ERROR) self.assertTrue(len(msgs) > 0) # ----------------------------------------------------------------------------- async def tests_rename_compound_command(self): """Tests the rename compound command""" controller = og.Controller(update_usd=True) keys = controller.Keys (_, _, _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound1", {keys.CREATE_NODES: [("Add1", "omni.graph.nodes.Add")]}), ("Compound2", {keys.CREATE_NODES: [("Add2", "omni.graph.nodes.Add")]}), ("Compound3", {keys.CREATE_NODES: [("Add3", "omni.graph.nodes.Add")]}), ("Compound4", {keys.CREATE_NODES: [("Add4", "omni.graph.nodes.Add")]}), ("Compound5", {keys.CREATE_NODES: [("Add5", "omni.graph.nodes.Add")]}), ] }, ) graph_paths = [ og.Controller.prim_path(node_map[f"Compound{idx}"].get_compound_graph_instance()) for idx in range(1, 6) ] # success case with undo og._unstable.cmds.RenameCompoundSubgraph( # noqa: PLW0212 subgraph=graph_paths[0], new_path=graph_paths[0] + "_renamed" ) await omni.kit.app.get_app().next_update_async() self.assertTrue(og.Controller.graph(graph_paths[0] + "_renamed")) omni.kit.undo.undo() await omni.kit.app.get_app().next_update_async() self.assertTrue(og.Controller.graph(graph_paths[0])) omni.kit.undo.redo() await omni.kit.app.get_app().next_update_async() self.assertTrue(og.Controller.graph(graph_paths[0] + "_renamed")) # failure case - bad path with ogts.ExpectedError(): (res, _) = og._unstable.cmds.RenameCompoundSubgraph( # noqa: PLW0212 subgraph=graph_paths[1], new_path="This is an invalid path" ) self.assertFalse(res) # failure case - rename to an invalid name in immediate mode with ogts.ExpectedError(): self.assertIsNone( og._unstable.cmds.imm.RenameCompoundSubgraph( # noqa: PLW0212 subgraph=graph_paths[2], new_path="invalid name" ) ) # pass by graph og._unstable.cmds.RenameCompoundSubgraph( # noqa: PLW0212 subgraph=og.Controller.graph(graph_paths[3]), new_path=graph_paths[3] + "_renamed" ) await omni.kit.app.get_app().next_update_async() self.assertTrue(og.Controller.graph(graph_paths[3] + "_renamed")) # failure case - path is not a child of the compound node with ogts.ExpectedError(): self.assertIsNone( og._unstable.cmds.imm.RenameCompoundSubgraph(graph_paths[4], "/World/OtherPath") # noqa: PLW0212 ) # ----------------------------------------------------------------------------- class TestCompoundSubgraphAttributeCommands(ogts.OmniGraphTestCase): """Tests related to commands to add, remove and rename attributes from compound nodes containing a subgraph """ _test_graph_path = "/World/TestGraph" # ------------------------------------------------------------------------- async def setUp(self): await super().setUp() # Set up a subgraph node as follows # The composedouble3 node as fixed-type inputs, so they aren't exposed # |-------------------------------------| # [Constant] --> | o(a) -->|------| | # | | Add1 | | # [Constant] --> | o(b) -->|------| --> |------| | # | | Add2 | --> o |-->[Add3] # | o(b_01) -----------> |------| | # | | # | |----------------| | # | | ComposeDouble3 | --> o | # | |----------------| | # |-------------------------------------| # # The inputs are a, b, b_01 # The outputs are sum and double3 controller = og.Controller(update_usd=True) keys = controller.Keys ( _, (self._constant_node_1, self._constant_node_2, self._compound_node, self._add3_node), _, mapping, ) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant1", "omni.graph.nodes.ConstantDouble"), ("Constant2", "omni.graph.nodes.ConstantDouble"), ( "Compound", { keys.CREATE_NODES: [ ("Add1", "omni.graph.nodes.Add"), ("Add2", "omni.graph.nodes.Add"), ("ComposeDouble3", "omni.graph.test.ComposeDouble3C"), ], keys.CONNECT: [ ("Add1.outputs:sum", "Add2.inputs:a"), ], keys.SET_VALUES: [ ("ComposeDouble3.inputs:x", 5.0), ], keys.PROMOTE_ATTRIBUTES: [ ("Add1.inputs:a", "a"), ("Add1.inputs:b", "b"), ("Add2.inputs:b", "b_01"), ("Add2.outputs:sum", "sum"), ("ComposeDouble3.outputs:double3", "double3"), ], }, ), ("Add3", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Constant1.inputs:value", "Compound.inputs:a"), ("Constant2.inputs:value", "Compound.inputs:b"), ("Compound.outputs:sum", "Add3.inputs:a"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 5.0), ], }, ) self._add1_node = mapping["Add1"] self._add2_node = mapping["Add2"] self._compose_node = mapping["ComposeDouble3"] self._compound_input_1 = og.ObjectLookup.attribute(("inputs:a", self._compound_node)) self._compound_input_2 = og.ObjectLookup.attribute(("inputs:b", self._compound_node)) self._compound_input_3 = og.ObjectLookup.attribute(("inputs:b_01", self._compound_node)) self._compound_output_1 = og.ObjectLookup.attribute(("outputs:sum", self._compound_node)) self._compound_output_2 = og.ObjectLookup.attribute(("outputs:double3", self._compound_node)) self._subgraph = og.ObjectLookup.graph(f"{self._compound_node.get_prim_path()}/Subgraph") # disable logging of command errors omni.kit.commands.set_logging_enabled(False) # ------------------------------------------------------------------------- async def tearDown(self): await super().tearDown() omni.kit.commands.set_logging_enabled(True) # ------------------------------------------------------------------------- async def test_create_input_command(self): """Test that input connections can be successfully added and works with undo and redo""" connect_to_attr = og.ObjectLookup.attribute(("inputs:x", self._compose_node)) (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=connect_to_attr ) self.assertTrue(success) self.assertTrue(attr.is_valid()) self.assertTrue(attr.get_downstream_connections()[0], connect_to_attr) # validate the value was copied up to the graph self.assertEqual(og.Controller.get(attr), 5.0) omni.kit.undo.undo() self.assertTrue(self._compound_node.is_valid()) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(("inputs:added_input", self._compound_node)) self.assertEqual(og.Controller.get(connect_to_attr), 5.0) omni.kit.undo.redo() self.assertTrue(self._compound_node.is_valid()) attr = og.ObjectLookup.attribute(("inputs:added_input", self._compound_node)) self.assertTrue(attr.is_valid()) self.assertTrue(attr.get_downstream_connections()[0], connect_to_attr) self.assertEqual(og.Controller.get(attr), 5.0) # --------------------------------------------------------------------------- async def test_resolved_attribute_values_are_copied_on_create(self): """Tests that resolved attribute values are copied when used with create input""" # create a new node in the graph new_node = og.GraphController.create_node( node_id=("Add4", self._subgraph), node_type_id="omni.graph.nodes.Add", update_usd=True ) attr = og.ObjectLookup.attribute(("inputs:a", new_node)) attr.set_resolved_type(og.Type(og.BaseDataType.DOUBLE)) og.Controller.set(attr, 10.0, update_usd=True) self.assertEqual(og.Controller.get(attr), 10.0) (success, compound_attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=attr ) self.assertTrue(success) self.assertTrue(compound_attr.is_valid()) self.assertEqual(10, og.Controller.get(compound_attr)) # --------------------------------------------------------------------------- async def test_create_input_error_cases(self): """Validates known failure cases for create input commands""" # 1) connecting to an attribute not in the subgraph with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=og.ObjectLookup.attribute("inputs:b", self._add3_node), ) self.assertTrue(success) self.assertIsNone(attr) # 2) connecting to no/invalid attribute with self.assertRaises(og.OmniGraphError): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=None ) with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to="/World/Path.inputs:not_valid" ) self.assertTrue(success) self.assertIsNone(attr) # 3) connecting to an existing attribute name with ogts.ExpectedError(): connect_to_attr = og.ObjectLookup.attribute(("inputs:x", self._compose_node)) (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="a", connect_to=connect_to_attr ) self.assertTrue(success) self.assertIsNone(attr) # 4) connecting to a non-compound node with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._add3_node, input_name="other", connect_to=connect_to_attr ) self.assertTrue(success) self.assertIsNone(attr) # 5) connecting to a connected attribute with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="other", connect_to=og.ObjectLookup.attribute(("inputs:a", self._add1_node)), ) self.assertTrue(success) self.assertIsNone(attr) # 6) connecting to output attribute with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="other", connect_to=og.ObjectLookup.attribute(("outputs:sum", self._add1_node)), ) self.assertTrue(success) self.assertIsNone(attr) # ------------------------------------------------------------------------- def _validate_create_output_command_with_undo_redo(self, connect_from_attr: og.Attribute): """Helper to validate create output""" (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="added_output", connect_from=connect_from_attr ) self.assertTrue(success) self.assertTrue(attr.is_valid()) self.assertTrue(attr.get_upstream_connections()[0], connect_from_attr) omni.kit.undo.undo() self.assertTrue(self._compound_node.is_valid()) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(("outputs:added_output", self._compound_node)) omni.kit.undo.redo() self.assertTrue(self._compound_node.is_valid()) attr = og.ObjectLookup.attribute(("outputs:added_output", self._compound_node)) self.assertTrue(attr.is_valid()) self.assertTrue(attr.get_upstream_connections()[0], connect_from_attr) # ------------------------------------------------------------------------- async def test_create_output_command(self): """Tests that output connections can be successfully added, including undo, redo""" # add a node to the subgraph, so there is an unconnected output new_node = og.GraphController.create_node( node_id=("Add4", self._subgraph), node_type_id="omni.graph.nodes.Add", ) connect_from_attr = og.ObjectLookup.attribute(("outputs:sum", new_node)) self._validate_create_output_command_with_undo_redo(connect_from_attr) # ------------------------------------------------------------------------- async def test_create_output_command_multiple_outputs(self): """Tests that the output command connectes to an already connected output""" connect_from_attr = og.ObjectLookup.attribute(("outputs:sum", self._add2_node)) self._validate_create_output_command_with_undo_redo(connect_from_attr) # ------------------------------------------------------------------------- async def test_create_output_command_from_input(self): """Tests that the output command can create outputs from inputs as output nodes""" new_node = og.GraphController.create_node( node_id=("NewConstant", self._subgraph), node_type_id="omni.graph.nodes.ConstantDouble", ) connect_from_attr = og.ObjectLookup.attribute(("inputs:value", new_node)) self._validate_create_output_command_with_undo_redo(connect_from_attr) # ------------------------------------------------------------------------- async def test_create_output_command_error_cases(self): """Tests command error cases of output commands""" # 1) connecting to an attribute not in the subgraph with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="added_output", connect_from=og.ObjectLookup.attribute("outputs:sum", self._add3_node), ) self.assertTrue(success) self.assertIsNone(attr) # 2) connecting to no/invalid attribute with self.assertRaises(og.OmniGraphError): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="added_output", connect_from=None ) with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="added_output", connect_from="/World/Path.outputs:not_valid", ) self.assertTrue(success) self.assertIsNone(attr) # 3) connecting to an existing attribute name with ogts.ExpectedError(): connect_from_attr = og.ObjectLookup.attribute(("outputs:double3", self._compose_node)) (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="sum", connect_from=connect_from_attr ) self.assertTrue(success) self.assertIsNone(attr) # 4) connecting to a non-compound node with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._add3_node, output_name="other", connect_from=connect_from_attr ) self.assertTrue(success) self.assertIsNone(attr) # 5) try to promote a bundle output og.Controller.edit( self._compound_node.get_compound_graph_instance(), {og.Controller.Keys.CREATE_NODES: ("BundleCreator", "omni.graph.nodes.BundleConstructor")}, ) node = og.Controller.node( f"{self._compound_node.get_compound_graph_instance().get_path_to_graph()}/BundleCreator" ) self.assertTrue(node.is_valid()) bundle_attr = node.get_attribute("outputs_bundle") self.assertTrue(bundle_attr.is_valid()) with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="exposed_bundle", connect_from=bundle_attr ) self.assertTrue(success) self.assertIsNone(attr) # ------------------------------------------------------------------------- async def test_remove_compound_input(self): """Tests the remove compound attribute command can remove an input, including undo and redo""" self._compound_input_1.set_resolved_type(og.Type(og.BaseDataType.DOUBLE)) og.Controller.set(self._compound_input_1, 10.0, update_usd=True) connected_attr = self._compound_input_1.get_downstream_connections()[0] (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute(attribute=self._compound_input_1) self.assertTrue(success) self.assertTrue(result) self.assertFalse(self._compound_node.get_attribute_exists("inputs:a")) self.assertEqual(0, connected_attr.get_upstream_connection_count()) omni.kit.undo.undo() self.assertTrue(self._compound_node.get_attribute_exists("inputs:a")) attr = og.ObjectLookup.attribute(("inputs:a", self._compound_node)) self.assertGreater(attr.get_downstream_connection_count(), 0) self.assertEqual(attr.get_downstream_connections()[0], connected_attr) omni.kit.undo.redo() self.assertFalse(self._compound_node.get_attribute_exists("inputs:a")) self.assertEqual(0, connected_attr.get_upstream_connection_count()) # ------------------------------------------------------------------------- async def test_remove_compound_inputs_keeps_resolved_values(self): """Test the remove compound attribute restores resolved values""" # add the connection to the resolved node connect_to_attr = og.ObjectLookup.attribute(("inputs:x", self._compose_node)) (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=connect_to_attr ) self.assertTrue(success) self.assertTrue(attr.is_valid()) (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute(attribute=attr) self.assertTrue(success) self.assertTrue(result) connect_to_attr = og.ObjectLookup.attribute(("inputs:x", self._compose_node)) self.assertEqual(5.0, og.Controller.get(connect_to_attr)) # ------------------------------------------------------------------------- async def test_remove_compound_output(self): """Tests the remove compound attribute command can remove an output, including undo and redo""" connected_attr = self._compound_output_1.get_upstream_connections()[0] (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute(attribute=self._compound_output_1) self.assertTrue(success) self.assertTrue(result) self.assertFalse(self._compound_node.get_attribute_exists("outputs:sum")) self.assertEqual(0, connected_attr.get_downstream_connection_count()) omni.kit.undo.undo() self.assertTrue(self._compound_node.get_attribute_exists("outputs:sum")) attr = og.ObjectLookup.attribute(("outputs:sum", self._compound_node)) self.assertGreater(attr.get_upstream_connection_count(), 0) self.assertEqual(attr.get_upstream_connections()[0], connected_attr) omni.kit.undo.redo() self.assertFalse(self._compound_node.get_attribute_exists("outputs:sum")) self.assertEqual(0, connected_attr.get_downstream_connection_count()) # ------------------------------------------------------------------------- async def test_remove_compound_output_error_cases(self): """Validates known failure cases for remove attribute commands""" # 1) not a compound node with ogts.ExpectedError(): (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute( attribute=og.ObjectLookup.attribute("inputs:b", self._add3_node) ) self.assertTrue(success) self.assertFalse(result) # 2) not a valid attribute with ogts.ExpectedError(): (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute(attribute="/World/Path.outputs:invalid_attr") self.assertTrue(success) self.assertFalse(result) # ------------------------------------------------------------------------- async def test_rename_compound_input_output(self): """Tests the rename input/output functionality""" # Rename an input attribute upstream = self._compound_input_1.get_upstream_connections() downstream = self._compound_input_1.get_downstream_connections() old_attr_path = self._compound_input_1.get_path() (success, new_attr) = ogu.cmds.RenameCompoundSubgraphAttribute( attribute=self._compound_input_1, new_name="new_a" ) # Verify that connections are now on new attr and old attr has been removed self.assertTrue(success) self.assertTrue(new_attr.is_valid()) self.assertEqual(new_attr.get_upstream_connections(), upstream) self.assertEqual(new_attr.get_downstream_connections(), downstream) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(old_attr_path) new_attr_path = new_attr.get_path() omni.kit.undo.undo() # Verify undo restores the old attr and connections with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(new_attr_path) attr = og.ObjectLookup.attribute(old_attr_path) self.assertEqual(attr.get_upstream_connections(), upstream) self.assertEqual(attr.get_downstream_connections(), downstream) # Verify redo omni.kit.undo.redo() attr = og.ObjectLookup.attribute(new_attr_path) self.assertEqual(attr.get_upstream_connections(), upstream) self.assertEqual(attr.get_downstream_connections(), downstream) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(old_attr_path) # Rename an output attribute upstream = self._compound_output_1.get_upstream_connections() downstream = self._compound_output_1.get_downstream_connections() old_attr_path = self._compound_output_1.get_path() (success, new_attr) = ogu.cmds.RenameCompoundSubgraphAttribute( attribute=self._compound_output_1, new_name="new_sum" ) self.assertTrue(success) self.assertTrue(new_attr.is_valid()) self.assertEqual(new_attr.get_upstream_connections(), upstream) self.assertEqual(new_attr.get_downstream_connections(), downstream) new_attr_path = new_attr.get_path() omni.kit.undo.undo() with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(new_attr_path) attr = og.ObjectLookup.attribute(old_attr_path) self.assertEqual(attr.get_upstream_connections(), upstream) self.assertEqual(attr.get_downstream_connections(), downstream) omni.kit.undo.redo() attr = og.ObjectLookup.attribute(new_attr_path) self.assertEqual(attr.get_upstream_connections(), upstream) self.assertEqual(attr.get_downstream_connections(), downstream) # ------------------------------------------------------------------------- async def test_rename_compound_input_output_error_cases(self): """Validates known failure cases for remove attribute commands""" # attempt to rename to an existing name with ogts.ExpectedError(): (success, new_attr) = ogu.cmds.RenameCompoundSubgraphAttribute( attribute=self._compound_input_1, new_name="b" ) self.assertFalse(success) self.assertEqual(new_attr, None) # ----------------------------------------------------------------------------- class TestCompoundSubgraphWithVariables(ogts.OmniGraphTestCase): _test_graph_path = "/World/TestGraph" # --------------------------------------------------------------------- async def test_subgraph_with_read_variables_evaluates(self): """Tests that a subgraph with variables in it evaluates correctly""" # Create a subgraph/graph pair with the following setup # # |--------------------------------------| # | [ReadVariable]->|----------| | # | [Constant]----->| Add |-----> o | ---> [Magnitude] # | |----------| | # | -------------------------------------| controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (compound_node, abs_node), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("Constant", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "Add.inputs:a"), ("Constant.inputs:value", "Add.inputs:b"), ], keys.PROMOTE_ATTRIBUTES: [("Add.outputs:sum", "value")], }, ), ("Abs", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Compound.outputs:value", "Abs.inputs:input"), ], keys.CREATE_VARIABLES: [ ("double_var", og.Type(og.BaseDataType.DOUBLE), 5.0), ], keys.SET_VALUES: [("Constant.inputs:value", 1.0), ("ReadVariable.inputs:variableName", "double_var")], }, ) await og.Controller.evaluate(graph) attr = og.Controller.attribute(("outputs:magnitude", abs_node)) self.assertEqual(6.0, og.Controller.get(attr)) # update the constant so we get different result - because it 'moved' to the subgraph, the # existing variable is no longer valid constant = og.Controller.node(f"{compound_node.get_prim_path()}/Subgraph/Constant") constant_attr = og.Controller.attribute(("inputs:value", constant)) og.Controller.set(constant_attr, 2.0) await og.Controller.evaluate(graph) abs_node = og.Controller.node(f"{self._test_graph_path}/Abs") attr = og.Controller.attribute(("outputs:magnitude", abs_node)) self.assertEqual(7.0, og.Controller.get(attr)) # --------------------------------------------------------------------- async def test_subgraph_read_write_variables_across_subnet(self): """Tests that a subgraph can read and write variables regardless of where they live """ # A graph that doubles the variable value each time # A single read is in the main graph, one in the subgraph # |----------------------------------------| # | | # [ReadVariable] --> | o-------------->|------| | # | [ReadVariable]->| Add |--->[WriteVar] | # | |------| | # |----------------------------------------| controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (_read1, _compound_node), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("ReadVariable1", "omni.graph.core.ReadVariable"), ( "Compound", { keys.CREATE_NODES: [ ("ReadVariable2", "omni.graph.core.ReadVariable"), ("Add", "omni.graph.nodes.Add"), ("WriteVariable", "omni.graph.core.WriteVariable"), ], keys.CONNECT: [ ("ReadVariable2.outputs:value", "Add.inputs:b"), ("Add.outputs:sum", "WriteVariable.inputs:value"), ], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ("WriteVariable.outputs:value", "outputs:value"), ], keys.SET_VALUES: [ ("ReadVariable2.inputs:variableName", "double_var"), ("WriteVariable.inputs:variableName", "double_var"), ], }, ), ], keys.CREATE_VARIABLES: [ ("double_var", og.Type(og.BaseDataType.DOUBLE), 2.0), ], keys.CONNECT: [ ("ReadVariable1.outputs:value", "Compound.inputs:a"), ], keys.SET_VALUES: [ ("ReadVariable1.inputs:variableName", "double_var"), ], }, ) # get the variable value variable = graph.find_variable("double_var") var_value = variable.get(graph.get_default_graph_context()) for _ in range(0, 3): await og.Controller.evaluate(graph) new_var_value = variable.get(graph.get_default_graph_context()) self.assertEqual(var_value * 2, new_var_value) var_value = new_var_value async def test_promote_unconnected(self): """ Test promoting all unconnected inputs/outputs on a node in a compound. Ensure that it also creates a unique name """ controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (_, _compound_node), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("ConstDouble", "omni.graph.nodes.ConstantDouble"), ( "Compound", { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ("ConstantFloat", "omni.graph.nodes.ConstantFloat"), ("RandomBool", "omni.graph.nodes.RandomBoolean"), ], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ], }, ), ], keys.CONNECT: [ ("ConstDouble.inputs:value", "Compound.inputs:a"), ], keys.SET_VALUES: [("ConstDouble.inputs:value", 2.0)], }, ) await og.Controller.evaluate(graph) self.assertTrue(_compound_node.get_attribute("inputs:a").is_valid()) self.assertFalse(_compound_node.get_attribute_exists("inputs:b")) add_node = og.Controller.node(f"{_compound_node.get_prim_path()}/Subgraph/Add") (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=add_node, inputs=True, outputs=False) self.assertTrue(success) self.assertEqual(len(ports), 1) self.assertTrue(ports[0].is_valid()) self.assertEqual(ports[0].get_name(), "inputs:b") self.assertTrue(_compound_node.get_attribute("inputs:b").is_valid()) omni.kit.undo.undo() self.assertFalse(_compound_node.get_attribute_exists("inputs:b")) omni.kit.undo.redo() self.assertTrue(_compound_node.get_attribute("inputs:b").is_valid()) # rename input "a" to "b" and promote unconnected again, should create b_01 omni.kit.undo.undo() self.assertFalse(_compound_node.get_attribute_exists("inputs:b")) attr = _compound_node.get_attribute("inputs:a") (success, new_attr) = ogu.cmds.RenameCompoundSubgraphAttribute(attribute=attr, new_name="b") self.assertTrue(success) self.assertTrue(new_attr.is_valid()) (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=add_node, inputs=True, outputs=False) self.assertTrue(success) self.assertEqual(len(ports), 1) self.assertTrue(ports[0].is_valid()) self.assertEqual(ports[0].get_name(), "inputs:b_01") omni.kit.undo.undo() c = og.Controller.create_attribute(add_node, "inputs:c", "double") self.assertTrue(c.is_valid()) (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=add_node, inputs=True, outputs=True) self.assertTrue(success) self.assertEqual(len(ports), 3) self.assertEqual(ports[0].get_name(), "inputs:b_01") self.assertEqual(ports[1].get_name(), "inputs:c") self.assertEqual(ports[2].get_name(), "outputs:sum") # verify that output-only inputs are promoted as outputs float_node = og.Controller.node(f"{_compound_node.get_prim_path()}/Subgraph/ConstantFloat") (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=float_node, inputs=False, outputs=True) self.assertTrue(success) self.assertEqual(len(ports), 1) self.assertEqual(ports[0].get_name(), "outputs:value") # test that literal only inputs are not promoted rand_node = og.Controller.node(f"{_compound_node.get_prim_path()}/Subgraph/RandomBool") (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=rand_node, inputs=True, outputs=False) self.assertTrue(success) self.assertEqual(len(ports), 3) self.assertFalse("inputs:isNoise" in {p.get_name() for p in ports})
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_controllers.py
"""Basic tests of the controller classes in omni.graph.core""" import json from typing import Any, Dict, List import carb import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from omni.graph.core._impl.utils import _flatten_arguments, _Unspecified from pxr import Sdf _KEYS = og.Controller.Keys """Syntactic sugar to shorten the name required to access the keywords""" # ============================================================================================================== class TestControllers(ogts.OmniGraphTestCase): """Run a simple set of unit tests that exercise the main controller functionality""" # -------------------------------------------------------------------------------------------------------------- async def test_arg_flattening(self): """Test the utility that flattens arguments list into a common dictionary""" test_data = [ ([], [("a", 1)], [], {}, [1]), ([("a", _Unspecified)], [], [1], {}, [1]), ([("a", 1)], [], [], {}, [1]), ([("a", _Unspecified)], [], [], {"a": 2}, [2]), ([("a", _Unspecified)], [], [5], {}, [5]), ([("a", _Unspecified)], [("b", 7)], [5], {}, [5, 7]), ([("a", _Unspecified)], [("b", 7)], [], {"a": 3}, [3, 7]), ([("a", _Unspecified)], [("b", 7)], [5], {"b": 3}, [5, 3]), ([("a", _Unspecified)], [("b", _Unspecified)], [5], {"b": 3}, [5, 3]), ] for test_index, (mandatory, optional, args, kwargs, expected_results) in enumerate(test_data): flat_args = _flatten_arguments(mandatory, optional, args, kwargs) self.assertCountEqual(flat_args, expected_results, f"Test {test_index}") # Test cases where the arguments are invalid and exceptions are expected test_data_invalid = [ ([("a", _Unspecified)], [], [], {}, [1]), # Missing mandatory arg ([("a", _Unspecified)], [], [], {"b": 1}, []), # Unknown kwarg ([("a", _Unspecified)], [], [1, 2], {}, [1]), # Too many args ([("a", _Unspecified)], [], [1], {"a": 2}, [1]), # Ambiguous arg value ([("a", _Unspecified)], [("b", 7)], [5], {"a": 3}, [5, 3]), # Ambiguous arg value ] for mandatory, optional, args, kwargs, _expected_results in test_data_invalid: with self.assertRaises(og.OmniGraphError): _ = _flatten_arguments(mandatory, optional, args, kwargs) carb.log_error(f"Should have failed with {mandatory}, {optional}, {args}, {kwargs}") # -------------------------------------------------------------------------------------------------------------- async def test_flattening_example(self): """Test that runs the code cited in the documentation for the _flatten_arguments function""" feet = 1 yards = 3 miles = 5280 class Toady: def __init__(self): self.__height_default = 1 self.__height_unit = yards self.jump = self.__jump_obj @classmethod def jump(cls, *args, **kwargs): # noqa: PLE0202 Hiding it is the point return cls.__jump(cls, args=args, kwargs=kwargs) def __jump_obj(self, *args, **kwargs): return self.__jump( self, how_high=self.__height_default, unit=self.__height_unit, args=args, kwargs=kwargs ) @staticmethod def __jump(obj, how_high: int = None, unit: str = miles, args=List[Any], kwargs=Dict[str, Any]): (how_high, unit) = _flatten_arguments( mandatory=[("how_high", how_high)], optional=[("unit", unit)], args=args, kwargs=kwargs ) return how_high, unit # Legal calls to this function self.assertEqual((123, miles), Toady.jump(how_high=123)) self.assertEqual((123, miles), Toady.jump(123)) self.assertEqual((123, feet), Toady.jump(123, unit=feet)) self.assertEqual((123, feet), Toady.jump(how_high=123, unit=feet)) # The main difference in object-based calls is the use of the object members for defaults, also allowing it # to omit the "mandatory" members in the call. smithers = Toady() self.assertEqual((1, yards), smithers.jump()) self.assertEqual((123, yards), smithers.jump(how_high=123)) self.assertEqual((123, yards), smithers.jump(123)) self.assertEqual((123, feet), smithers.jump(123, unit=feet)) self.assertEqual((123, feet), smithers.jump(how_high=123, unit=feet)) self.assertEqual((1, feet), smithers.jump(unit=feet)) # -------------------------------------------------------------------------------------------------------------- async def test_graph_construction(self): """Test the basic graph construction function of the og.Controller class""" controller = og.Controller() (graph, _, _, _) = controller.edit("/World/PushGraph") self.assertTrue(graph, "Created a new graph") await controller.evaluate(graph) graph_by_path = og.get_graph_by_path("/World/PushGraph") self.assertEqual(graph, graph_by_path, "Created graph lookup") self.assertEqual(graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION) self.assertEqual(graph.get_graph_backing_type(), og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED) (same_graph, _, _, _) = controller.edit(graph) self.assertEqual(graph, same_graph, "Edit of the same graph twice") await controller.evaluate(same_graph) index = 0 all_graphs = [graph] for backing_type in og.GraphBackingType.__members__.values(): if backing_type in [ og.GraphBackingType.GRAPH_BACKING_TYPE_UNKNOWN, og.GraphBackingType.GRAPH_BACKING_TYPE_NONE, og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_WITH_HISTORY, ]: continue for pipeline_stage in og.GraphPipelineStage.__members__.values(): if pipeline_stage in [og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_UNKNOWN]: continue for evaluation_mode in [ og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED, ]: error_msg = ( f"Created graph with backing {backing_type}, pipeline {pipeline_stage} " "and evaluation mode {evaluation_mode}" ) (new_graph, _, _, _) = controller.edit( { "graph_path": f"/World/TestGraph{index}", "fc_backing_type": backing_type, "pipeline_stage": pipeline_stage, "evaluation_mode": evaluation_mode, } ) self.assertTrue(new_graph, error_msg) self.assertEqual(new_graph.get_pipeline_stage(), pipeline_stage, error_msg) self.assertEqual(new_graph.get_graph_backing_type(), backing_type, error_msg) self.assertEqual(new_graph.evaluation_mode, evaluation_mode, error_msg) self.assertTrue( any( new_graph == pipeline_graph for pipeline_graph in og.get_graphs_in_pipeline_stage(pipeline_stage) ) ) index += 1 all_graphs.append(new_graph) await controller.evaluate(all_graphs) # ---------------------------------------------------------------------- async def test_graph_population(self): """Test node creation and deletion via the og.Controller class""" controller = og.Controller() simple_node_type = "omni.graph.tutorials.SimpleData" # Create a couple of random nodes (graph, nodes_created, _, _) = controller.edit( "/World/PushGraph", { _KEYS.CREATE_NODES: [ ("Simple1", simple_node_type), ("Simple2", simple_node_type), ("Simple3", simple_node_type), ] }, ) for node in nodes_created: self.assertTrue(node.is_valid(), "Created node is valid") self.assertEqual(node.get_node_type().get_node_type(), simple_node_type) self.assertEqual(len(nodes_created), 3, "Correct number of nodes created and returned") nodes_matched = 0 for node in graph.get_nodes(): for expected_node in nodes_created: if node == expected_node: nodes_matched += 1 break self.assertEqual(nodes_matched, 3, "Found all created nodes in the return values") # Delete one node, add two nodes, then delete an earlier one. # Uses a static controller instead of the existing one for some operations to confirm that also works controller.edit(graph, {_KEYS.DELETE_NODES: "Simple1"}) (static_graph, static_nodes, _, static_path_node_map) = og.Controller.edit( graph, { _KEYS.CREATE_NODES: [ ("Simple1", simple_node_type), ("Simple4", simple_node_type), ] }, ) self.assertEqual(graph, static_graph, "Static controller uses same graph") self.assertEqual(len(static_nodes), 2, "Static node creation") self.assertCountEqual(["Simple1", "Simple4"], list(static_path_node_map.keys()), "Static node path map") (_, _, _, new_path_node_map) = controller.edit(graph, {_KEYS.DELETE_NODES: "Simple2"}) self.assertCountEqual( ["Simple3"], list(new_path_node_map.keys()), "Path map is only aware of object-based changes" ) # Delete a node then immediately create one with the same name but a different type, using the non-list forms (_, retyped_nodes, _, retyped_path_node_map) = controller.edit( graph, { _KEYS.DELETE_NODES: "Simple1", _KEYS.CREATE_NODES: ("Simple1", "omni.tutorials.TupleData"), }, ) self.assertCountEqual( ["Simple1", "Simple3"], list(retyped_path_node_map.keys()), "Path map deleted and added a node of the same name", ) self.assertEqual( "omni.tutorials.TupleData", controller.node_type(retyped_nodes[0]).get_node_type(), "Same node name, different type", ) # Attempt to add a node with a bad type with self.assertRaises(og.OmniGraphError): og.Controller.edit(graph, {_KEYS.CREATE_NODES: [("NoSuchNode", "omni.no.such.type")]}) # Attempt to delete a non-existing node (using a static Controller object instead of the existing one) with self.assertRaises(og.OmniGraphError): og.Controller.edit(graph, {_KEYS.DELETE_NODES: ["/This/Node/Does/Not/Exist"]}) # -------------------------------------------------------------------------------------------------------------- async def test_prim_construction(self): """Test the controller's ability to create USD prims. This is just testing basic functionality. A separate test will exercise creation of prims with all of the available attribute types. Testing Type Matrix: prim_path: str, Sdf.Path, Invalid attribute_id: dict of KEY: str, Invalid VALUE: 2-tuple of VALUE[0]: str(ogn type), str(sdf type), og.Type, Invalid VALUE[1]: Matching Value Type, Unmatching Value Type, Invalid prim_type: str, None """ controller = og.Controller() (graph, _, prims, _,) = controller.edit( "/PrimGraph", { controller.Keys.CREATE_PRIMS: [ # (str, {str: (ogn_str, value)}) ("PrimFloat2", {"float2Value": ("float[2]", [1.0, 2.0])}), # (str, {Sdf.Path: (sdf_str, value)}) (Sdf.Path("PrimFloat3"), {"float3Value": ("float3", [1.0, 2.0, 3.0])}), # (str, {str: (og.Type, value)}) ("PrimFloat4", {"float4Value": (og.Type(og.BaseDataType.FLOAT, 4, 0), [1.0, 2.0, 3.0, 4.0])}), # str "PrimWithNoAttributes", ] }, ) # Verify prims are created with the right attributes self.assertEqual(len(prims), 4) self.assertTrue(all(prim.IsValid() for prim in prims)) float2_attr = prims[0].GetAttribute("float2Value") self.assertTrue(float2_attr.IsValid()) self.assertEqual([1.0, 2.0], float2_attr.Get()) float3_attr = prims[1].GetAttribute("float3Value") self.assertTrue(float3_attr.IsValid()) self.assertEqual([1.0, 2.0, 3.0], float3_attr.Get()) float4_attr = prims[2].GetAttribute("float4Value") self.assertTrue(float4_attr.IsValid()) self.assertEqual([1.0, 2.0, 3.0, 4.0], float4_attr.Get()) # Test that non-string prim path fails with self.assertRaises(og.OmniGraphError): og.Controller.edit(graph, {controller.Keys.CREATE_PRIMS: [prims[0]]}) # Test that attempt to create prim in already existing location fails, with both absolute and relative paths with self.assertRaises(og.OmniGraphError): controller.edit(graph, {controller.Keys.CREATE_PRIMS: [("PrimFloat2", "Cube")]}) with self.assertRaises(og.OmniGraphError): controller.edit(graph, {controller.Keys.CREATE_PRIMS: [("/PrimFloat2", "Cube", {})]}) # Test that prims are forbidden from being created inside an OmniGraph with self.assertRaises(og.OmniGraphError): controller.edit(graph, {controller.Keys.CREATE_PRIMS: [("/PrimGraph/IllegalLocation", {})]}) # Test that non-string attribute name fails with self.assertRaises(og.OmniGraphError): controller.edit( graph, { controller.Keys.CREATE_PRIMS: [ ("PrimWithBadAttribute", {None: None}), ] }, ) # Test that invalid attribute data type fails with self.assertRaises(og.OmniGraphError): controller.edit( graph, { controller.Keys.CREATE_PRIMS: [ ("PrimWithBadAttributeData", {"complex": [1.0, 2.0]}), ] }, ) # Test that non-matching attribute data type fails with self.assertRaises(og.OmniGraphError): controller.edit( graph, { controller.Keys.CREATE_PRIMS: [ ("PrimWithBadAttributeData", {"float": None}), ] }, ) # Test that invalid attribute data fails with self.assertRaises(og.OmniGraphError): controller.edit( graph, { controller.Keys.CREATE_PRIMS: [ ("PrimWithBadAttributeData", {"float": None}), ] }, ) # -------------------------------------------------------------------------------------------------------------- def __confirm_connection_counts(self, attribute: og.Attribute, upstream_count: int, downstream_count: int): """Check that the given attribute has the proscribed number of upstream and downstream connections""" self.assertEqual(attribute.get_upstream_connection_count(), upstream_count) self.assertEqual(attribute.get_downstream_connection_count(), downstream_count) # -------------------------------------------------------------------------------------------------------------- async def test_connections(self): """Test the various connection-related functions on the graph controller.""" # Use the main controller for testing as it derives from the graph controller controller = og.Controller() # Source --> Sink --> InOut # \ \ / # \ -----/ # --> FanOut # Command 1 (graph, nodes_created, _, _) = controller.edit( "/TestGraph", { controller.Keys.CREATE_NODES: [ ("Source", "omni.graph.tutorials.SimpleData"), ("Sink", "omni.graph.tutorials.SimpleData"), ("FanOut", "omni.graph.tutorials.SimpleData"), ("InOut", "omni.graph.tutorials.SimpleData"), ], controller.Keys.CONNECT: [ ("Source.outputs:a_bool", "Sink.inputs:a_bool"), (("outputs:a_bool", "Source"), ("inputs:a_bool", "FanOut")), ("Sink.inputs:a_bool", "InOut.inputs:a_bool"), ], }, ) (source_node, sink_node, fanout_node, inout_node) = nodes_created def _get_nodes(): return ( controller.node(("Source", graph)), controller.node(("Sink", graph)), controller.node(("FanOut", graph)), controller.node(("InOut", graph)), ) def _get_attributes(): return ( controller.attribute(("outputs:a_bool", source_node)), controller.attribute("inputs:a_bool", sink_node), controller.attribute(("inputs:a_bool", fanout_node)), controller.attribute("inputs:a_bool", inout_node), ) source_output, sink_input, fanout_input, inout_input = _get_attributes() # The sequence tests successful restoration when everything is deleted and restored in groups; # DisconnectAll(Source.outputs:a_bool) # Removes Source->Sink and Source->FanOut # DisconnectAll(Sink.inputs:a_bool) # Removes Sink->InOut # Delete Source, Sink, InOut, FanOut # undo deletes # undo second disconnect # Restores Sink->InOut # undo first disconnect # Restores Source->Sink and Source->FanOut # redo and undo to go the beginning and get back here again # DisconnectAll(Sink.inputs:a_bool) # Removes Sink->InOut and Source->Sink # undo # Command 2 controller.disconnect_all(("outputs:a_bool", source_node)) self.__confirm_connection_counts(source_output, 0, 0) self.__confirm_connection_counts(sink_input, 0, 1) self.__confirm_connection_counts(fanout_input, 0, 0) self.__confirm_connection_counts(inout_input, 1, 0) # Command 3 controller.disconnect_all(sink_input) self.__confirm_connection_counts(source_output, 0, 0) self.__confirm_connection_counts(sink_input, 0, 0) self.__confirm_connection_counts(fanout_input, 0, 0) self.__confirm_connection_counts(inout_input, 0, 0) # Command 4 controller.edit(graph, {controller.Keys.DELETE_NODES: [source_node, sink_node, fanout_node, inout_node]}) omni.kit.undo.undo() # Command 4 omni.kit.undo.undo() # Command 3 # May have lost the objects through the undo process so get them again (source_node, sink_node, fanout_node, inout_node) = _get_nodes() source_output, sink_input, fanout_input, inout_input = _get_attributes() self.__confirm_connection_counts(source_output, 0, 0) self.__confirm_connection_counts(sink_input, 0, 1) self.__confirm_connection_counts(fanout_input, 0, 0) self.__confirm_connection_counts(inout_input, 1, 0) omni.kit.undo.undo() # Command 2 self.__confirm_connection_counts(source_output, 0, 2) self.__confirm_connection_counts(sink_input, 1, 1) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 1, 0) # Go back and forth in the undo queue to get back to having all objects and connections present omni.kit.undo.redo() # Command 2 omni.kit.undo.redo() # Command 3 omni.kit.undo.redo() # Command 4 omni.kit.undo.undo() # Command 4 omni.kit.undo.undo() # Command 3 omni.kit.undo.undo() # Command 2 # May have lost the objects through the undo process so get them again (source_node, sink_node, fanout_node, inout_node) = _get_nodes() source_output, sink_input, fanout_input, inout_input = _get_attributes() self.__confirm_connection_counts(source_output, 0, 2) self.__confirm_connection_counts(sink_input, 1, 1) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 1, 0) # Direct calls are okay when the attribute is fully specified # Command 5 og.Controller.disconnect_all(sink_input) self.__confirm_connection_counts(source_output, 0, 1) self.__confirm_connection_counts(sink_input, 0, 0) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 0, 0) omni.kit.undo.undo() # Command 5 self.__confirm_connection_counts(source_output, 0, 2) self.__confirm_connection_counts(sink_input, 1, 1) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 1, 0) # -------------------------------------------------------------------------------------------------------------- async def test_prim_exposure(self): """Test the controller's ability to expose USD prims to OmniGraph. def expose_prim(cls, exposure_type: PrimExposureType, prim_id: Prim_t, node_path_id: NewNode_t) -> Union[og.Node, List[og.Node]]: The test proceeds by first creating a few prims and then exposing them to OmniGraph, confirming that the OmniGraph nodes do in fact get the correct values from their underlying prims. """ controller = og.Controller() exposure_types = og.GraphController.PrimExposureType (graph, _, _, path_to_object_map,) = controller.edit( "/PrimGraph", { _KEYS.CREATE_PRIMS: [ ("PrimFloat2", {"float2Value": ("float[2]", [1.0, 2.0])}), ("Cube", "Cube"), ("PrimVelocity", {"velocity": ("float[3]", [1.0, 2.0, 3.0])}, "Velocity"), ("Prim1"), ("Prim2"), ("Prim3"), ("PrimPosition", {"position": ("pointf[3]", [1.0, 2.0, 3.0])}, "Position"), ] }, ) # Test exposure of a prim as a bundle (_, exposed_nodes, _, _) = og.Controller.edit( graph, { _KEYS.EXPOSE_PRIMS: (exposure_types.AS_BUNDLE, "PrimFloat2", "ExposedAsBundle"), }, path_to_object_map, ) await controller.evaluate(graph) self.assertEqual(len(exposed_nodes), 1, "Exposed a simple prim by bundle") self.assertTrue("ExposedAsBundle" in path_to_object_map) self.assertEqual(exposed_nodes[0].get_prim_path(), "/PrimGraph/ExposedAsBundle") self.assertEqual(exposed_nodes[0].get_type_name(), "omni.graph.nodes.ExtractPrim") (_, inspector_nodes, _, _) = controller.edit( graph, { _KEYS.CREATE_NODES: ("Inspector", "omni.graph.nodes.BundleInspector"), _KEYS.CONNECT: ("ExposedAsBundle.outputs_primBundle", "Inspector.inputs:bundle"), }, ) await controller.evaluate(graph) # float2Value is in the exposed bundle inspector_node = inspector_nodes[0] bundle_names = og.Controller.get(controller.attribute("outputs:names", inspector_node)) index = bundle_names.index("float2Value") self.assertTrue(index >= 0) # The value of that attribute is [1.0, 2.0] try: bundle_values = og.Controller.get(controller.attribute("outputs:values", inspector_node)) # This weird thing is necessary because the tuple values are not JSON-compatible tuple_to_list = json.loads(bundle_values[index].replace("(", "[").replace(")", "]")) self.assertCountEqual(tuple_to_list, [1.0, 2.0]) except AssertionError as error: carb.log_warn(f"ReadBundle node can't get the bundle to the inspector - {error}") # Test exposure of a prim as attributes (_, exposed_nodes, _, _) = og.Controller.edit( graph, { _KEYS.EXPOSE_PRIMS: (exposure_types.AS_ATTRIBUTES, "PrimVelocity", "ExposedAsAttribute"), }, path_to_object_map, ) await controller.evaluate(graph) self.assertEqual(len(exposed_nodes), 1, "Exposed a simple prim by attribute") self.assertTrue("ExposedAsAttribute" in path_to_object_map) self.assertEqual(exposed_nodes[0].get_prim_path(), "/PrimGraph/ExposedAsAttribute") self.assertEqual(exposed_nodes[0].get_type_name(), "omni.graph.nodes.ReadPrimAttributes") # in order to read data, the attribute needs to be connected, and an eval must be done (graph, _, _, _) = og.Controller.edit( graph, { _KEYS.CREATE_NODES: [ ("Const", "omni.graph.nodes.ConstantFloat3"), ], }, ) # we need to evaluate for dynamic attributes to appear on ExtractPrim2 await controller.evaluate(graph) # after attributes appeared on ExtractBundle2 we can connect them (graph, _, _, _) = og.Controller.edit( graph, { _KEYS.CONNECT: ("/PrimGraph/ExposedAsAttribute.outputs:velocity", "/PrimGraph/Const.inputs:value"), }, ) await controller.evaluate(graph) self.assertCountEqual( [1.0, 2.0, 3.0], og.Controller.get(controller.attribute(("outputs:velocity", exposed_nodes[0]))) ) # Test exposure of a list of prims (_, exposed_nodes, _, _) = og.Controller.edit( graph, { _KEYS.EXPOSE_PRIMS: [ (exposure_types.AS_ATTRIBUTES, "Prim1", "Exposed1"), (exposure_types.AS_ATTRIBUTES, "Prim2", "Exposed2"), (exposure_types.AS_ATTRIBUTES, "Prim3", "Exposed3"), ] }, path_to_object_map, ) await controller.evaluate(graph) self.assertEqual(len(exposed_nodes), 3, "Exposed a list of prims by attribute") for index in range(3): self.assertTrue(f"Exposed{index + 1}" in path_to_object_map) self.assertEqual(exposed_nodes[index].get_prim_path(), f"/PrimGraph/Exposed{index + 1}") self.assertEqual(exposed_nodes[index].get_type_name(), "omni.graph.nodes.ReadPrimAttributes") # Test exposure as write (_, exposed_nodes, _, _) = controller.edit( graph, {_KEYS.EXPOSE_PRIMS: (exposure_types.AS_WRITABLE, "PrimPosition", "ExposedWritable")} ) await controller.evaluate(graph) write_node = exposed_nodes[0] self.assertEqual(len(exposed_nodes), 1, "Exposed a simple writable prim") self.assertTrue("ExposedWritable" in path_to_object_map) self.assertEqual(write_node.get_prim_path(), "/PrimGraph/ExposedWritable") self.assertEqual(write_node.get_type_name(), "omni.graph.nodes.WritePrim") # Check we have the expected dynamic attrib on WritePrim attribs = write_node.get_attributes() found_size_attrib = False for attrib in attribs: if attrib.get_name() == "inputs:position" and attrib.get_resolved_type().get_ogn_type_name() == "pointf[3]": found_size_attrib = True self.assertTrue(found_size_attrib) # Test invalid attempt to expose non-existent prim with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.EXPOSE_PRIMS: (exposure_types.AS_ATTRIBUTES, "NotAPrim", "NotANode")}) # Test invalid attempt to expose prim on node path that's not in a graph with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.EXPOSE_PRIMS: (exposure_types.AS_ATTRIBUTES, "Cube", "/NotANode")}) # Test invalid attempt to expose prim on an already existing node with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.EXPOSE_PRIMS: (exposure_types.AS_ATTRIBUTES, "Cube", "Exposed1")}) # -------------------------------------------------------------------------------------------------------------- async def test_set_values(self): """Test the controller's ability to set values on nodes. def set(AttributeValues_t) """ controller = og.Controller() (graph, (node1, _, _, add_node), _, _) = controller.edit( "/TestGraph", { _KEYS.CREATE_NODES: [ ("Node1", "omni.graph.tutorials.SimpleData"), ("Node2", "omni.graph.tutorials.SimpleData"), ("Node3", "omni.graph.tutorials.SimpleData"), ("AddNode", "omni.graph.nodes.Add"), ], }, ) # Test setting of a regular attribute value controller.edit(graph, {_KEYS.SET_VALUES: [("Node1.inputs:a_float", 17.0)]}) await controller.evaluate(graph) # Exercise the controller version that takes an attribute (passing it up to the DataView) data_controller = og.Controller(attribute="/TestGraph/Node1.outputs:a_float") self.assertEqual(18.0, data_controller.get()) # Test setting of an extended attribute value with a resolution type controller.edit( graph, { _KEYS.SET_VALUES: [ (("inputs:a", add_node), og.TypedValue(17.0, "float")), ("AddNode.inputs:b", og.TypedValue(51.0, "float")), ] }, ) await controller.evaluate(graph) # Until type resolution works when values are set as well as connections are made this cannot check the output self.assertEqual(17.0, og.DataView.get(og.ObjectLookup.attribute(("inputs:a", add_node)))) # Test setting of multiple attributes in one shot controller.edit( graph, { _KEYS.SET_VALUES: [ ("Node1.inputs:a_float", 42.0), ("Node1.inputs:a_double", 23.0), ] }, ) await controller.evaluate(graph) self.assertEqual(43.0, og.DataView.get(og.ObjectLookup.attribute(("outputs:a_float", node1)))) self.assertEqual(24.0, og.Controller.get("/TestGraph/Node1.outputs:a_double")) # Test invalid attempt to set non-existent attribute with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.SET_VALUES: ("Node1.inputs:a_not_there", 5.0)}) # Test invalid attempt to set extended attribute with non-existent type with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.SET_VALUES: (("inputs:a", add_node), 17.0, "not_a_type")}) # -------------------------------------------------------------------------------------------------------------- async def test_variables(self): """Test variable methods via the og.Controller class def get_variable_default_value(cls, variable_id: Variable_t): def set_variable_default_value(cls, variable_id: Variable_t, value): """ controller = og.Controller() (graph, _, _, _) = controller.edit( "/TestGraph", { _KEYS.CREATE_VARIABLES: [ ("Variable_1", og.Type(og.BaseDataType.FLOAT)), ("Variable_2", og.Type(og.BaseDataType.INT)), ], }, ) variable_1_id = graph.find_variable("Variable_1") og.Controller.set_variable_default_value(variable_1_id, 5) self.assertEqual(og.Controller.get_variable_default_value(variable_1_id), 5) variable_2_id = (graph, "Variable_2") og.Controller.set_variable_default_value(variable_2_id, 6) self.assertEqual(og.Controller.get_variable_default_value(variable_2_id), 6) with self.assertRaises(og.OmniGraphError): og.Controller.set_variable_default_value(variable_1_id, "Not a float") with self.assertRaises(og.OmniGraphError): og.Controller.get_variable_default_value((graph, "InvalidVariable")) with self.assertRaises(og.OmniGraphError): og.Controller.set_variable_default_value((graph, "InvalidVariable"), 5) with self.assertRaises(og.OmniGraphError): og.Controller.get_variable_default_value(None) # -------------------------------------------------------------------------------------------------------------- async def test_compound_subgraph_graph_population(self): """Test graph population when using compound subgraphs""" controller = og.Controller() simple_node_type = "omni.graph.tutorials.SimpleData" (graph, nodes, _, _path_node_map) = controller.edit( "/TestGraph", { _KEYS.CREATE_NODES: [ ( "Compound_1", {_KEYS.CREATE_NODES: [("Compound_1_1", simple_node_type), ("Compound_1_2", simple_node_type)]}, ), ( "Compound_2", { _KEYS.CREATE_NODES: [ ( "Compound_2_1", { _KEYS.CREATE_NODES: [ ("Compound_2_1_1", simple_node_type), ("Compound_2_1_2", simple_node_type), ] }, ) ] }, ), ] }, ) # test graph level self.assertTrue(graph.is_valid()) self.assertEqual(2, len(nodes), "Expected 2 nodes create in graph") self.assertTrue(nodes[0].is_compound_node()) self.assertTrue(nodes[1].is_compound_node()) # test sublevels are constructed correctly compound_1_graph = nodes[0].get_compound_graph_instance() self.assertTrue(compound_1_graph.is_valid()) compound_1_graph_nodes = compound_1_graph.get_nodes() self.assertEqual(2, len(compound_1_graph_nodes)) self.assertEqual(compound_1_graph_nodes[0].get_node_type().get_node_type(), simple_node_type) self.assertEqual(compound_1_graph_nodes[1].get_node_type().get_node_type(), simple_node_type) compound_2_graph = nodes[1].get_compound_graph_instance() self.assertTrue(compound_2_graph.is_valid()) compound_2_graph_nodes = compound_2_graph.get_nodes() self.assertEqual(1, len(compound_2_graph_nodes)) compound_2_1_graph = compound_2_graph_nodes[0].get_compound_graph_instance() self.assertTrue(compound_2_1_graph.is_valid()) compound_2_1_graph_nodes = compound_2_1_graph.get_nodes() self.assertEquals(2, len(compound_2_1_graph_nodes)) self.assertEqual(compound_2_1_graph_nodes[0].get_node_type().get_node_type(), simple_node_type) self.assertEqual(compound_2_1_graph_nodes[1].get_node_type().get_node_type(), simple_node_type) # try to create a node with the same name in the subgraph. All node names must be unique with self.assertRaises(og.OmniGraphError): controller.edit("/TestGraph", {_KEYS.CREATE_NODES: ("Compound_1_1", simple_node_type)}) # node with the same name on a subgraph as the parent with self.assertRaises(og.OmniGraphError): controller.edit( nodes[0].get_compound_graph_instance(), {_KEYS.CREATE_NODES: ("Compound_1", simple_node_type)} ) # allowed with a new controller though og.Controller.edit( nodes[0].get_compound_graph_instance(), {_KEYS.CREATE_NODES: ("Compound_1", simple_node_type)} ) self.assertTrue(compound_1_graph.get_node(f"{compound_1_graph.get_path_to_graph()}/Compound_1").is_valid()) # create another graph that uses the class lookup (og.Controller) instead of an object (_graph2, nodes2, _, path_node_map2) = og.Controller.edit( "/TestGraph2", { _KEYS.CREATE_NODES: [ ("Compound_1", {_KEYS.CREATE_NODES: ("Compound_1_1", simple_node_type)}), ] }, ) self.assertTrue(nodes2[0].is_valid()) self.assertTrue(nodes2[0].is_compound_node()) self.assertTrue(path_node_map2["Compound_1_1"].is_valid()) self.assertFalse(path_node_map2["Compound_1_1"].is_compound_node()) # -------------------------------------------------------------------------------------------------------------- async def test_attribute_promotion(self): """Tests the functionality of promoting attributes using the Controller._KEYS.PROMOTE_ATTRIBUTES command and the NodeController.promote_attribute() method""" controller = og.Controller(update_usd=True, undoable=True) simple_node_type = "omni.graph.tutorials.SimpleData" # graph with a subgraphs (graph, (compound, _non_compound), _, path_node_map) = controller.edit( "/TestGraph", { _KEYS.CREATE_NODES: [ ( "Compound_1", { _KEYS.CREATE_NODES: [ ("Compound_1_1", simple_node_type), ("Compound_1_2", simple_node_type), ( "Compound_1_3", { _KEYS.CREATE_NODES: [ ("Compound_1_3_1", simple_node_type), ] }, ), ] }, ), ("NonCompound", simple_node_type), ] }, ) # cannot promote on the top-level graph with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("NonCompound.inputs:a_int", "inputs:a_int")}) subgraph = compound.get_compound_graph_instance() # promote basic inputs, using both the graph and subgraph controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.inputs:a_int", "inputs:a_int")}) controller.edit(subgraph, {_KEYS.PROMOTE_ATTRIBUTES: [("Compound_1_2.outputs:a_int", "outputs:a_int")]}) self.assertTrue(compound.get_attribute_exists("inputs:a_int")) self.assertTrue(compound.get_attribute_exists("outputs:a_int")) # inputs already connected should fail. with ogts.ExpectedError(): with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.inputs:a_int", "inputs:a_int_2")}) # output already connected should pass controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_2.outputs:a_int", "outputs:a_int_2")}) self.assertTrue(compound.get_attribute_exists("outputs:a_int_2")) # input already exists with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_2.inputs:a_int", "inputs:a_int")}) # output already exists with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.outputs:a_int", "outputs:a_int")}) # input can be promoted as output controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.inputs:a_bool", "outputs:a_bool")}) # output cannot be promoted as input controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.outputs:a_bool", "inputs:a_bool_2")}) self.assertTrue(compound.get_attribute_exists("outputs:inputs:a_bool_2")) # promoted name without prefix, the prefix is automatically added controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.inputs:a_float", "a_float")}) controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.outputs:a_float", "a_float")}) self.assertTrue(compound.get_attribute_exists("inputs:a_float")) self.assertTrue(compound.get_attribute_exists("outputs:a_float")) # validate output only inputs promote as outputs controller.edit(subgraph, {_KEYS.CREATE_NODES: ("Compound_1_4", "omni.graph.nodes.ConstantDouble")}) controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_4.inputs:value", "constant")}) self.assertTrue(compound.get_attribute_exists("outputs:constant")) # similar tests but using the NodeController API directly compound_1_1_node = path_node_map["Compound_1_1"] compound_1_2_node = path_node_map["Compound_1_2"] og.NodeController.promote_attribute(og.Controller.attribute("inputs:a_half", compound_1_1_node), "a_half") og.NodeController.promote_attribute(og.Controller.attribute("outputs:a_half", compound_1_2_node), "a_half") self.assertTrue(compound.get_attribute_exists("inputs:a_half")) self.assertTrue(compound.get_attribute_exists("outputs:a_half")) # already exists with self.assertRaises(og.OmniGraphError): og.NodeController.promote_attribute(og.Controller.attribute("inputs:a_double", compound_1_1_node), "a_half") with self.assertRaises(og.OmniGraphError): og.NodeController.promote_attribute( og.Controller.attribute("outputs:a_double", compound_1_1_node), "a_half" ) # promote attributes on a nested recursion level controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_3_1.inputs:a_int", "inputs:value")}) self.assertTrue(path_node_map["Compound_1_3"].get_attribute_exists("inputs:value")) # ---------------------------------------------------------------------- async def test_attribute_creation(self): """Test attribute creation via the og.Controller class""" controller = og.Controller(undoable=False) (graph, (node,), _, _) = controller.edit( "/TestGraph", { _KEYS.CREATE_NODES: ("TestNode", "omni.graph.test.TestDynamicAttributeRawData"), _KEYS.CREATE_ATTRIBUTES: [ ("TestNode.inputs:a_float", "float"), ], }, ) self.assertTrue(node.is_valid()) a_float = node.get_attribute("inputs:a_float") self.assertTrue(a_float.is_valid()) base_attribute_count = len(node.get_attributes()) # A scattered assortment of spec combinations that covers all of the types accepted by the command test_configs = [ ("a_double", "/TestGraph/TestNode.inputs:a_double", "double"), ("a_any", Sdf.Path("/TestGraph/TestNode.inputs:a_any"), "any"), ("a_real", ("inputs:a_real", node), ["float", "double"]), ("a_numbers", (("a_numbers", og.AttributePortType.INPUT), node), ["numerics"]), ("a_bundle", ("inputs:a_bundle", "TestNode", graph), "bundle"), ("a_mesh", (("a_mesh", og.AttributePortType.INPUT), "TestNode", graph), "pointd[3][]"), ] for attr_name, attr_spec, attr_type in test_configs: controller.edit(graph, {_KEYS.CREATE_ATTRIBUTES: (attr_spec, attr_type)}) attr = node.get_attribute(f"inputs:{attr_name}") self.assertTrue(attr.is_valid()) self.assertEqual(base_attribute_count + len(test_configs), len(node.get_attributes())) # AttributeTypeSpec_t = str | og.Type | list[str] # """Typing that identifies a regular or extended type definition # 1. "any" # 2. og.Type(og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.VECTOR) # 3. ["float", "integral_scalers"] # """ # NewAttribute_t = Path_t | tuple[AttributeName_t, Node_t] | tuple[AttributeName_t, str, Graph_t] # """Typing for the information required to uniquely identify an attribute that does not yet exist # 1a. "/MyGraph/MyNode/inputs:new_attr" # 1b. Sdf.Path("/MyGraph/MyNode/inputs:new_attr") # 2a. ("inputs:new_attr", og.Controller.node("/MyGraph/MyNode")) # 2b. (("new_attr", og.AttributePortType.INPUT), og.Controller.node("/MyGraph/MyNode")) # 3a. ("inputs:new_attr", "MyNode", og.Controller.graph("/MyGraph")) # 3b. (("new_attr", og.AttributePortType.INPUT), "MyNode", og.Controller.graph("/MyGraph")) # """
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_graph_management.py
"""Tests relating to management of OmniGraph graphs""" import tempfile from pathlib import Path import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit import omni.usd class TestOmniGraphGraphManagement(ogts.OmniGraphTestCase): # -------------------------------------------------------------------------------------------------------------- async def test_multiple_schema_root_graphs(self): """Check that a configuration with more than one root level graph can be created, saved, and loaded. This test creates three root-level graphs and then executes all of them to confirm that they are working properly. Each graph is a simple addition sequence, where one is an action graph to confirm that different graphs can use different evaluators. Const1 ---v Add ---> SimpleData Const2 ---^ OnTick --> Counter """ keys = og.Controller.Keys (graph_1, (const_nodea_1, const_nodeb_1, _, simple_data_node_1), _, _) = og.Controller.edit( "/Graph1", { keys.CREATE_NODES: [ ("ConstA", "omni.graph.nodes.ConstantInt"), ("ConstB", "omni.graph.nodes.ConstantInt"), ("Add", "omni.graph.nodes.Add"), ("SimpleData", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("ConstA.inputs:value", "Add.inputs:a"), ("ConstB.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "SimpleData.inputs:a_int"), ], keys.SET_VALUES: [ ("ConstA.inputs:value", 3), ("ConstB.inputs:value", 7), ], }, ) # we'll be reading data directly in the graph: prevent any auto-instancing merging graph_1.set_auto_instancing_allowed(False) simple_data_node_1_path = simple_data_node_1.get_prim_path() graph_1_path = graph_1.get_path_to_graph() (graph_2, (const_nodea_2, const_nodeb_2, _, simple_data_node_2), _, _) = og.Controller.edit( "/Graph2", { keys.CREATE_NODES: [ ("ConstA", "omni.graph.nodes.ConstantInt"), ("ConstB", "omni.graph.nodes.ConstantInt"), ("Add", "omni.graph.nodes.Add"), ("SimpleData", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("ConstA.inputs:value", "Add.inputs:a"), ("ConstB.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "SimpleData.inputs:a_int"), ], keys.SET_VALUES: [ ("ConstA.inputs:value", 33), ("ConstB.inputs:value", 77), ], }, ) # we'll be reading data directly in the graph: prevent any auto-instancing merging graph_2.set_auto_instancing_allowed(False) simple_data_node_2_path = simple_data_node_2.get_prim_path() graph_2_path = graph_2.get_path_to_graph() (graph_3, (ontick_node, counter_node), _, _) = og.Controller.edit( { "graph_path": "/Graph3", "evaluator_name": "execution", }, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Counter", "omni.graph.action.Counter"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Counter.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ], }, ) # we'll be reading data directly in the graph: prevent any auto-instancing merging graph_3.set_auto_instancing_allowed(False) counter_node_path = counter_node.get_prim_path() graph_3_path = graph_3.get_path_to_graph() # ============================================================================================================== # OM-52190 specifies work that will prevent the need for this temporary setting. Without it, the values being # set onto the attributes will not be part of USD, and hence will not be saved out to the file, # causing the second half of the test to fail. stage = omni.usd.get_context().get_stage() stage.GetPrimAtPath(const_nodea_1.get_prim_path()).GetAttribute("inputs:value").Set(3) stage.GetPrimAtPath(const_nodeb_1.get_prim_path()).GetAttribute("inputs:value").Set(7) stage.GetPrimAtPath(const_nodea_2.get_prim_path()).GetAttribute("inputs:value").Set(33) stage.GetPrimAtPath(const_nodeb_2.get_prim_path()).GetAttribute("inputs:value").Set(77) stage.GetPrimAtPath(ontick_node.get_prim_path()).GetAttribute("inputs:onlyPlayback").Set(False) # ============================================================================================================== await og.Controller.evaluate([graph_1, graph_2, graph_3]) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_1)).get(), 10) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_2)).get(), 110) self.assertTrue(og.Controller(("state:count", counter_node)).get() > 0) with tempfile.TemporaryDirectory() as tmpdirname: await omni.kit.app.get_app().next_update_async() # save the file tmp_file_path = Path(tmpdirname) / "tmp.usda" result = omni.usd.get_context().save_as_stage(str(tmp_file_path)) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload the file back (result, error) = await ogts.load_test_file(str(tmp_file_path)) self.assertTrue(result, error) graph_1 = og.get_graph_by_path(graph_1_path) graph_2 = og.get_graph_by_path(graph_2_path) graph_3 = og.get_graph_by_path(graph_3_path) simple_data_node_1 = og.get_node_by_path(simple_data_node_1_path) simple_data_node_2 = og.get_node_by_path(simple_data_node_2_path) counter_node = og.get_node_by_path(counter_node_path) self.assertIsNotNone(simple_data_node_1) self.assertIsNotNone(simple_data_node_2) self.assertIsNotNone(counter_node) await og.Controller.evaluate([graph_1, graph_2, graph_3]) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_1)).get(), 10) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_2)).get(), 110) self.assertTrue(og.Controller(("state:count", counter_node)).get() > 0) # Close the stage to avoid dangling references to the graph. (OM-84680) await omni.usd.get_context().close_stage_async()
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_math_nodes.py
"""Test the math nodes""" import math import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts # ====================================================================== class TestMathNodes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises graph functionality""" TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- async def test_add_node_simple(self): """Test the add node for a variety of simple types""" controller = og.Controller() keys = og.Controller.Keys (graph, (simple_node_a, simple_node_b, simple_node_sum, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ("SimpleSum", "omni.graph.tutorials.SimpleData"), ("Add", "omni.graph.nodes.Add"), ] }, ) input_a = add_node.get_attribute("inputs:a") input_b = add_node.get_attribute("inputs:b") output_sum = add_node.get_attribute("outputs:sum") # Test data is a list of lists, one per test configuration, containing (ATTRIBUTE, A, B, SUM): # ATTRIBUTE: the name of the attribute to be connected from the "Simple" nodes to resolve the data types # A: First value to add # B: Second value to add # SUM: Expected sum # (Note that since the simple nodes add 1 to inputs to get outputs SUM != A + B) test_data = [ ["a_float", 5.25, 6.25, 13.5], ["a_double", 5.125, 6.125, 13.25], ["a_half", 5.0, 6.0, 13.0], ["a_int", 6, 7, 15], ["a_int64", 8, 9, 19], ["unsigned:a_uchar", 10, 11, 23], ["unsigned:a_uint", 12, 13, 27], ["unsigned:a_uint64", 14, 15, 31], ] for (attribute_name, a, b, expected) in test_data: connection_list = [ ((f"outputs:{attribute_name}", simple_node_a), input_a), ((f"outputs:{attribute_name}", simple_node_b), input_b), (output_sum, (f"inputs:{attribute_name}", simple_node_sum)), ] controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: connection_list, keys.SET_VALUES: [ ((f"inputs:{attribute_name}", simple_node_a), a), ((f"inputs:{attribute_name}", simple_node_b), b), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(output_sum) self.assertAlmostEqual(expected, actual) # Disconnecting the connections we just made lets the loop work controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: connection_list}) # ---------------------------------------------------------------------- async def test_add_node_mismatched(self): """Test the add node for simple types that have compatible but not identical types""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, _, _, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ("SimpleSum", "omni.graph.tutorials.SimpleData"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("SimpleA.outputs:a_double", "Add.inputs:a"), ("SimpleB.outputs:a_int", "Add.inputs:b"), ("Add.outputs:sum", "SimpleSum.inputs:a_float"), ], keys.SET_VALUES: [ ("SimpleA.inputs:a_double", 5.5), ("SimpleB.inputs:a_int", 11), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(controller.attribute("outputs:sum", add_node)) self.assertAlmostEqual(18.5, actual) # ---------------------------------------------------------------------- async def test_add_node_tuples(self): """Test the add node for a variety of tuple types""" controller = og.Controller() keys = og.Controller.Keys (graph, (tuple_node_a, tuple_node_b, tuple_node_sum, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("TupleA", "omni.tutorials.TupleData"), ("TupleB", "omni.tutorials.TupleData"), ("TupleSum", "omni.tutorials.TupleData"), ("Add", "omni.graph.nodes.Add"), ] }, ) input_a = add_node.get_attribute("inputs:a") input_b = add_node.get_attribute("inputs:b") output_sum = add_node.get_attribute("outputs:sum") # Test data is a list of lists, one per test configuration, containing (ATTRIBUTE, A, B, SUM): # ATTRIBUTE: the name of the attribute to be connected from the "Tuple" nodes to resolve the data types # A: First value to add # B: Second value to add # SUM: Expected sum # (Note that since the tuple nodes add 1 to input elements to get outputs SUM != A + B) test_data = [ ["a_double2", (20.0, 30.0), (20.1, 30.1), (42.1, 62.1)], ["a_float2", (2.0, 3.0), (2.1, 3.1), (6.1, 8.1)], ["a_half2", (1.0, 2.0), (3.0, 4.0), (6.0, 8.0)], ["a_int2", (16, -5), (22, 5), (40, 2)], ["a_float3", (1.1, 2.2, 3.3), (2.2, 3.3, 4.4), (5.3, 7.5, 9.7)], ["a_double3", (10.1, 20.2, 30.3), (20.2, 30.3, 40.4), (32.3, 52.5, 72.7)], ] for (attribute_name, a, b, expected) in test_data: connection_list = [ ((f"outputs:{attribute_name}", tuple_node_a), input_a), ((f"outputs:{attribute_name}", tuple_node_b), input_b), (output_sum, (f"inputs:{attribute_name}", tuple_node_sum)), ] controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: connection_list, keys.SET_VALUES: [ ((f"inputs:{attribute_name}", tuple_node_a), a), ((f"inputs:{attribute_name}", tuple_node_b), b), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(output_sum) self.assertTrue(np.allclose(expected, actual), f"{expected} != {actual}") # Disconnecting the connections we just made lets the loop work controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: connection_list}) # ---------------------------------------------------------------------- async def test_add_node_arrays(self): """Test the add node for a variety of array types""" controller = og.Controller() keys = og.Controller.Keys (graph, (array_node_a, array_node_b, array_node_sum, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ArrayA", "omni.graph.tutorials.ArrayData"), ("ArrayB", "omni.graph.tutorials.ArrayData"), ("ArraySum", "omni.graph.tutorials.ArrayData"), ("Add", "omni.graph.nodes.Add"), ], keys.SET_VALUES: [ # Set the array nodes up to double the values ("ArrayA.inputs:multiplier", 2.0), ("ArrayB.inputs:multiplier", 2.0), ], }, ) input_a = add_node.get_attribute("inputs:a") input_b = add_node.get_attribute("inputs:b") output_sum = add_node.get_attribute("outputs:sum") # Test data is a list of lists, one per test configuration, containing (A, B, SUM): # A: First value to add # B: Second value to add # SUM: Expected sum # (Note that since the array nodes add 1 to input elements to get outputs SUM != A + B) test_data = [ [[20.0, 30.0], [20.1, 30.1], [80.2, 120.2]], [[1.0, 2.0, 3.0, 4.0], [-1.0, -2.0, -3.0, -4.0], [0.0, 0.0, 0.0, 0.0]], ] for (a, b, expected) in test_data: controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: [ (("outputs:result", array_node_a), input_a), (("outputs:result", array_node_b), input_b), (output_sum, ("inputs:original", array_node_sum)), ], keys.SET_VALUES: [ (("inputs:gates", array_node_a), [True] * len(a)), (("inputs:gates", array_node_b), [True] * len(b)), (("inputs:original", array_node_a), a), (("inputs:original", array_node_b), b), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(output_sum) self.assertTrue(np.allclose(expected, actual), f"{expected} != {actual}") # ---------------------------------------------------------------------- async def test_add_node_tuple_arrays(self): """Test the add node for array-of-tuple types""" controller = og.Controller() keys = og.Controller.Keys (graph, (tuple_array_node_a, tuple_array_node_b, tuple_array_node_sum, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("TupleArrayA", "omni.graph.test.TupleArrays"), ("TupleArrayB", "omni.graph.test.TupleArrays"), ("TupleArraySum", "omni.graph.test.TupleArrays"), ("Add", "omni.graph.nodes.Add"), ], keys.SET_VALUES: [ # Set the array nodes up to double the values ("TupleArrayA.inputs:multiplier", 2.0), ("TupleArrayB.inputs:multiplier", 2.0), ], }, ) input_a = add_node.get_attribute("inputs:a") input_b = add_node.get_attribute("inputs:b") output_sum = add_node.get_attribute("outputs:sum") # Test data is a list of lists, one per test configuration, containing (A, B, SUM): # A: First value to add # B: Second value to add # SUM: Expected sum # (Note that since the array nodes add 1 to input elements to get outputs SUM != A + B) test_data = [ [ [[1.0, 2.0, 3.0], [1.1, 2.2, 3.3]], [[10.0, 20.0, 30.0], [11.0, 22.0, 33.0]], [[22.0, 44.0, 66.0], [24.2, 48.4, 72.6]], ], ] for (a, b, expected) in test_data: controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: [ (("outputs:float3Array", tuple_array_node_a), input_a), (("outputs:float3Array", tuple_array_node_b), input_b), (output_sum, ("inputs:float3Array", tuple_array_node_sum)), ], keys.SET_VALUES: [ (("inputs:float3Array", tuple_array_node_a), a), (("inputs:float3Array", tuple_array_node_b), b), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(output_sum) self.assertTrue(np.allclose(expected, actual), f"{expected} != {actual}") # ---------------------------------------------------------------------- async def test_add_all_types(self): """Test the OgnAdd node with all types""" node_name = "omni.graph.nodes.Add" # Input attributes to be resolved input_attribute_names = ["inputs:a", "inputs:b"] # Output attributes to be tested output_attribute_names = ["outputs:sum"] # list of unsupported types unsupported_types = ["string", "token", "path", "bool", "uint64", "bundle", "target"] # Operation giving the expected value operation = np.add # ---------------------------------------------------------- controller = og.Controller() keys = og.Controller.Keys (graph, (test_node, data_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: [("TestNode", node_name), ("TestData", "omni.graph.test.TestAllDataTypes")]}, ) # Generate Test data consisting of the input attribute followed by the expected output values test_data = [] for attribute in data_node.get_attributes(): type_base_name = attribute.get_resolved_type().get_base_type_name() if ( "output" not in attribute.get_name() or type_base_name in unsupported_types or attribute.get_type_name() in unsupported_types or attribute.get_resolved_type().role == og.AttributeRole.EXECUTION ): continue value = og.Controller.get(attribute) test_data.append([attribute, operation(value, value)]) input_attributes = [test_node.get_attribute(input_attribute) for input_attribute in input_attribute_names] output_attributes = [test_node.get_attribute(output_attribute) for output_attribute in output_attribute_names] for data_attribute, expected_value in test_data: connections = [(data_attribute, input_attribute) for input_attribute in input_attributes] controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: connections}) await controller.evaluate(graph) # Check outputs for output_attribute in output_attributes: actual_value = og.Controller.get(output_attribute) self.assertTrue(np.allclose(expected_value, actual_value), f"{expected_value} != {actual_value}") controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: connections}) # ---------------------------------------------------------------------- async def test_multiply_all_types(self): """Test the OgnMultiply node with all types""" node_name = "omni.graph.nodes.Multiply" # Input attributes to be resolved input_attribute_names = ["inputs:a", "inputs:b"] # Output attributes to be tested output_attribute_names = ["outputs:product"] # list of unsupported types unsupported_types = ["string", "token", "path", "bool", "uint64", "bundle", "target"] # Operation giving the expected value operation = np.multiply # ---------------------------------------------------------- controller = og.Controller() keys = og.Controller.Keys (graph, (test_node, data_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: [("TestNode", node_name), ("DataNode", "omni.graph.test.TestAllDataTypes")]}, ) # Generate Test data consisting of the input attribute followed by the expected output values test_data = [] for attribute in data_node.get_attributes(): type_base_name = attribute.get_resolved_type().get_base_type_name() if ( "output" not in attribute.get_name() or type_base_name in unsupported_types or attribute.get_type_name() in unsupported_types or attribute.get_resolved_type().role == og.AttributeRole.EXECUTION ): continue value = og.Controller.get(attribute) test_data.append([attribute, operation(value, value)]) input_attributes = [test_node.get_attribute(input_attribute) for input_attribute in input_attribute_names] output_attributes = [test_node.get_attribute(output_attribute) for output_attribute in output_attribute_names] for data_attribute, expected_value in test_data: connections = [(data_attribute, input_attribute) for input_attribute in input_attributes] controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: connections}) await controller.evaluate(graph) # Check outputs for output_attribute in output_attributes: actual_value = og.Controller.get(output_attribute) self.assertTrue(np.allclose(expected_value, actual_value), f"{expected_value} != {actual_value}") controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: connections}) # ---------------------------------------------------------------------- async def test_constant_pi_node(self): """Test the constant pi node""" controller = og.Controller() keys = og.Controller.Keys() (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: [("constPi", "omni.graph.nodes.ConstantPi")]} ) result = nodes[0].get_attribute("outputs:value") setter = og.Controller(attribute=og.Controller.attribute("inputs:factor", nodes[0])) getter = og.Controller(attribute=result) # Test data is a list, one per test configuration, containing (A, SUM): # A: Multiply this by Pi to get the result # SUM: Expected value test_data = [ [1.0, math.pi], [2.0, 2.0 * math.pi], [0.5, 0.5 * math.pi], ] for (multiplier, expected) in test_data: setter.set(multiplier) await og.Controller.evaluate(graph) self.assertAlmostEqual(expected, getter.get()) # --------------------------------------------------------------------- async def test_nth_root_node(self): """Test the nthroot node""" controller = og.Controller() keys = og.Controller.Keys() (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("nthRoot", "omni.graph.nodes.NthRoot"), ("src", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [("src.inputs:value", "nthRoot.inputs:value")], }, ) result = nodes[0].get_attribute("outputs:result") value_setter = og.Controller(attribute=og.Controller.attribute("inputs:value", nodes[1])) nth_root_setter = og.Controller(attribute=og.Controller.attribute("inputs:nthRoot", nodes[0])) getter = og.Controller(attribute=result) # Test data is a list, one per test configuration, containing (nthroot, value): # nthroot: Take the nthroot of the value # value: The number that is to be taken roots test_data = [[2, -4], [4, -8.0], [5, -1]] for (nthroot, value) in test_data: nth_root_setter.set(nthroot) value_setter.set(value) await og.Controller.evaluate(graph) self.assertTrue(np.isnan(getter.get())) test_data = [[3, -8.0, -2], [3, -1, -1]] for (nthroot, value, expected) in test_data: nth_root_setter.set(nthroot) value_setter.set(value) await og.Controller.evaluate(graph) self.assertEqual(expected, getter.get()) # ---------------------------------------------------------------------- async def test_floor_node_backwards_compatibility(self): """Test the floor node extended outputs for backwards compatibility""" # Test data contains floor nodes with int output, instead of token (result, error) = await ogts.load_test_file("TestFloorOutput.usda", use_caller_subdirectory=True) self.assertTrue(result, f"{error}") controller = og.Controller() graph = controller.graph("/World/TestGraph") def assert_attr_is_int(node): attr = controller.attribute("outputs:result", node, graph) self.assertEqual(attr.get_resolved_type().base_type, og.BaseDataType.INT) assert_attr_is_int("floor_double") assert_attr_is_int("floor_float") assert_attr_is_int("floor_half")
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_extended_attributes.py
# noqa PLC0302 """Tests that exercise the functionality of the extended (union and any) attribute types""" import os import tempfile from typing import List, Optional import carb import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.app import omni.kit.stage_templates import omni.kit.test import omni.usd from pxr import Gf, Sdf, UsdGeom, Vt # ====================================================================== class TestExtendedAttributes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises graph functionality""" TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- async def test_output_type_resolution(self): """Test the automatic type resolution for extended types based on output connection types""" controller = og.Controller() keys = og.Controller.Keys # Node is by itself, union attributes have no type (use Attribute.getTypeName to check) (graph, (extended_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("ExtendedNode", "omni.graph.test.TypeResolution")} ) value_output = "outputs:value" array_output = "outputs:arrayValue" tuple_output = "outputs:tupleValue" tuple_array_output = "outputs:tupleArrayValue" mixed_output = "outputs:mixedValue" any_output = "outputs:anyValue" resolved_type = controller.attribute("outputs:resolvedType", extended_node) value = controller.attribute(value_output, extended_node) array_value = controller.attribute(array_output, extended_node) tuple_value = controller.attribute(tuple_output, extended_node) tuple_array_value = controller.attribute(tuple_array_output, extended_node) mixed_value = controller.attribute(mixed_output, extended_node) any_value = controller.attribute(any_output, extended_node) await controller.evaluate(graph) def result(): return og.Controller.get(resolved_type) def expected( value_type: Optional[str] = None, array_type: Optional[str] = None, tuple_type: Optional[str] = None, tuple_array_type: Optional[str] = None, mixed_type: Optional[str] = None, any_type: Optional[str] = None, ) -> List[str]: """Return an expected output array for the given resolved types (None means unresolved)""" return [ f"{value_output},{value_type if value_type else 'unknown'}", f"{array_output},{array_type if array_type else 'unknown'}", f"{tuple_output},{tuple_type if tuple_type else 'unknown'}", f"{tuple_array_output},{tuple_array_type if tuple_array_type else 'unknown'}", f"{mixed_output},{mixed_type if mixed_type else 'unknown'}", f"{any_output},{any_type if any_type else 'unknown'}", ] default_expected = expected() default_actual = result() self.assertEqual(len(default_expected), len(default_actual)) self.assertCountEqual(default_expected, default_actual) # Node has float/token output connected to a float input - type should be float controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Simple", "omni.graph.tutorials.SimpleData"), keys.CONNECT: (value, "Simple.inputs:a_float"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected("float"), result()) # Node disconnects, then connects the same output to an int input - type should be int controller.edit( self.TEST_GRAPH_PATH, { keys.DISCONNECT: (value, "Simple.inputs:a_float"), }, ) controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: (value, "Simple.inputs:a_int"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected("int"), result()) # Node totally disconnects - type should be reverted to unknown controller.edit( self.TEST_GRAPH_PATH, { keys.DISCONNECT: (value, "Simple.inputs:a_int"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected(), result()) # Adding array type connection controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Array", "omni.graph.tutorials.ArrayData"), keys.CONNECT: (array_value, "Array.inputs:original"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected("unknown", "float[]"), result()) # Adding tuple, tupleArray, and mixed type connections controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Tuple", "omni.tutorials.TupleData"), ("TupleArray", "omni.graph.tutorials.TupleArrays"), ], keys.CONNECT: [ (tuple_value, "Tuple.inputs:a_float3"), (tuple_array_value, "TupleArray.inputs:a"), (mixed_value, "Array.inputs:original"), ], }, ) await controller.evaluate(graph) self.assertCountEqual(expected("unknown", "float[]", "float[3]", "float[3][]", "float[]"), result()) # Adding anyValue connection, check type controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: (any_value, "Simple.inputs:a_float"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected("unknown", "float[]", "float[3]", "float[3][]", "float[]", "float"), result()) # Now test the type-resolution cascade for a linear chain of any-type connections (_, (extended_node_a, extended_node_b, extended_node_c), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ExtendedNodeA", "omni.graph.test.TypeResolution"), ("ExtendedNodeB", "omni.graph.test.TypeResolution"), ("ExtendedNodeC", "omni.graph.test.TypeResolution"), ], keys.CONNECT: [ ("ExtendedNodeA.outputs:anyValue", "ExtendedNodeB.inputs:anyValueIn"), ("ExtendedNodeB.outputs:anyValue", "ExtendedNodeC.inputs:anyValueIn"), ], }, ) await controller.evaluate(graph) node_a_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_a)) node_b_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_b)) node_c_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_c)) resolved_types = node_c_controller.get() self.assertCountEqual(expected(), resolved_types) # connect a concrete type to the start of the chain and verify it cascades to the last output controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: ("Simple.outputs:a_double", "ExtendedNodeA.inputs:anyValueIn"), }, ) await controller.evaluate(graph) resolved_types = node_a_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) resolved_types = node_b_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) resolved_types = node_c_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) # remove the concrete connection and verify it cascades unresolved to the last output # FIXME: Auto-unresolve is not supported yet # controller.edit(self.TEST_GRAPH_PATH, { # keys.DISCONNECT: ("Simple.outputs:a_double", "ExtendedNodeA.inputs:anyValueIn"), # }) # await controller.evaluate(graph) # # resolved_types = node_a_controller.get() # self.assertCountEqual(expected(), resolved_types) # resolved_types = node_b_controller.get() # self.assertCountEqual(expected(), resolved_types) # resolved_types = node_c_controller.get() # self.assertCountEqual(expected(), resolved_types) # add a concrete type to the output connection at the end of the chain and verify it cascades upwards # to the input of the start of the chain (_, (extended_node_a, extended_node_b, extended_node_c), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.DELETE_NODES: [ extended_node_a, extended_node_b, extended_node_c, ], keys.CREATE_NODES: [ ("ExtendedNodeA", "omni.graph.test.TypeResolution"), ("ExtendedNodeB", "omni.graph.test.TypeResolution"), ("ExtendedNodeC", "omni.graph.test.TypeResolution"), ], keys.CONNECT: [ ("ExtendedNodeA.outputs:anyValue", "ExtendedNodeB.inputs:anyValueIn"), ("ExtendedNodeB.outputs:anyValue", "ExtendedNodeC.inputs:anyValueIn"), ("ExtendedNodeC.outputs:anyValue", "Simple.inputs:a_double"), ], }, ) await controller.evaluate(graph) node_a_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_a)) node_b_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_b)) node_c_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_c)) resolved_types = node_c_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) resolved_types = node_b_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) resolved_types = node_a_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) # ---------------------------------------------------------------------- async def test_type_propagation(self): """Test the propagation of type resolution through the network""" controller = og.Controller() keys = og.Controller.Keys # Test with a more complicated diamond-shaped topology # +-----+ # +-->| B +-+ +-----+ # +-----+ +------+-+ +-----+ |-->| | +-----+ # | SA +--->| A | | Add |-->| SB + # +-----+ +------+-+ +-----+ |-->| | +-----+ # +-->| C +-+ +-----+ # +-----+ # (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("ExtendedNodeA", "omni.graph.test.TypeResolution"), ("ExtendedNodeB", "omni.graph.test.TypeResolution"), ("ExtendedNodeC", "omni.graph.test.TypeResolution"), ("Add", "omni.graph.nodes.Add"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("ExtendedNodeA.outputs:anyValue", "ExtendedNodeB.inputs:anyValueIn"), ("ExtendedNodeA.outputs:anyValue", "ExtendedNodeC.inputs:anyValueIn"), ("ExtendedNodeB.outputs:anyValue", "Add.inputs:a"), ("ExtendedNodeC.outputs:anyValue", "Add.inputs:b"), ("Add.outputs:sum", "SimpleB.inputs:a_double"), # Concrete double wired to front of chain to propagate forward ("SimpleA.outputs:a_double", "ExtendedNodeA.inputs:anyValueIn"), ], keys.SET_VALUES: [ ("SimpleA.inputs:a_double", 10.0), ], }, ) await controller.evaluate(graph) (simple_a_node, extended_node_a, _, _, add_node, simple_b_node) = nodes v = og.Controller.get(controller.attribute("outputs:a_double", simple_a_node)) self.assertEqual(v, 11.0) v = og.Controller.get(controller.attribute("outputs:anyValue", extended_node_a)) self.assertEqual(v, 11.0) v = og.Controller.get(controller.attribute("outputs:sum", add_node)) self.assertEqual(v, 22.0) # connect the last any output to a concrete input, verify value controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: ("Add.outputs:sum", "SimpleB.inputs:a_double"), }, ) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:a_double", simple_b_node)) self.assertEqual(v, 23.0) # disconnect and re-connect the connection, verify the value is the same (tests output re-connect) controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: ("Add.outputs:sum", "SimpleB.inputs:a_double")}) await controller.evaluate(graph) controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: ("Add.outputs:sum", "SimpleB.inputs:a_double")}) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:a_double", simple_b_node)) self.assertEqual(v, 23.0) # disconnect and re-connect the extended inputs to sum and verify (tests input re-connect) controller.edit( self.TEST_GRAPH_PATH, { keys.DISCONNECT: [ ("ExtendedNodeB.outputs:anyValue", "Add.inputs:a"), ("ExtendedNodeC.outputs:anyValue", "Add.inputs:b"), ] }, ) await controller.evaluate(graph) controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: [ ("ExtendedNodeB.outputs:anyValue", "Add.inputs:a"), ("ExtendedNodeC.outputs:anyValue", "Add.inputs:b"), ] }, ) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:a_double", simple_b_node)) self.assertEqual(v, 23.0) # ---------------------------------------------------------------------- async def test_sandwiched_type_resolution(self): """modulo (which only operate on integers) is sandwiched between 2 nodes that feed/expect double this setup will test that this conversion are correctly chosen""" controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Modulo", "omni.graph.nodes.Modulo"), ("ConstD", "omni.graph.nodes.ConstantDouble"), ("ConstF", "omni.graph.nodes.ConstantFloat"), ("Scale", "omni.graph.nodes.ScaleToSize"), ], keys.CONNECT: [ ("ConstD.inputs:value", "Modulo.inputs:a"), ("ConstD.inputs:value", "Modulo.inputs:b"), ("Modulo.outputs:result", "Scale.inputs:speed"), ], }, ) await controller.evaluate(graph) # Helper to verify the base data type of an attribute def assert_attrib_is(attrib, node, base_type): attrib = controller.attribute(attrib, node, graph) self.assertEqual(attrib.get_resolved_type().base_type, base_type) assert_attrib_is("outputs:result", "Modulo", og.BaseDataType.INT64) # Disconnect the Multiply inputs to cause a wave of unresolutions controller.edit( graph, {keys.DISCONNECT: [("ConstD.inputs:value", "Modulo.inputs:a"), ("ConstD.inputs:value", "Modulo.inputs:b")]}, ) await controller.evaluate(graph) assert_attrib_is("outputs:result", "Modulo", og.BaseDataType.UNKNOWN) # now connect a float on input:a, that should make it the prefered type to choose conversion from # which will be INT this time controller.edit( graph, {keys.CONNECT: [("ConstF.inputs:value", "Modulo.inputs:a"), ("ConstD.inputs:value", "Modulo.inputs:b")]}, ) await controller.evaluate(graph) assert_attrib_is("outputs:result", "Modulo", og.BaseDataType.INT) # ---------------------------------------------------------------------- async def test_reconnect_different_type(self): """Tests re-resolving and the RESOLVE_ATTRIBUTE event""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, node, _, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("ForEach", "omni.graph.action.ForEach"), ("Get", "omni.graph.nodes.ReadPrimAttribute"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: [ ("/World/Source", {"myfloatarray": ("float[]", [1000.5]), "myintarray": ("int64[]", [2**40])}), ("/World/Sink", {"myfloat": ("float", 0), "myint": ("int64", 0)}), ], keys.CONNECT: [ ("OnTick.outputs:tick", "ForEach.inputs:execIn"), ("Get.outputs:value", "ForEach.inputs:arrayIn"), ("ForEach.outputs:element", "Set.inputs:value"), ], keys.SET_VALUES: [ ("Set.inputs:name", "myfloat"), ("Set.inputs:primPath", "/World/Sink"), ("Set.inputs:usePath", True), ("Get.inputs:name", "myfloatarray"), ("Get.inputs:primPath", "/World/Source"), ("Get.inputs:usePath", True), ], }, ) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:element", node)) self.assertEqual(v, 1000.5) # Trigger unresolve and re-resolve of the 2 ForEach attributes event_counter = [0] def on_node_event(event): self.assertEqual(event.type, int(og.NodeEvent.ATTRIBUTE_TYPE_RESOLVE)) event_counter[0] += 1 # Hold on to the sub! sub = node.get_event_stream().create_subscription_to_pop(on_node_event) with ogts.ExpectedError(): controller.edit( self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Set.inputs:name", "myint"), ("Get.inputs:name", "myintarray")]}, ) await controller.evaluate(graph) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:element", node)) self.assertEqual(v, 2**40) # Check we got the right number of callbacks (2x callbacks for 2 attributes) self.assertEqual(event_counter[0], 4) del sub # ---------------------------------------------------------------------- # Tests of ReadPrimAttribute follow async def test_readprimattribute_scaler(self): """Exercise ReadPrimAttribute for scaler value""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Get", "omni.graph.nodes.ReadPrimAttribute"), keys.CREATE_PRIMS: ("/World/Float", {"myfloat": ("float", 42.0)}), keys.SET_VALUES: [ ("Get.inputs:name", "myfloat"), ("Get.inputs:primPath", "/World/Float"), ("Get.inputs:usePath", True), ], }, ) await controller.evaluate(graph) await controller.evaluate(graph) get_node_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) self.assertEqual(get_node_controller.get(), 42.0) # Change USD attrib, check we get the new value on our output attr = stage.GetPropertyAtPath("/World/Float.myfloat") attr.Set(0.0) await controller.evaluate(graph) self.assertEqual(get_node_controller.get(), 0.0) # Same test but with bundle input stage.GetPrimAtPath(f"{self.TEST_GRAPH_PATH}/Get").GetRelationship("inputs:prim").SetTargets( [Sdf.Path("/World/Float")] ) attr.Set(42.0) controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("Get.inputs:usePath", False)}) await controller.evaluate(graph) self.assertEqual(get_node_controller.get(), 42.0) # Change USD attrib, check we get the new value on our output attr = stage.GetPropertyAtPath("/World/Float.myfloat") attr.Set(0.0) await controller.evaluate(graph) self.assertEqual(get_node_controller.get(), 0.0) # ---------------------------------------------------------------------- async def test_readprimattribute_noexist(self): """Test ReadPrimAttribute can handle attribute that exists in USD but not in FC""" controller = og.Controller() keys = og.Controller.Keys (graph, (get_node,), (prim,), _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Get", "omni.graph.nodes.ReadPrimAttribute"), keys.CREATE_PRIMS: ("/World/Cube", "Cube"), keys.SET_VALUES: [ ("Get.inputs:name", "visibility"), ("Get.inputs:primPath", "/World/Cube"), ("Get.inputs:usePath", True), ], }, ) await controller.evaluate(graph) await controller.evaluate(graph) self.assertEqual(og.Controller.get(controller.attribute("outputs:value", get_node)), "inherited") # Change USD attrib, check we get the new value on our output UsdGeom.Imageable(prim).MakeInvisible() await controller.evaluate(graph) # ReadPrimAttribute will put the visibility value to Fabric, but it doesn't get # updated by the FSD USD handler. # Instead it updates the visibility of the prim, so this is a workaround to test # that the visibility of the prim been updated. if carb.settings.get_settings().get("/app/useFabricSceneDelegate"): import usdrt stage = usdrt.Usd.Stage.Attach(omni.usd.get_context().get_stage_id()) prim = stage.GetPrimAtPath("/World/Cube") attr = prim.GetAttribute("_worldVisibility") self.assertFalse(attr.Get()) else: self.assertEqual(og.Controller.get(controller.attribute("outputs:value", get_node)), "invisible") # ---------------------------------------------------------------------- async def test_readprimattribute_tuple(self): """Exercise ReadPrimAttribute for a tuple value""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Get", "omni.graph.nodes.ReadPrimAttribute"), keys.CREATE_PRIMS: ("/World/Double3", {"mydouble3": ("double[3]", Gf.Vec3d(42.0, 40.0, 1.0))}), keys.SET_VALUES: [ ("Get.inputs:name", "mydouble3"), ("Get.inputs:primPath", "/World/Double3"), ("Get.inputs:usePath", True), ], }, ) await controller.evaluate(graph) og.Controller.get(controller.attribute("outputs:value", get_node)) self.assertEqual( Gf.Vec3d(*og.Controller.get(controller.attribute("outputs:value", get_node))), Gf.Vec3d(42.0, 40.0, 1.0) ) # Change USD attrib, check we get the new value on our output attr = stage.GetPropertyAtPath("/World/Double3.mydouble3") attr.Set(Gf.Vec3d(0, 0, 0)) await controller.evaluate(graph) self.assertEqual( Gf.Vec3d(*og.Controller.get(controller.attribute("outputs:value", get_node))), Gf.Vec3d(0, 0, 0) ) # ---------------------------------------------------------------------- async def test_readprimattribute_array(self): """Exercise ReadPrimAttribute for an array value""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys small_array = [0xFF for _ in range(10)] (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Get", "omni.graph.nodes.ReadPrimAttribute"), keys.CREATE_PRIMS: ("/World/IntArray", {"myintarray": ("int[]", small_array)}), keys.SET_VALUES: [ ("Get.inputs:name", "myintarray"), ("Get.inputs:usePath", True), ("Get.inputs:primPath", "/World/IntArray"), ], }, ) await controller.evaluate(graph) self.assertSequenceEqual( og.Controller.get(controller.attribute("outputs:value", get_node)).tolist(), small_array ) # Change USD attrib, check we get the new value on our output big_array = Vt.IntArray(1000, [0 for _ in range(1000)]) attr = stage.GetPropertyAtPath("/World/IntArray.myintarray") attr.Set(big_array) await controller.evaluate(graph) self.assertSequenceEqual(og.Controller.get(controller.attribute("outputs:value", get_node)).tolist(), big_array) # ---------------------------------------------------------------------- async def test_dynamic_extended_attributes_any(self): """Test functionality of extended any attributes when they are created dynamically""" # Set up a graph that tests dynamically created extended attrs. Here we have a node with # extended attribute attr1. We create another extended attribute dynamically (dynamic_attr1) # we then make sure these two behave the same. dyanmic_attr1 is an any attribute in this case # # SimpleIn ----=> Extended1 # -inputs:anyValueIn # -inputs:dynamic_attr1 # controller = og.Controller() keys = og.Controller.Keys (graph, (simple_node, extended_node_1), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleIn", "omni.graph.tutorials.SimpleData"), ("Extended1", "omni.graph.test.TypeResolution"), ], keys.CONNECT: ("SimpleIn.outputs:a_float", "Extended1.inputs:anyValueIn"), keys.SET_VALUES: ("SimpleIn.inputs:a_float", 5.0), }, ) await controller.evaluate(graph) # Check that the inputs into the extended type nodes are correct self.assertEqual(6.0, og.Controller.get(controller.attribute("inputs:anyValueIn", extended_node_1))) extended_node_1.create_attribute( "inputs:dynamic_attr1", og.Type(og.BaseDataType.TOKEN), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, "", ) controller.edit( self.TEST_GRAPH_PATH, {keys.CONNECT: (("outputs:a_float", simple_node), ("inputs:dynamic_attr1", extended_node_1))}, ) await controller.evaluate(graph) self.assertEqual(6.0, og.Controller.get(controller.attribute("inputs:dynamic_attr1", extended_node_1))) # ---------------------------------------------------------------------- async def test_dynamic_extended_attributes_union(self): """Test functionality of extended union attributes when they are created dynamically""" # Set up a graph that tests dynamically created extended attrs. Here we have a node with # extended attribute attr1. We create another extended attribute dynamically (dynamic_attr1) # we then make sure these two behave the same. dyanmic_attr1 is a union attribute in this case # # SimpleIn ----=> Extended1 # -inputs:anyValueIn # -inputs:dynamic_attr1 # controller = og.Controller() keys = og.Controller.Keys (graph, (simple_node, extended_node_1), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleIn", "omni.graph.tutorials.SimpleData"), ("Extended1", "omni.graph.tutorials.ExtendedTypes"), ], keys.CONNECT: ("SimpleIn.outputs:a_float", "Extended1.inputs:floatOrToken"), keys.SET_VALUES: ("SimpleIn.inputs:a_float", 5.0), }, ) await controller.evaluate(graph) # Check that the inputs into the extended type nodes are correct self.assertEqual(6.0, og.Controller.get(controller.attribute("inputs:floatOrToken", extended_node_1))) extended_node_1.create_attribute( "inputs:dynamic_attr1", og.Type(og.BaseDataType.TOKEN), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, "float,token", ) controller.edit( self.TEST_GRAPH_PATH, {keys.CONNECT: (("outputs:a_float", simple_node), ("inputs:dynamic_attr1", extended_node_1))}, ) await controller.evaluate(graph) self.assertEqual(6.0, og.Controller.get(controller.attribute("inputs:dynamic_attr1", extended_node_1))) # ---------------------------------------------------------------------- async def test_unresolve_propagation(self): """Tests unresolve propagates through the network""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, _, _, _, to_string_node, _, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ConstDouble", "omni.graph.nodes.ConstantDouble"), ("Const1", "omni.graph.nodes.ConstantVec3d"), ("Multiply", "omni.graph.nodes.Multiply"), ("Magnitude", "omni.graph.nodes.Magnitude"), ("ToString", "omni.graph.nodes.ToString"), ("Const2", "omni.graph.nodes.ConstantDouble"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: [("/World/Sink", {"mydouble": ("double", 0)})], keys.SET_VALUES: [ ("ConstDouble.inputs:value", 2.0), ("Const1.inputs:value", (0.5, 0, 0)), ("Set.inputs:name", "mydouble"), ("Set.inputs:primPath", "/World/Sink"), ("Set.inputs:usePath", True), ], keys.CONNECT: [ ("ConstDouble.inputs:value", "Multiply.inputs:a"), ("Const1.inputs:value", "Multiply.inputs:b"), ("Multiply.outputs:product", "Magnitude.inputs:input"), ("Magnitude.outputs:magnitude", "ToString.inputs:value"), ], }, ) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("inputs:value", to_string_node)) self.assertEqual(v, 1.0) # Disconnect one of the Multiply inputs to cause a wave of unresolutions controller.edit( graph, { keys.DISCONNECT: [ ("ConstDouble.inputs:value", "Multiply.inputs:a"), ("Const1.inputs:value", "Multiply.inputs:b"), ] }, ) # Helper to verify the base data type of an attribute def assert_attrib_is(attrib, node, base_type): attrib = controller.attribute(attrib, node, graph) self.assertEqual(attrib.get_resolved_type().base_type, base_type) # Verify the irresolute quality of the downstream attributes assert_attrib_is("outputs:product", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:input", "Magnitude", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:value", "ToString", og.BaseDataType.UNKNOWN) # Re-connect to observe resolution controller.edit( graph, { keys.CONNECT: [ ("ConstDouble.inputs:value", "Multiply.inputs:a"), ("Const1.inputs:value", "Multiply.inputs:b"), ] }, ) # Verify the resolute quality of the downstream attributes assert_attrib_is("outputs:product", "Multiply", og.BaseDataType.DOUBLE) assert_attrib_is("inputs:input", "Magnitude", og.BaseDataType.DOUBLE) assert_attrib_is("inputs:value", "ToString", og.BaseDataType.DOUBLE) # Disconnect as before controller.edit( graph, { keys.DISCONNECT: [ ("ConstDouble.inputs:value", "Multiply.inputs:a"), ("Const1.inputs:value", "Multiply.inputs:b"), ] }, ) # Wait on the next framework tick, we don't need a full evaluation await omni.kit.app.get_app().next_update_async() # Verify that this time the unresolution was blocked at Magnitude assert_attrib_is("outputs:product", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:a", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:input", "Magnitude", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:value", "ToString", og.BaseDataType.UNKNOWN) # Now check that WritePrimAttribute will cause upstream propagation await controller.evaluate(graph) controller.edit(graph, {keys.CONNECT: [("Magnitude.outputs:magnitude", "Set.inputs:value")]}) await controller.evaluate(graph) # Verify that our network has flipped over to double assert_attrib_is("outputs:magnitude", "Magnitude", og.BaseDataType.DOUBLE) # Note that we no longer propagate resolution upstream from outputs->inputs, so unresolution # remains upstream of Magnitude assert_attrib_is("inputs:input", "Magnitude", og.BaseDataType.UNKNOWN) assert_attrib_is("outputs:product", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:a", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:value", "ToString", og.BaseDataType.DOUBLE) # ---------------------------------------------------------------------- async def test_unresolve_contradiction(self): """Tests unresolve contradiction is handled""" controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ConstVec3f", "omni.graph.nodes.ConstantVec3f"), ("Add", "omni.graph.nodes.Add"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("Add.outputs:sum", "Set.inputs:value"), ], }, ) await omni.kit.app.get_app().next_update_async() event_counter = [0] def on_node_event(event): event_counter[0] += 1 self.assertEqual(event.type, int(og.NodeEvent.ATTRIBUTE_TYPE_RESOLVE)) node = controller.node("Add", graph) sub = node.get_event_stream().create_subscription_to_pop(on_node_event) controller.edit( graph, { keys.CONNECT: [ ("ConstVec3f.inputs:value", "Add.inputs:a"), ("ConstVec3f.inputs:value", "Add.inputs:b"), ] }, ) for _ in range(10): await omni.kit.app.get_app().next_update_async() self.assertLess(event_counter[0], 10) del sub # ---------------------------------------------------------------------- async def test_unresolve_resolve_pingpong(self): """Tests resolve doesn't ping-pong is handled""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, get_node, _), (p_in, p_out), _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Get", "omni.graph.nodes.ReadPrimAttribute"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: [("PIn", {"f": ("float", 1.0)}), ("POut", {"f": ("float", 1.0)})], keys.CONNECT: [ ("OnTick.outputs:tick", "Set.inputs:execIn"), ("Get.outputs:value", "Set.inputs:value"), ], }, ) controller.edit( graph, { keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("Get.inputs:usePath", True), ("Get.inputs:usePath", True), ("Get.inputs:name", "f"), ("Set.inputs:name", "f"), ("Get.inputs:primPath", p_in.GetPrimPath().pathString), ("Set.inputs:primPath", p_out.GetPrimPath().pathString), ], }, ) await omni.kit.app.get_app().next_update_async() event_counter = [0] def on_node_event(event): event_counter[0] += 1 self.assertEqual(event.type, int(og.NodeEvent.ATTRIBUTE_TYPE_RESOLVE)) sub = get_node.get_event_stream().create_subscription_to_pop(on_node_event) for _ in range(5): await omni.kit.app.get_app().next_update_async() self.assertLess(event_counter[0], 5) del sub # ---------------------------------------------------------------------- async def test_loading_extended_attribute_values(self): """Test that saved extended attribute values are de-serialized correctly""" (result, error) = await ogts.load_test_file("TestExtendedAttributes.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph_path = "/World/PushGraph" controller = og.Controller() graph = controller.graph(graph_path) await controller.evaluate(graph) tests = [ # name, og_type, input0, input1 ("make_array", "bool", True, False, None), ("make_array_01", "double", 42, 43, None), ("make_array_02", "token", "FOO", "BAR", None), ("make_array_03", "double[2]", np.array((1.0, 2.0)), np.array((3.0, 4.0)), Gf.Vec2d), ("make_array_04", "int[2]", np.array((1, 2)), np.array((3, 4)), Gf.Vec2i), ("make_array_05", "half", 42.0, 43.0, None), ( "make_array_06", "matrixd[3]", np.array((1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)), np.array((1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)), Gf.Matrix3d, ), ] # verify the values on the loaded nodes for name, og_type, expected_1, expected_2, _ in tests: make_array = controller.node(f"{graph_path}/{name}") input_0 = og.Controller.get(controller.attribute("inputs:input0", make_array)) input_type = controller.attribute("inputs:input0", make_array).get_resolved_type().get_ogn_type_name() input_1 = og.Controller.get(controller.attribute("inputs:input1", make_array)) value = og.Controller.get(controller.attribute("outputs:array", make_array)) self.assertEqual(input_type, og_type) try: self.assertEqual(input_0, expected_1) except ValueError: self.assertListEqual(list(input_0), list(expected_1)) try: self.assertEqual(input_1, expected_2) except ValueError: self.assertListEqual(list(input_1), list(expected_2)) try: self.assertListEqual(list(value), [expected_1, expected_2]) except ValueError: self.assertListEqual([list(v) for v in value], [list(expected_1), list(expected_2)]) usd_context = omni.usd.get_context() stage = usd_context.get_stage() # Reset the arrayType to clear the saved resolved values for name, _, _, _, _ in tests: og.Controller.set(controller.attribute(f"{graph_path}/{name}.inputs:arrayType"), "auto") # Verify that all the inputs are now unresolved for name, _, _, _, _ in tests: make_array = controller.node(f"{graph_path}/{name}") attrib = controller.attribute("inputs:input0", make_array) tp = attrib.get_resolved_type() self.assertEqual(tp.base_type, og.BaseDataType.UNKNOWN) attrib = controller.attribute("inputs:input1", make_array) tp = attrib.get_resolved_type() self.assertEqual(tp.base_type, og.BaseDataType.UNKNOWN) # Verify that in the re-serialized stage, the attrType and attrValue are reset await controller.evaluate(graph) for name, _, _, _, _ in tests: self.assertIsNone( stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1").GetCustomDataByKey( "omni:graph:attrValue" ) ) self.assertEqual( "Any", stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1").GetCustomDataByKey( "omni:graph:attrType" ), ) self.assertIsNone( stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1").GetCustomDataByKey( "omni:graph:resolvedType" ) ) # Re-resolve and set different values for name, og_type, _, input_1, _ in tests: og.Controller.set(controller.attribute(f"{graph_path}/{name}.inputs:arrayType"), f"{og_type}[]") og.Controller.set(controller.attribute(f"{graph_path}/{name}.inputs:input1"), input_1) # Serialize stage again, verify the types and values await controller.evaluate(graph) for name, og_type, _, _, _ in tests: attr = stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1") self.assertIsNotNone(attr.GetCustomDataByKey("omni:graph:attrValue"), f"For {name}") self.assertIsNotNone(attr.GetCustomDataByKey("omni:graph:attrType"), f"For {name}") usd_value = stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1").GetCustomDataByKey( "omni:graph:resolvedType" ) self.assertEqual(og_type, usd_value, f"For {name}") # ---------------------------------------------------------------------- async def test_resolution_invalidates_existing_connection(self): """ Test that when the type resolution makes an existing connection invalid, that we get an error """ controller = og.Controller() keys = og.Controller.Keys (graph, (build_str, find_prims), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("BuildString", "omni.graph.nodes.BuildString"), ("FindPrims", "omni.graph.nodes.FindPrims"), ], keys.CREATE_PRIMS: [("/World/Cube", "Cube"), ("/World/Cone", "Cone")], keys.SET_VALUES: [("FindPrims.inputs:rootPrimPath", "/World")], keys.CONNECT: [("BuildString.outputs:value", "FindPrims.inputs:namePrefix")], }, ) await og.Controller.evaluate(graph) out = find_prims.get_attribute("outputs:prims") self.assertEqual(out.get(), [f"{self.TEST_GRAPH_PATH}", "/World/Cube", "/World/Cone"]) # Setting inputs to string will change resolution on output value to a string as well. But string -> token # connections are not supported. So this should raise an error with ogts.ExpectedError(): controller.edit( self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("BuildString.inputs:a", {"type": "string", "value": "Cu"})]}, ) err_list = build_str.get_compute_messages(og.Severity.ERROR) self.assertEqual(len(err_list), 1) err_list[0].startswith("Type error") await controller.evaluate(graph) out = build_str.get_attribute("outputs:value") self.assertEqual(out.get_resolved_type(), og.Controller.attribute_type("string")) # ---------------------------------------------------------------------- async def test_resolved_type_saved(self): """Test that a type resolution is saved when a value is never set""" # See OM-93596 controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ("ConstantFloat", "omni.graph.nodes.ConstantFloat"), ], keys.SET_VALUES: [ ("Add.inputs:a", {"type": "float", "value": 1.0}), ("ConstantFloat.inputs:value", 42.0), ], }, ) await controller.evaluate(graph) attr = stage.GetAttributeAtPath(f"{self.TEST_GRAPH_PATH}/Add.inputs:a") og_attr = controller.attribute(f"{self.TEST_GRAPH_PATH}/Add.inputs:a") self.assertIsNotNone(attr.GetCustomDataByKey("omni:graph:attrValue")) # Since the controller manually resolves the type above, verify the customData is there usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertEqual("float", usd_value) # manually resolve to a different type - verify it is saved og.cmds.ResolveAttrType(attr=og_attr, type_id="double") await controller.evaluate(graph) usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertEqual("double", usd_value) # manually unresolve - verify the customData is gone og.cmds.ResolveAttrType(attr=og_attr, type_id="unknown") await controller.evaluate(graph) usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertIsNone(usd_value) self.assertEqual(og_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN, 1, 0)) # Verify that: # 1. manually resolving # 2. connect # 3. disconnect # Restores the manual resolution customData AND literal value # FIXME: OM-94077 if False: # noqa PLW0125 og.cmds.ResolveAttrType(attr=og_attr, type_id="float") og.Controller.set(attr, {"type": "float", "value": 2.0}) await controller.evaluate(graph) self.assertEqual(attr.GetCustomDataByKey("omni:graph:attrValue"), 2.0) usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertEqual("float", usd_value) controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: [("ConstantFloat.inputs:value", "Add.inputs:a")]}) await controller.evaluate(graph) self.assertEqual(og_attr.get(), 42.0) controller.edit( self.TEST_GRAPH_PATH, {keys.DISCONNECT: [("ConstantFloat.inputs:value", "Add.inputs:a")]}, ) await controller.evaluate(graph) self.assertEqual(attr.GetCustomDataByKey("omni:graph:attrValue"), 2.0) usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertEqual("float", usd_value) self.assertEqual(og_attr.get(), 2.0) controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: [("Add.outputs:sum", "ConstantFloat.inputs:value")]}) await controller.evaluate(graph) og_sum_attr = controller.attribute(f"{self.TEST_GRAPH_PATH}/Add.outputs:sum") self.assertEqual(og_sum_attr.get_resolved_type(), og.Type(og.BaseDataType.FLOAT, 1, 0)) controller.edit( self.TEST_GRAPH_PATH, {keys.DISCONNECT: [("Add.outputs:sum", "ConstantFloat.inputs:value")]}, ) await controller.evaluate(graph) self.assertEqual(og_sum_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN, 1, 0)) # ---------------------------------------------------------------------- async def test_resolved_types_serialized_in_compounds(self): """Validates that resolved types are serialized in compound graphs (OM-99390)""" controller = og.Controller(update_usd=True) keys = og.Controller.Keys (_, _, _, nodes) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ( "Compound", { keys.CREATE_NODES: [("CompoundAdd", "omni.graph.nodes.Add")], keys.SET_VALUES: [("CompoundAdd.inputs:a", {"type": "float", "value": 2.0})], }, ), ], keys.SET_VALUES: [ ("Add.inputs:a", {"type": "double", "value": 1.0}), ], }, ) add_path = nodes["Add"].get_prim_path() compound_add_path = nodes["CompoundAdd"].get_prim_path() # resolve and set attributes top_level_attr_a = nodes["Add"].get_attribute("inputs:a") top_level_attr_b = nodes["Add"].get_attribute("inputs:b") compound_attr_a = nodes["CompoundAdd"].get_attribute("inputs:a") compound_attr_b = nodes["CompoundAdd"].get_attribute("inputs:b") og.cmds.ResolveAttrType(attr=top_level_attr_b, type_id="double") og.cmds.ResolveAttrType(attr=compound_attr_b, type_id="float") controller.set(top_level_attr_b, 3.0) controller.set(compound_attr_b, 4.0) self.assertEqual(og.Controller.get(top_level_attr_a), 1.0) self.assertEqual(og.Controller.get(compound_attr_a), 2.0) self.assertEqual(og.Controller.get(top_level_attr_b), 3.0) self.assertEqual(og.Controller.get(compound_attr_b), 4.0) # save and reload the scene with tempfile.TemporaryDirectory() as test_directory: tmp_file_path = os.path.join(test_directory, "tmp_test_resolve_in_compounds.usda") (result, error, _) = await omni.usd.get_context().save_as_stage_async(str(tmp_file_path)) self.assertTrue(result, error) (result, error) = await omni.usd.get_context().reopen_stage_async() self.assertTrue(result, error) add_node = og.Controller.node(add_path) compound_add_node = og.Controller.node(compound_add_path) top_level_attr_a = add_node.get_attribute("inputs:a") top_level_attr_b = add_node.get_attribute("inputs:b") compound_attr_a = compound_add_node.get_attribute("inputs:a") compound_attr_b = compound_add_node.get_attribute("inputs:b") self.assertEqual(og.Controller.get(top_level_attr_a), 1.0) self.assertEqual(og.Controller.get(compound_attr_a), 2.0) self.assertEqual(og.Controller.get(top_level_attr_b), 3.0) self.assertEqual(og.Controller.get(compound_attr_b), 4.0)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_graph_settings.py
"""OmniGraph Graph Settings Tests""" import os import tempfile import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.kit.undo import omni.usd import omni.usd.commands from pxr import OmniGraphSchema class TestOmniGraphSchemaGraphSettings(ogts.OmniGraphTestCase): """Tests for OmniGraph Graph Settings with Schema Enabled""" # ---------------------------------------------------------------------- async def test_compute_settings_save_and_load(self): """Tests that creating, saving and loading compute graph settings writes and reads the correct settings""" pipeline_stages = list(og.GraphPipelineStage.__members__.values()) evaluation_modes = list(og.GraphEvaluationMode.__members__.values()) backing_types = [ og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_WITHOUT_HISTORY, og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, ] setting_tuples = zip(pipeline_stages[0:3], evaluation_modes[0:3], backing_types[0:3]) index = 0 for (pipeline_stage, evaluation_mode, backing_type) in setting_tuples: (graph, _, _, _) = og.Controller.edit( { "graph_path": f"/World/TestGraph{index}", "fc_backing_type": backing_type, "pipeline_stage": pipeline_stage, "evaluation_mode": evaluation_mode, } ) path = graph.get_path_to_graph() self.assertIsNotNone(graph) with tempfile.TemporaryDirectory() as tmpdirname: # save the file tmp_file_path = os.path.join(tmpdirname, f"tmp{index}.usda") result = omni.usd.get_context().save_as_stage(tmp_file_path) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload the file back (result, error) = await ogts.load_test_file(tmp_file_path) self.assertTrue(result, error) graph = omni.graph.core.get_graph_by_path(path) self.assertIsNotNone(graph, f"Failed to load graph at {path} from {tmp_file_path}") self.assertEquals(graph.evaluation_mode, evaluation_mode) self.assertEquals(graph.get_pipeline_stage(), pipeline_stage) self.assertEquals(graph.get_graph_backing_type(), backing_type) index = index + 1 await omni.usd.get_context().new_stage_async() # ---------------------------------------------------------------------- async def test_evaluation_mode_changed_from_usd(self): """Tests that changing evaluation mode from usd is applied to the underlying graph""" controller = og.Controller() keys = og.Controller.Keys stage = omni.usd.get_context().get_stage() graph_path = "/World/TestGraph" (graph, nodes, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ] }, ) self.assertEquals(graph.evaluation_mode, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC) # automatic mode, computes because no references exist count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count + 1, nodes[0].get_compute_count()) prim = stage.GetPrimAtPath(graph_path) self.assertTrue(prim.IsA(OmniGraphSchema.OmniGraph)) schema_prim = OmniGraphSchema.OmniGraph(prim) # change the evaluation to instanced schema_prim.GetEvaluationModeAttr().Set("Instanced") count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED, graph.evaluation_mode) self.assertEqual(count, nodes[0].get_compute_count()) # ---------------------------------------------------------------------- async def test_evaluator_type_changed_from_usd(self): """Tests that changing evaluation mode from usd is applied to the underlying graph""" stage = omni.usd.get_context().get_stage() graph_path = "/World/TestGraph" controller = og.Controller() (graph, (read_time, constant_node, _), _, _) = controller.edit( {"graph_path": graph_path, "evaluator_name": "dirty_push"}, { og.Controller.Keys.CREATE_NODES: [ ("ReadTime", "omni.graph.nodes.ReadTime"), ("ConstantInt", "omni.graph.nodes.ConstantInt"), ("Sub", "omni.graph.test.SubtractDoubleC"), ], og.Controller.Keys.CONNECT: [ ("ReadTime.outputs:timeSinceStart", "Sub.inputs:a"), ("ReadTime.outputs:timeSinceStart", "Sub.inputs:b"), ], og.Controller.Keys.SET_VALUES: [("ConstantInt.inputs:value", 3)], }, ) # skip the initial compute await omni.kit.app.get_app().next_update_async() # validate the graph ticks as expected count_time = read_time.get_compute_count() count_print = constant_node.get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count_time + 1, read_time.get_compute_count(), "Expected time to tick") self.assertEqual(count_print, constant_node.get_compute_count(), "Expected print not to tick") prim = stage.GetPrimAtPath(graph_path) self.assertTrue(prim.IsA(OmniGraphSchema.OmniGraph)) schema_prim = OmniGraphSchema.OmniGraph(prim) # change the graph to push by changing the USD. schema_prim.GetEvaluatorTypeAttr().Set("push") await omni.kit.app.get_app().next_update_async() self.assertEqual(graph.get_evaluator_name(), "push") self.assertEqual(count_time + 2, read_time.get_compute_count(), "Expected time to tick") self.assertEqual(count_print + 1, constant_node.get_compute_count(), "Expected print to tick") # change the graph back schema_prim.GetEvaluatorTypeAttr().Set("dirty_push") await omni.kit.app.get_app().next_update_async() # skip the intial frame count_time = read_time.get_compute_count() count_print = constant_node.get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(graph.get_evaluator_name(), "dirty_push") self.assertEqual(count_time + 1, read_time.get_compute_count(), "Expected time to tick") self.assertEqual(count_print, constant_node.get_compute_count(), "Expected print not to tick") # --------------------------------------------------------------------- async def test_fabric_backing_changed_from_usd(self): stage = omni.usd.get_context().get_stage() graph_path = "/World/TestGraph" (graph, _, _, _) = og.Controller.edit( {"graph_path": graph_path, "fc_backing_type": og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED} ) self.assertEqual(og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, graph.get_graph_backing_type()) prim = stage.GetPrimAtPath(graph_path) self.assertTrue(prim.IsA(OmniGraphSchema.OmniGraph)) schema_prim = OmniGraphSchema.OmniGraph(prim) schema_prim.GetFabricCacheBackingAttr().Set("StageWithoutHistory") await omni.kit.app.get_app().next_update_async() self.assertEqual(og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_WITHOUT_HISTORY, graph.get_graph_backing_type()) # --------------------------------------------------------------------- async def test_pipeline_stage_changed_from_usd(self): """Tests the changing the pipeline stage in usd changes the underlying pipeline stage""" controller = og.Controller() keys = og.Controller.Keys stage = omni.usd.get_context().get_stage() graph_path = "/World/TestGraph" (graph, nodes, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ] }, ) self.assertEqual(og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, graph.get_pipeline_stage()) # validate the node updates count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count + 1, nodes[0].get_compute_count()) prim = stage.GetPrimAtPath(graph_path) self.assertTrue(prim.IsA(OmniGraphSchema.OmniGraph)) schema_prim = OmniGraphSchema.OmniGraph(prim) # change the pipeline stage to on demand schema_prim.GetPipelineStageAttr().Set("pipelineStageOnDemand") await omni.kit.app.get_app().next_update_async() self.assertEqual(og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, graph.get_pipeline_stage()) # validate the node did not update count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count, nodes[0].get_compute_count()) # change back to simulation schema_prim.GetPipelineStageAttr().Set("pipelineStageSimulation") await omni.kit.app.get_app().next_update_async() self.assertEqual(og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, graph.get_pipeline_stage()) # validate the node updates count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count + 1, nodes[0].get_compute_count())
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_callbacks.py
""" Tests for omnigraph callbacks """ import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd # Global variable for sharing callback location _callback_path = None # ====================================================================== class TestCallbacks(ogts.OmniGraphTestCase): _graph_path = "/World/TestGraph" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.conn_count = 0 self.disconn_count = 0 self.attr_count = 0 # ---------------------------------------------------------------------- async def test_connection_callbacks(self): """ Test attribute connect/disconnect callbacks. """ # Create the graph. (_, (simple1, simple2), _, _) = og.Controller.edit( self._graph_path, { og.Controller.Keys.CREATE_NODES: [ ("simple1", "omni.graph.tutorials.SimpleData"), ("simple2", "omni.graph.tutorials.SimpleData"), ], }, ) self.conn_count = 0 self.disconn_count = 0 self.attr_count = 0 def on_connection(attr1, attr2): self.conn_count += 1 # Were the correct arguments passed? if (attr1.get_name() == "outputs:a_int") and (attr2.get_name() == "inputs:a_int"): self.attr_count += 1 def on_disconnection(attr1, attr2): self.disconn_count += 1 # Were the correct arguments passed? if (attr1.get_name() == "outputs:a_int") and (attr2.get_name() == "inputs:a_int"): self.attr_count += 1 conn1_cb = simple1.register_on_connected_callback(on_connection) conn2_cb = simple2.register_on_connected_callback(on_connection) disconn1_cb = simple1.register_on_disconnected_callback(on_disconnection) self.assertEqual(self.conn_count, 0) self.assertEqual(self.disconn_count, 0) self.assertEqual(self.attr_count, 0) # Make a connection. We should get calls from both nodes. attr1 = simple1.get_attribute("outputs:a_int") attr2 = simple2.get_attribute("inputs:a_int") attr1.connect(attr2, True) self.assertEqual(self.conn_count, 2) self.assertEqual(self.disconn_count, 0) self.assertEqual(self.attr_count, 2) # Break the connection. We should only get a call from simple1. attr1.disconnect(attr2, True) self.assertEqual(self.conn_count, 2) self.assertEqual(self.disconn_count, 1) self.assertEqual(self.attr_count, 3) # Deregister one of the connection callbacks then make a connection. simple1.deregister_on_connected_callback(conn1_cb) attr1.connect(attr2, True) self.assertEqual(self.conn_count, 3) self.assertEqual(self.disconn_count, 1) self.assertEqual(self.attr_count, 4) # Deregistering the same callback again should have no effect. simple1.deregister_on_connected_callback(conn1_cb) # Cleanup. simple1.deregister_on_connected_callback(conn2_cb) simple1.deregister_on_connected_callback(disconn1_cb) # ---------------------------------------------------------------------- async def test_path_changed_callback(self): """ Test the ability to register callbacks on nodes so that they receive path change notices from USD """ # Create the graph. (graph, (simple_node,), _, _) = og.Controller.edit( self._graph_path, { og.Controller.Keys.CREATE_NODES: [("simple", "omni.graph.tutorials.SimpleData")], }, ) k_want_print = False k_not_received = "not_received" global _callback_path _callback_path = k_not_received def on_path_changed_callback(changed_paths): global _callback_path _callback_path = changed_paths[-1] def _do_the_print(changed_paths, want_print: bool = k_want_print): return print(changed_paths) if k_want_print else None print_changed_paths = _do_the_print async def test_callback(should_work: bool): cb_handle = simple_node.register_on_path_changed_callback(on_path_changed_callback) print_changed_paths_cb_handle = simple_node.register_on_path_changed_callback(print_changed_paths) usd_context = omni.usd.get_context() stage = usd_context.get_stage() stage.DefinePrim("/World/xform1", "Xform") await og.Controller.evaluate(graph) self.assertEqual(_callback_path, "/World/xform1" if should_work else k_not_received) simple_node.deregister_on_path_changed_callback(cb_handle) simple_node.deregister_on_path_changed_callback(print_changed_paths_cb_handle) stage.DefinePrim("/World/xform2", "Xform") # This time we should not receive a callback, so ensure path is unchanged self.assertEqual(_callback_path, "/World/xform1" if should_work else k_not_received) await og.Controller.evaluate(graph) with og.Settings.temporary(og.Settings.ENABLE_PATH_CHANGED_CALLBACK, True): await test_callback(True) _callback_path = k_not_received with og.Settings.temporary(og.Settings.ENABLE_PATH_CHANGED_CALLBACK, False): await test_callback(False) # ---------------------------------------------------------------------- async def test_register_value_changed_callback(self): """Test Attribute.register_value_changed callback""" connected_attr = None def on_value_changed(attr): nonlocal connected_attr connected_attr = attr controller = og.Controller() keys = og.Controller.Keys (_, (test_node_a, test_node_b, test_node_c), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("NodeWithAllTypes1", "omni.graph.test.TestAllDataTypes"), ("NodeWithAllTypes2", "omni.graph.test.TestAllDataTypes"), ("NodeWithAllTypes3", "omni.graph.test.TestAllDataTypes"), ] }, ) test_values = [ ("inputs:a_bool", True), ("inputs:a_double", 42.0), ("inputs:a_float_2", (2.0, 3.0)), ("inputs:a_string", "test"), ] for name, value in test_values: src_attrib = test_node_b.get_attribute(name.replace("inputs:", "outputs:")) attrib = test_node_a.get_attribute(name) attrib.register_value_changed_callback(on_value_changed) # test the callback is hit when an attribute changes value og.Controller.set(attrib, value) self.assertEqual(connected_attr, attrib) # validate it is called on connection connected_attr = None og.Controller.connect(src_attrib, attrib) self.assertEqual(connected_attr, attrib) # validate it is called on disconnection connected_attr = None og.Controller.disconnect(src_attrib, attrib) self.assertEqual(connected_attr, attrib) # reset the callback, verify it is not called connected_attr = None attrib.register_value_changed_callback(None) og.Controller.set(attrib, value) self.assertIsNone(connected_attr) # Now validate it is hit when set with USD instead of OG read_attrib = None got_value = None def on_value_changed_2(_): nonlocal read_attrib nonlocal got_value # check if we have an attribute to read the value from if read_attrib: got_value = og.Controller.get(controller.attribute(read_attrib, test_node_c)) usd_context = omni.usd.get_context() stage = usd_context.get_stage() for name, value in test_values: attrib_c = test_node_c.get_attribute(name) attrib_c.register_value_changed_callback(on_value_changed_2) read_attrib = name got_value = None usd_attrib = stage.GetAttributeAtPath(attrib_c.get_path()) usd_attrib.Set(value) if isinstance(got_value, np.ndarray): self.assertSequenceEqual(got_value.tolist(), value) else: self.assertEqual(got_value, value) attrib_c.register_value_changed_callback(None) # Verify callbacks are _not_ sent when disableInfoNoticeHandlingInPlayback=true with og.Settings.temporary(og.Settings.DISABLE_INFO_NOTICE_HANDLING_IN_PLAYBACK, True): for name, value in test_values: attrib_c = test_node_c.get_attribute(name) attrib_c.register_value_changed_callback(on_value_changed_2) read_attrib = name got_value = None usd_attrib = stage.GetAttributeAtPath(attrib_c.get_path()) usd_attrib.Set(value) self.assertEqual(got_value, None) attrib_c.register_value_changed_callback(None)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_data_model.py
"""Tests OG Data Model""" import omni.graph.core.tests as ogts import omni.kit.test import omni.usd # ====================================================================== class TestDataModel(ogts.OmniGraphTestCase): """ Run tests that exercises the data model features of omni graph, such as copy on write and data stealing. """ async def test_copy_on_write(self): """ Test all basic CoW behaviors: - Bundle passthrough is passing a reference to original bundle - Bundle mutation trigger CoW, but array attribute in the new bundle are references - Array attribute mutation in bundle trigger CoW on the attribute - Array attribute on node can be passed by ref, and mutation triggers CoW behavior Load the test scene which has 3 OgnTestDataModel nodes that performs some checks Node #1: - receives a passthrough bundle and the original one, and makes sure those are the same (not equal, the actual same in RAM) - mutate the "points" attribute in its output bundle - receives an array attribute and pass it through unchanged Node #2: - compare the original bundle to the output of node #1, makes sure it is a copy - Checks that all array attribute are actually pointing to the same buffer than the original one, BUT "points", that has been mutated by #1 - validate that the received array attribute is actually pointing to the original one - mutate it on its output Node #3: - validate that the array attribute out of node #2 is a new copy """ (result, error) = await ogts.load_test_file("TestCoW.usda", use_caller_subdirectory=True) self.assertTrue(result, error) # run the graph 2 more times to exercise DB caching await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async()
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_scriptnode.py
"""Basic tests of the action graph""" import omni.graph.core as og import omni.graph.core.tests as ogts # ====================================================================== class TestActionGraphIntegration(ogts.OmniGraphTestCase): """Tests for Script Node""" # ---------------------------------------------------------------------- async def test_compute_creates_dynamic_attrib_legacy(self): """Test that the script node can create dynamic attribs within its compute""" controller = og.Controller() keys = og.Controller.Keys script = """ attribute_exists = db.node.get_attribute_exists("inputs:multiplier") if attribute_exists != True: db.node.create_attribute("inputs:multiplier", og.Type(og.BaseDataType.DOUBLE)) db.outputs.data = db.inputs.data * db.inputs.multiplier""" (graph, (on_impulse_node, script_node), _, _,) = controller.edit( {"graph_path": "/TestGraph", "evaluator_name": "execution"}, { keys.CREATE_NODES: [ ("OnImpulse", "omni.graph.action.OnImpulseEvent"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.CONNECT: ("OnImpulse.outputs:execOut", "Script.inputs:execIn"), keys.SET_VALUES: [ ("OnImpulse.inputs:onlyPlayback", False), ("Script.inputs:script", script), ], }, ) script_node.create_attribute( "inputs:data", og.Type(og.BaseDataType.DOUBLE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ) script_node.create_attribute( "outputs:data", og.Type(og.BaseDataType.DOUBLE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:data", 42), ("Script.outputs:data", 0), ], }, ) await controller.evaluate(graph) # trigger graph evaluation once so the compute runs og.Controller.set(controller.attribute("state:enableImpulse", on_impulse_node), True) await controller.evaluate(graph) val = og.Controller.get(controller.attribute("outputs:data", script_node)) self.assertEqual(val, 0) # set value on the dynamic attrib and check compute og.Controller.set(controller.attribute("inputs:multiplier", script_node), 2.0) og.Controller.set(controller.attribute("state:enableImpulse", on_impulse_node), True) await controller.evaluate(graph) val = og.Controller.get(controller.attribute("outputs:data", script_node)) self.assertEqual(val, 84) # ---------------------------------------------------------------------- async def test_use_loaded_dynamic_attrib(self): """Test that the script node can use a dynamic attrib loaded from USD""" await ogts.load_test_file("TestScriptNode.usda", use_caller_subdirectory=True) controller = og.Controller() val = og.Controller.get(controller.attribute("outputs:data", "/World/ActionGraph/script_node")) self.assertEqual(val, 0) # trigger graph evaluation once so the compute runs og.Controller.set(controller.attribute("state:enableImpulse", "/World/ActionGraph/on_impulse_event"), True) await controller.evaluate() val = og.Controller.get(controller.attribute("outputs:data", "/World/ActionGraph/script_node")) self.assertEqual(val, 84) as_int = og.Controller.get(controller.attribute("outputs:asInt", "/World/ActionGraph/script_node")) as_float = og.Controller.get(controller.attribute("state:asFloat", "/World/ActionGraph/script_node")) self.assertEqual(as_int, 84) self.assertEqual(as_float, 84.0) # ---------------------------------------------------------------------- async def test_simple_scripts_legacy(self): """Test that some simple scripts work as intended""" controller = og.Controller() keys = og.Controller.Keys (graph, (script_node,), _, _,) = controller.edit( "/TestGraph", { keys.CREATE_NODES: ("Script", "omni.graph.scriptnode.ScriptNode"), }, ) script_node.create_attribute( "inputs:my_input_attribute", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ) script_node.create_attribute( "outputs:my_output_attribute", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) output_controller = og.Controller(og.Controller.attribute("outputs:my_output_attribute", script_node)) controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", "db.outputs.my_output_attribute = 123"), }, ) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 123) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:script", "db.outputs.my_output_attribute = -db.inputs.my_input_attribute"), ("Script.inputs:my_input_attribute", 1234), ] }, ) await controller.evaluate(graph) self.assertEqual(output_controller.get(), -1234) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ( "Script.inputs:script", "db.outputs.my_output_attribute = db.inputs.my_input_attribute * db.inputs.my_input_attribute", ), ("Script.inputs:my_input_attribute", -12), ] }, ) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 144) # ---------------------------------------------------------------------- async def test_internal_state_keeps_persistent_info_legacy(self): """Test that the script node can keep persistent information using internal state""" script = """ if (not hasattr(db.internal_state, 'num1')): db.internal_state.num1 = 0 db.internal_state.num2 = 1 else: sum = db.internal_state.num1 + db.internal_state.num2 db.internal_state.num1 = db.internal_state.num2 db.internal_state.num2 = sum db.outputs.data = db.internal_state.num1""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, script_node), _, _,) = controller.edit( {"graph_path": "/TestGraph", "evaluator_name": "execution"}, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.CONNECT: ("OnTick.outputs:tick", "Script.inputs:execIn"), keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("Script.inputs:script", script), ], }, ) script_node.create_attribute( "outputs:data", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) output_controller = og.Controller(og.Controller.attribute("outputs:data", script_node)) # Check that the script node produces the Fibonacci numbers await controller.evaluate(graph) self.assertEqual(output_controller.get(), 0) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 1) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 1) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 2) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 3) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 5) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 8) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 13) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 21) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 34) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 55) # ---------------------------------------------------------------------- async def test_script_global_scope(self): """Test that variables, functions, and classes defined outside of the user-defined callbacks are visible""" controller = og.Controller() keys = og.Controller.Keys (graph, (script_node,), _, _,) = controller.edit( "/TestGraph", { keys.CREATE_NODES: ("Script", "omni.graph.scriptnode.ScriptNode"), }, ) script_node.create_attribute( "outputs:output_a", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) script_node.create_attribute( "outputs:output_b", og.Type(og.BaseDataType.TOKEN), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) output_a_controller = og.Controller(og.Controller.attribute("outputs:output_a", script_node)) output_b_controller = og.Controller(og.Controller.attribute("outputs:output_b", script_node)) script_test_constants = """ MY_CONSTANT_A = 123 MY_CONSTANT_B = 'foo' def setup(db): db.outputs.output_a = MY_CONSTANT_A def compute(db): db.outputs.output_b = MY_CONSTANT_B""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_constants), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 123) self.assertEqual(output_b_controller.get(), "foo") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "foo") script_test_variables = """ my_variable = 123 def setup(db): global my_variable my_variable = 234 db.outputs.output_a = my_variable def compute(db): global my_variable db.outputs.output_b = f'{my_variable}' my_variable += 1""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_variables), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 234) self.assertEqual(output_b_controller.get(), "234") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "235") script_test_functions = """ def my_function_a(): return 123 my_variable_b = 'foo' def my_function_b(): return my_variable_b def setup(db): db.outputs.output_a = my_function_a() def compute(db): db.outputs.output_b = my_function_b() global my_variable_b my_variable_b = 'bar'""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_functions), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 123) self.assertEqual(output_b_controller.get(), "foo") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "bar") script_test_imports = """ import inspect import math my_lambda = lambda x: x code_len = len(inspect.getsource(my_lambda)) def setup(db): db.outputs.output_a = code_len def compute(db): db.outputs.output_b = f'{math.pi:.2f}'""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_imports), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 24) self.assertEqual(output_b_controller.get(), "3.14") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "3.14") script_test_classes = """ class MyClass: def __init__(self, value): self.value = value def get_value(self): return self.value @staticmethod def get_num(): return 123 my_variable = MyClass('foo') def setup(db): db.outputs.output_a = MyClass.get_num() def compute(db): db.outputs.output_b = my_variable.get_value() my_variable.value = 'bar'""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_classes), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 123) self.assertEqual(output_b_controller.get(), "foo") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "bar")
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_helpers.py
"""Tests related to the helper scripts""" import json import re from contextlib import suppress from pathlib import Path from typing import Dict, Optional, Union import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn import omni.kit import omni.usd from omni.graph.core.typing import NodeType_t from pxr import Sdf, Usd # ============================================================================================================== # Iteration helpers GRAPH_BY_GRAPH = "og.Graph" GRAPH_BY_PATH = "path" GRAPH_BY_SDF_PATH = "Sdf path" GRAPH_NONE = "None" GRAPH_LOOKUPS = [GRAPH_BY_GRAPH, GRAPH_BY_PATH, GRAPH_BY_SDF_PATH, GRAPH_NONE] NODE_BY_NODE = "og.Node" NODE_BY_PATH = "path" NODE_BY_USD_PRIM = "Usd.Prim" NODE_NONE = "None" NODE_BY_TUPLE = "tuple" NODE_LOOKUPS = [NODE_BY_NODE, NODE_BY_PATH, NODE_BY_USD_PRIM, NODE_NONE, NODE_BY_TUPLE] NODE_TYPE_BY_NODE = "og.Node" NODE_TYPE_BY_USD_PRIM = "Usd.Prim" NODE_TYPE_BY_NAME = "name" NODE_TYPE_BY_NODE_TYPE = "og.NodeType" NODE_TYPE_LOOKUPS = [NODE_TYPE_BY_NODE, NODE_TYPE_BY_NAME, NODE_TYPE_BY_USD_PRIM, NODE_TYPE_BY_NODE_TYPE] ATTRIBUTE_BY_ATTRIBUTE = "og.Attribute" ATTRIBUTE_BY_PATH = "path" ATTRIBUTE_BY_SDF_PATH = "Sdf.Path" ATTRIBUTE_BY_USD_ATTRIBUTE = "Usd.Attribute" ATTRIBUTE_BY_TUPLE = "tuple" ATTRIBUTE_LOOKUPS = [ ATTRIBUTE_BY_ATTRIBUTE, ATTRIBUTE_BY_PATH, ATTRIBUTE_BY_SDF_PATH, ATTRIBUTE_BY_USD_ATTRIBUTE, ATTRIBUTE_BY_TUPLE, ] # ============================================================================================================== class TestHelpers(ogts.OmniGraphTestCase): """Testing to ensure OGN helpers work""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.outer_graph1_path = None self.outer_graph2_path = None self.inner_graph1_1_path = None self.inner_graph1_2_path = None self.inner_graph2_1_path = None self.inner_graph2_2_path = None self.graph_paths = None self.node1_path = None self.node2_path = None self.node3_path = None self.node4_path = None self.node5_path = None self.node1_1_path = None self.node1_2_path = None self.node2_1_path = None self.node2_2_path = None self.node_paths = None self.attribute1_path = None self.attribute2_path = None self.attribute1_1_path = None self.attribute1_2_path = None self.attribute2_1_path = None self.attribute2_2_path = None self.attribute1_target_input_path = None self.attribute1_target_output_path = None self.attribute1_bundle_input_path = None self.attribute_paths = None self.variable_bool_name = None self.variable_float_name = None self.variable_double_name = None self.variable_names = None # -------------------------------------------------------------------------------------------------------------- async def __populate_data(self): """ Read in the test file and populate the local variables to use for testing. Note that this test file has graph prims whose parents are other graph prims, i.e., the old subgraphs. While these are no longer supported (will not evaluate), we still keep this test file as-is in to ensure that the helper scripts continue to operate correctly even in situations that, while technically authorable, are no longer officially supported in OG. """ (result, error) = await ogts.load_test_file("TestObjectIdentification.usda", use_caller_subdirectory=True) self.assertTrue(result, error) self.outer_graph1_path = "/World/OuterGraph1" self.outer_graph2_path = "/World/OuterGraph2" self.inner_graph1_1_path = f"{self.outer_graph1_path}/InnerGraph1" self.inner_graph1_2_path = f"{self.outer_graph1_path}/InnerGraph2" self.inner_graph2_1_path = f"{self.outer_graph2_path}/InnerGraph1" self.inner_graph2_2_path = f"{self.outer_graph2_path}/InnerGraph2" self.graph_paths = [ self.outer_graph1_path, self.outer_graph2_path, self.inner_graph1_1_path, self.inner_graph1_2_path, self.inner_graph2_1_path, self.inner_graph2_2_path, ] self.node1_path = f"{self.outer_graph1_path}/constant_bool" self.node2_path = f"{self.outer_graph2_path}/constant_double" self.node3_path = f"{self.outer_graph1_path}/constant_prims" self.node4_path = f"{self.outer_graph1_path}/get_prims_at_path" self.node5_path = f"{self.outer_graph1_path}/extract_bundle" self.node1_1_path = f"{self.inner_graph1_1_path}/constant_float" self.node1_2_path = f"{self.inner_graph1_2_path}/constant_int" self.node2_1_path = f"{self.inner_graph2_1_path}/constant_uint" self.node2_2_path = f"{self.inner_graph2_2_path}/constant_uint64" self.node_paths = [ self.node1_path, self.node2_path, self.node3_path, self.node4_path, self.node5_path, self.node1_1_path, self.node1_2_path, self.node2_1_path, self.node2_2_path, ] self.attribute1_path = f"{self.node1_path}.inputs:value" self.attribute2_path = f"{self.node2_path}.inputs:value" self.attribute1_1_path = f"{self.node1_1_path}.inputs:value" self.attribute1_2_path = f"{self.node1_2_path}.inputs:value" self.attribute2_1_path = f"{self.node2_1_path}.inputs:value" self.attribute2_2_path = f"{self.node2_2_path}.inputs:value" # additional attributes of relationship types self.attribute1_target_input_path = f"{self.node3_path}.inputs:value" self.attribute1_target_output_path = f"{self.node4_path}.outputs:prims" self.attribute1_bundle_input_path = f"{self.node5_path}.inputs:bundle" self.attribute_paths = [ self.attribute1_path, self.attribute2_path, self.attribute1_1_path, self.attribute1_2_path, self.attribute2_1_path, self.attribute2_2_path, self.attribute1_target_input_path, self.attribute1_target_output_path, self.attribute1_bundle_input_path, ] self.variable_bool_name = "variable_bool" self.variable_float_name = "variable_float" self.variable_double_name = "variable_double" self.variable_names = [ self.variable_bool_name, self.variable_float_name, self.variable_double_name, ] # -------------------------------------------------------------------------------------------------------------- @staticmethod def __graph_id_from_path(graph_path: str, lookup_type: str) -> Union[str, Sdf.Path, og.Graph, None]: """Return a typed graph lookup value based on the lookup requested""" if lookup_type == GRAPH_BY_GRAPH: return og.get_graph_by_path(graph_path) if lookup_type == GRAPH_BY_PATH: return graph_path if lookup_type == GRAPH_BY_SDF_PATH: return Sdf.Path(graph_path) return None # -------------------------------------------------------------------------------------------------------------- @staticmethod def __node_id_from_path(node_path: str, lookup_type: str) -> Union[str, Usd.Prim, og.Node, None]: """Return a typed node lookup value based on the lookup requested""" if lookup_type == NODE_BY_NODE: return og.get_node_by_path(node_path) if lookup_type == NODE_BY_PATH: return node_path if lookup_type == NODE_BY_USD_PRIM: return omni.usd.get_context().get_stage().GetPrimAtPath(node_path) return None # -------------------------------------------------------------------------------------------------------------- @staticmethod def __node_type_id_from_info(type_name: str, node_type: og.NodeType, node: og.Node, lookup_type: str) -> NodeType_t: """Return a typed node type lookup value based on the lookup requested""" if lookup_type == NODE_TYPE_BY_NODE: return node if lookup_type == NODE_TYPE_BY_NODE_TYPE: return node_type if lookup_type == NODE_TYPE_BY_NAME: return og.get_node_type(type_name).get_node_type() if lookup_type == NODE_TYPE_BY_USD_PRIM: return omni.usd.get_context().get_stage().GetPrimAtPath(node.get_prim_path()) return None # -------------------------------------------------------------------------------------------------------------- @staticmethod def __attribute_id_from_path( attribute_path: str, attribute_type: str, node: Optional[og.Node] = None ) -> Union[str, Usd.Attribute, og.Attribute, None]: """Return a typed attribute lookup value based on the lookup requested. Args: attribute_path: Absolute (if node is None) or relative (if node is not None) path to attribute attribute_type: ID type to return that represents the attribute node: Optional node to which the attribute belongs Returns: ID type requested that corresponds to the attribute that was found Raises: og.OmniGraphError if the attribute configuration information does not provide a unique lookup location """ (node_path, attribute_relative_path) = attribute_path.split(".") if not attribute_relative_path: # No separator means the path is a relative attribute path and the node must be specified, and contain # the attribute passed in. if node is None: raise og.OmniGraphError(f"Relative attribute path {attribute_path} requires a node to resolve") attribute_relative_path = node_path node_path = node.get_prim_path() else: node_lookup = og.get_node_by_path(node_path) try: node_lookup_handle = node_lookup.get_handle() if node_lookup is not None else None except AttributeError as error: raise og.OmniGraphError( f"Node extracted from attribute path '{attribute_path}' was not a valid og.Node" ) from error # If a node was specified, and was also a part of the attribute path, make sure they match if node is not None: try: node_handle = node.get_handle() except AttributeError as error: raise og.OmniGraphError(f"Node description passed in ({node}) was not a valid og.Node") from error if node_lookup is None or node_handle != node_lookup_handle: raise og.OmniGraphError( f"Node extracted from attribute path '{attribute_path}' " "did not match the node passed in {node.get_prim_path()}" ) else: node = node_lookup if attribute_type == ATTRIBUTE_BY_ATTRIBUTE: if not node.get_attribute_exists(attribute_relative_path): raise og.OmniGraphError(f"No attribute {attribute_relative_path} exists on node {node.get_prim_path()}") return node.get_attribute(attribute_relative_path) if attribute_type == ATTRIBUTE_BY_PATH: return f"{node_path}.{attribute_relative_path}" if attribute_type == ATTRIBUTE_BY_SDF_PATH: return Sdf.Path(f"{node_path}.{attribute_relative_path}") if attribute_type == ATTRIBUTE_BY_USD_ATTRIBUTE: return ( omni.usd.get_context().get_stage().GetPropertyAtPath(Sdf.Path(f"{node_path}.{attribute_relative_path}")) ) return None # -------------------------------------------------------------------------------------------------------------- def __test_graph_lookup(self, graphs: Dict[str, og.Graph]): """Run the test on this method that looks up a graph from identifying information. def graph(cls, graph_id: GraphSpecs_t) -> Union[og.Graph, List[og.Graph]]: Args: graphs: Dictionary of path:graph for expected graphs being looked up """ # Test graph lookup for path, graph in graphs.items(): for lookup in GRAPH_LOOKUPS: graph_lookup = og.ObjectLookup.graph(self.__graph_id_from_path(path, lookup)) lookup_msg = f"Looking up graph {path} by {lookup}" if lookup == GRAPH_NONE: self.assertIsNone(graph_lookup, lookup_msg) else: self.assertIsNotNone(graph_lookup, lookup_msg) self.assertEqual(graph.get_handle(), graph_lookup.get_handle(), lookup_msg) # Test list of graph lookup graph_paths = list(graphs.keys()) all_graphs = og.ObjectLookup.graph(graph_paths) for index, path in enumerate(graph_paths): graph_lookup = all_graphs[index] self.assertIsNotNone(graph_lookup, f"List-based lookup of graph {path}") self.assertEqual( graph_lookup.get_handle(), graphs[path].get_handle(), f"Lookup graph by list, item {index} = {path}" ) # Test failing graph lookups self.assertIsNone(og.ObjectLookup.graph(None), "Looking up None graph") self.assertIsNone(og.ObjectLookup.graph("/NoGraph"), "Looking up unknown graph path") self.assertIsNone(og.ObjectLookup.graph(self.node1_path), "Looking up non-graph path") self.assertIsNone(og.ObjectLookup.graph(Sdf.Path("/NoGraph")), "Looking up unknown graph path") self.assertIsNone(og.ObjectLookup.graph(Sdf.Path(self.node1_path)), "Looking up non-graph Sdf path") # -------------------------------------------------------------------------------------------------------------- def __test_node_lookup(self, nodes: Dict[str, og.Node]): """Run the set of tests to look up nodes from identifying information using these API functions. def node(cls, node_id: NodeSpecs_t, graph: GraphSpec_t = None) -> Union[og.Node, List[og.Node]]: def prim(cls, node_id: NodeSpecs_t, graph: GraphSpec_t = None) -> Union[Usd.Prim, List[Usd.Prim]]: def node_path(cls, node_id: NodeSpecs_t, graph: GraphSpec_t = None) -> Union[str, List[str]]: Args: nodes: Dictionary of path:node for expected nodes being looked up """ # Test various node lookups for graph_lookup_type in GRAPH_LOOKUPS: for path, node in nodes.items(): graph_path = node.get_graph().get_path_to_graph() graph_id = self.__graph_id_from_path(graph_path, graph_lookup_type) for lookup in NODE_LOOKUPS: # Looking up a node without a node identifier is not possible if lookup == NODE_NONE: continue # If a node spec requires a graph and there isn't one then skip it (it will be tested below) if lookup in [NODE_BY_PATH, NODE_BY_TUPLE] and graph_id is None: continue if lookup == NODE_BY_TUPLE: (graph, node_path) = og.ObjectLookup.split_graph_from_node_path(path) node_lookup = og.ObjectLookup.node((node_path, graph)) else: node_id = self.__node_id_from_path(path, lookup) node_lookup = og.ObjectLookup.node(node_id, graph_id) lookup_msg = ( f"Looking up node {path} by {lookup} in graph {graph_path} found by {graph_lookup_type}" ) if lookup == NODE_NONE: self.assertIsNone(node_lookup, lookup_msg) else: self.assertIsNotNone(node_lookup, lookup_msg) self.assertEqual(node.get_handle(), node_lookup.get_handle(), lookup_msg) if graph_lookup_type == GRAPH_NONE: prim_lookup = og.ObjectLookup.prim(node_id) if lookup == NODE_NONE: self.assertIsNone(prim_lookup, lookup_msg) else: self.assertIsNotNone(prim_lookup, lookup_msg) self.assertEqual(node.get_prim_path(), prim_lookup.GetPrimPath(), lookup_msg) node_path_lookup = og.ObjectLookup.node_path(node_id) if lookup == NODE_NONE: self.assertIsNone(node_path_lookup, lookup_msg) else: self.assertIsNotNone(node_path_lookup, lookup_msg) self.assertEqual(node.get_prim_path(), node_path_lookup, lookup_msg) # Test list of node lookups node_paths = list(nodes.keys()) all_nodes = og.ObjectLookup.node(node_paths) for index, path in enumerate(node_paths): node_lookup = all_nodes[index] self.assertIsNotNone(node_lookup, f"List-based lookup of node {path}") self.assertEqual( node_lookup.get_handle(), nodes[path].get_handle(), f"Lookup by node, item {index} = {path}" ) # Test failing node lookups with self.assertRaises(og.OmniGraphValueError): og.ObjectLookup.node(None) for parameters in [ ["/NoNode"], # Non-existent path [self.inner_graph2_1_path], # Non-node path [self.node1_path, og.ObjectLookup.graph(self.outer_graph2_path)], # Mismatched graph ]: with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node(*parameters) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.prim("/NotAPrim") # -------------------------------------------------------------------------------------------------------------- def __test_node_type_lookup(self, nodes: Dict[str, og.Node]): """Run the set of tests to look up node types from identifying information using this API. def node_type(cls, type_id: NodeTypes_t) -> Union[og.NodeType, List[og.NodeType]]: Args: nodes: Dictionary of path:node for expected nodes being looked up """ node_types = [(node.get_node_type().get_node_type(), node.get_node_type(), node) for node in nodes.values()] for name, expected_node_type, node in node_types: self.assertTrue(expected_node_type.is_valid(), f"Checking lookup of node type {name}") for lookup in NODE_TYPE_LOOKUPS: lookup_msg = f"Looking up node type {name} by {lookup}" node_type_lookup = og.ObjectLookup.node_type( self.__node_type_id_from_info(name, expected_node_type, node, lookup) ) self.assertIsNotNone(node_type_lookup, lookup_msg) self.assertTrue(node_type_lookup, lookup_msg) # Test list of node type lookups all_lookups = [name for name, _, _ in node_types] all_lookups += [node_type for _, node_type, _ in node_types] all_lookups += [node for _, _, node in node_types] all_lookups += [og.ObjectLookup.prim(node) for _, _, node in node_types] all_node_types = og.ObjectLookup.node_type(all_lookups) node_type_count = len(node_types) for index, (_, node_type, _) in enumerate(node_types): msg = f"Lookup of {all_lookups[index]} by" self.assertEqual(all_node_types[index], node_type, f"{msg} name") self.assertEqual(all_node_types[index + node_type_count], node_type, f"{msg} node type") self.assertEqual(all_node_types[index + node_type_count * 2], node_type, f"{msg} node") self.assertEqual(all_node_types[index + node_type_count * 3], node_type, f"{msg} prim") # Test failing node type lookups with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node_type(None) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node_type("omni.this.type.is.invalid") with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node_type(og.get_node_by_path("/This/Is/Not/A/Node")) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node_type(og.get_node_type("omni.this.type.is.invalid")) # -------------------------------------------------------------------------------------------------------------- def __test_variable_lookup(self): """Run the set of tests for running variable lookup from identifying information def variable(cls, variable_id: Variables_t) -> Union[og.IVariable, List[og.IVariable]]: """ graph_with_variables = og.ObjectLookup.graph(self.outer_graph1_path) graph_without_variables = og.ObjectLookup.graph(self.outer_graph2_path) variables = [graph_with_variables.find_variable(x) for x in self.variable_names] variable_tuples = [(graph_with_variables, x) for x in self.variable_names] # Test lookup of variable types for v in variables: self.assertTrue(bool(v)) self.assertEquals(v, og.ObjectLookup.variable(v)) self.assertEquals(v, og.ObjectLookup.variable((graph_with_variables, v.name))) self.assertEquals(v, og.ObjectLookup.variable(v.source_path)) self.assertEquals(v, og.ObjectLookup.variable(Sdf.Path(v.source_path))) # Test lookup with wrong graph with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable((graph_without_variables, v.name)) # Test lookup with wrong name with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable((graph_with_variables, "Variable4")) # Test list lookup self.assertEquals(variables, og.ObjectLookup.variable(variables)) self.assertEquals(variables, og.ObjectLookup.variable(variable_tuples)) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable(None) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable("Invalid string") with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable([variables[0], "Invalid Entry"]) # -------------------------------------------------------------------------------------------------------------- def __test_attribute_lookup(self): """Run the set of tests to look up attributes from identifying information using this API. def attribute(cls, attribute_id: AttributeSpecs_t, node: NodeSpec_t = None, graph: GraphSpec_t = None) -> Union[og.Attribute, List[og.Attribute]]: def usd_attribute(cls, attribute_id: AttributeSpecs_t) -> Union[Usd.Attribute, List[Usd.Attribute]]: """ # Dictionary mapping the attribute path as a string to the actual attribute attributes = { attribute_path: self.__attribute_id_from_path(attribute_path, ATTRIBUTE_BY_ATTRIBUTE) for attribute_path in self.attribute_paths } # Dictionary mapping the attribute path as a string to the corresponding Usd.Attribute stage = omni.usd.get_context().get_stage() usd_attributes = { attribute_path: stage.GetPropertyAtPath(attribute_path) for attribute_path in self.attribute_paths } # Test various attribute lookups for graph_lookup_type in GRAPH_LOOKUPS: # noqa: PLR1702 for node_lookup_type in NODE_LOOKUPS: for path, attribute in attributes.items(): graph_path = attribute.get_node().get_graph().get_path_to_graph() graph_lookup_msg = f"graph {graph_path} found by {graph_lookup_type}" graph_lookup = self.__graph_id_from_path(graph_path, graph_lookup_type) node_path = attribute.get_node().get_prim_path() node_lookup_msg = f"in node {node_path} found by {node_lookup_type}" node_lookup = self.__node_id_from_path(node_path, node_lookup_type) for lookup in ATTRIBUTE_LOOKUPS: try: node = og.ObjectLookup.node(node_lookup) except og.OmniGraphValueError: node = None if lookup == ATTRIBUTE_BY_TUPLE: # The tuple lookup only works with valid nodes if node is None: continue attribute_lookup = og.ObjectLookup.attribute((attribute.get_name(), node)) usd_property_lookup = og.ObjectLookup.usd_property((attribute.get_name(), node)) else: attribute_id = self.__attribute_id_from_path(path, lookup, node) attribute_lookup = og.ObjectLookup.attribute(attribute_id, node_lookup, graph_lookup) if node_lookup is None and graph_lookup is None: usd_property_lookup = og.ObjectLookup.usd_property(attribute_id) else: # We have to catch the case of the lookup being None so use a different value to # flag the fact that this combination doesn't require testing of Usd.Attribute lookup usd_property_lookup = "" lookup_msg = f"Looking up attribute {path} by {lookup} {node_lookup_msg} {graph_lookup_msg}" self.assertIsNotNone(usd_property_lookup, lookup_msg) self.assertEqual(attribute.get_handle(), attribute_lookup.get_handle(), lookup_msg) lookup_msg = lookup_msg.replace("attribute", "Usd.Attribute") usd_attribute = usd_attributes[path] self.assertIsNotNone(attribute_lookup, lookup_msg) if usd_property_lookup != "": self.assertEqual(usd_attribute.GetPath(), usd_property_lookup.GetPath(), lookup_msg) # Test list of attribute lookups attribute_paths = list(attributes.keys()) all_attributes = og.ObjectLookup.attribute(attribute_paths) for index, path in enumerate(attribute_paths): attribute_lookup = all_attributes[index] self.assertIsNotNone(attribute_lookup, f"List-based lookup of attribute {path}") self.assertEqual( attribute_lookup.get_handle(), attributes[path].get_handle(), f"Lookup by attribute, item {index} = {path}", ) # Test failing attribute lookups with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(None) # None is illegal with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(f"{self.node1_path}.FooBar") # Non-existent attribute on legal node with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(self.inner_graph2_1_path) # Non-attribute path with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(self.attribute1_path, self.node1_1_path) # Mismatched node with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(None) # None is illegal with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(f"{self.node1_path}.FooBar") # Non-existent attribute on legal node with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(self.inner_graph2_1_path) # Non-attribute path with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute((self.attribute1_path, self.node1_1_path)) # Mismatched node # -------------------------------------------------------------------------------------------------------------- async def test_object_identification(self): """Test operation of the utility class that identifies nodes, attributes, and graphs from a variety of inputs. This is the structure of the relevant parts of the test file: def Xform "World" def OmniGraph "OuterGraph1" custom bool graph:variable:var_bool def OmniGraph "InnerGraph1" def OmniGraphNode "constant_float" custom float inputs:value def OmniGraph "InnerGraph2" def OmniGraphNode "constant_int" custom int inputs:value def OmniGraphNode "constant_bool" custom bool inputs:value def OmniGraph "OuterGraph2" def OmniGraphNode "constant_double" custom double inputs:value def ComputeGraph "InnerGraph1" def OmniGraphNode "constant_uint" custom uint inputs:value def ComputeGraph "InnerGraph2" def OmniGraphNode "constant_uint64" custom uint64 inputs:value """ await self.__populate_data() # Dictionary mapping the graph path as a string to the actual graph graphs = {graph_path: self.__graph_id_from_path(graph_path, GRAPH_BY_GRAPH) for graph_path in self.graph_paths} # Make sure all of the expected graphs from the file were found for path, graph in graphs.items(): self.assertIsNotNone(graph, f"Graph at {path}") # Dictionary mapping the node path as a string to the actual node nodes = {node_path: self.__node_id_from_path(node_path, NODE_BY_NODE) for node_path in self.node_paths} # Make sure all of the excpected node paths from the file were found for path, node in nodes.items(): self.assertIsNotNone(node, f"Node at {path}") # Make sure the nodes belong to their expected graph nodes_graph = {node: node.get_graph() for node in nodes.values()} for node, graph in nodes_graph.items(): self.assertIsNotNone(graph, f"Graph of node {node.get_prim_path()}") node_lookup = graph.get_node(node.get_prim_path()) self.assertIsNotNone(node_lookup, f"Lookup in graph of node {node.get_prim_path()}") self.assertEqual(node.get_handle(), node_lookup.get_handle(), f"Node {node.get_prim_path()} matches lookup") self.__test_graph_lookup(graphs) self.__test_node_lookup(nodes) self.__test_attribute_lookup() self.__test_node_type_lookup(nodes) self.__test_variable_lookup() # -------------------------------------------------------------------------------------------------------------- async def test_attribute_type_identification(self): """The attribute type ID does not rely on file contents so it can be tested in isolation.""" # AttributeType_t = Union[str, og.Type] # def attribute_type(cls, type_id: AttributeType_t) -> og.Type: attribute_types = { type_name: og.AttributeType.type_from_ogn_type_name(type_name) for type_name in ogn.supported_attribute_type_names() } # The list of all legal types for type_name, attr_type in attribute_types.items(): type_from_string = og.ObjectLookup.attribute_type(type_name) self.assertEqual(attr_type, type_from_string, f"Type from string {type_name}") type_from_type = og.ObjectLookup.attribute_type(attr_type) self.assertEqual(attr_type, type_from_type, f"Type from string {type_name}") # Illegal type names and types for illegal_type in [ "dubble", "double[5]", og.Type(og.BaseDataType.ASSET), og.Type(og.BaseDataType.TAG), og.Type(og.BaseDataType.PRIM), og.Type(og.BaseDataType.DOUBLE, 5), og.Type(og.BaseDataType.PRIM, 1, 1), og.Type(og.BaseDataType.INT, 3, 0, og.AttributeRole.COLOR), ]: if isinstance(illegal_type, og.Type): self.assertFalse(og.AttributeType.is_legal_ogn_type(illegal_type)) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute_type(illegal_type) # -------------------------------------------------------------------------------------------------------------- async def test_deprecation(self): """Uses the deprecation helpers to ensure the proper messaging is sent out for each type.""" (was_silenced, was_showing_stack, current_messages) = ( ogt.DeprecateMessage.SILENCE_LOG, ogt.DeprecateMessage.SHOW_STACK, ogt.DeprecateMessage._MESSAGES_LOGGED.copy(), # noqa: PLW0212 ) ogt.DeprecateMessage.SILENCE_LOG = True ogt.DeprecateMessage.SHOW_STACK = True ogt.DeprecateMessage.clear_messages() try: def __has_deprecation(pattern: str, expected_count: int) -> bool: """Returns True if the pattern appears in the deprecation messages the given number of times""" return ( sum( match is not None for match in [ re.search(pattern, message) for message in ogt.DeprecateMessage._MESSAGES_LOGGED # noqa: PLW0212 ] ) == expected_count ) class NewClass: CLASS_MEMBER = 1 def __init__(self, value: int): self._ro_value = value self._rw_value = value * 2 @classmethod def class_method(cls): pass @staticmethod def static_method(): pass def regular_method(self): pass @property def ro_property(self): return self._ro_value @property def rw_property(self): return self._rw_value @rw_property.setter def rw_property(self, value): self._rw_value = value @ogt.DeprecatedClass("Use NewClass") class DeadClass: pass renamed_class = ogt.RenamedClass(NewClass, "OldName", "Renamed to NewClass") @ogt.deprecated_function("Use new_function") def old_function(): return 7 self.assertFalse( ogt.DeprecateMessage._MESSAGES_LOGGED, "Defining deprecations should not log messages" # noqa: PLW0212 ) dead_class = DeadClass() self.assertIsNotNone(dead_class) self.assertTrue(__has_deprecation(".*Use NewClass", 1), "Instantiated a deprecated class") ogt.DeprecateMessage.clear_messages() for dead_class in [renamed_class, renamed_class(5)]: self.assertIsNotNone(dead_class) self.assertTrue(isinstance(dead_class, NewClass)) self.assertTrue(callable(dead_class.class_method)) self.assertTrue(callable(dead_class.static_method)) self.assertTrue(callable(dead_class.regular_method)) if dead_class.__class__.__name__ == "NewClass": self.assertEqual(dead_class.ro_property, 5) self.assertEqual(dead_class.rw_property, 10) dead_class.rw_property = 11 self.assertEqual(dead_class.rw_property, 11) self.assertEqual(dead_class.CLASS_MEMBER, 1) self.assertTrue( __has_deprecation(".*Renamed to NewClass", 2), f"Accessing a renamed class {ogt.DeprecateMessage.messages_logged}", ) ogt.DeprecateMessage.clear_messages() dead_value = old_function() self.assertEqual(dead_value, 7, "Return value from a deprecated function") self.assertTrue(__has_deprecation("old_function.*Use new_function", 1), "Called a deprecated function") ogt.DeprecateMessage.clear_messages() from .deprecated_module import test_function test_function() self.assertTrue( __has_deprecation("deprecated_module.*import omni.graph.core", 1), "Importing a deprecated module" ) finally: import sys ogt.DeprecateMessage.SILENCE_LOG = was_silenced ogt.DeprecateMessage.SHOW_STACK = was_showing_stack ogt.DeprecateMessage._MESSAGES_LOGGED = current_messages # noqa: PLW0212 with suppress(AttributeError): del omni.graph.test.tests.deprecated_module sys.modules.pop("omni.graph.test.tests.deprecated_module") # -------------------------------------------------------------------------------------------------------------- async def test_inspector_format(self): """Dumps out graph and Fabric contents for a sample file, just to make sure the format stays legal. This does not test any of the semantics of the data, only that it will produce legal .json data. """ await self.__populate_data() # Check the dump of the Fabric data contents = None try: context = og.get_compute_graph_contexts()[0] contents = og.OmniGraphInspector().as_json(context) json.loads(contents) except json.JSONDecodeError as error: self.assertFalse(True, f"Formatting of Fabric data inspection is not legal JSON ({error}) - {contents}") # Check the dump of the graph structure contents = None try: for graph in og.get_all_graphs(): contents = og.OmniGraphInspector().as_json(graph) json.loads(contents) except json.JSONDecodeError as error: self.assertFalse(True, f"Formatting of Fabric data inspection is not legal JSON ({error}) - {contents}") # -------------------------------------------------------------------------------------------------------------- async def test_extension_versions_match(self): """Checks to make sure the core versions cited in CHANGELOG.md and extensions.toml match.""" extension_manager = omni.kit.app.get_app().get_extension_manager() for extension_name in [ "omni.graph", "omni.graph.tools", "omni.graph.examples.cpp", "omni.graph.examples.python", "omni.graph.nodes", "omni.graph.tutorials", "omni.graph.action", "omni.graph.scriptnode", "omni.inspect", ]: # Find the canonical extension of the core, which will come from extension.toml enabled_version = None for version in extension_manager.fetch_extension_versions(extension_name): if version["enabled"]: sem_ver = version["version"] enabled_version = f"{sem_ver[0]}.{sem_ver[1]}.{sem_ver[2]}" extension_path = Path(version["path"]) self.assertIsNotNone(enabled_version, f"Failed to find enabled version of {extension_name}") # Find the latest version in the changelog and make sure it matches the enabled version re_version_changelog = re.compile( r"##\s*\[([0-9]+\.[0-9]+\.[0-9]+)\]\s*-\s*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\s*" ) changelog_path = extension_path / "docs" / "CHANGELOG.md" self.assertTrue(changelog_path.is_file(), f"Changelog file {changelog_path} not found") changelog_version = None with open(changelog_path, "r", encoding="utf-8") as log_fd: for line in log_fd: version_match = re_version_changelog.match(line) if version_match: changelog_version = version_match.group(1) break self.assertEqual(enabled_version, changelog_version, f"Mismatch in versions of {changelog_path}")
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_dynamic_attributes.py
"""Tests related to the dynamic attribute Python interface generation feature""" import carb import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit from omni.graph.tools._impl.node_generator.attributes.naming import CPP_KEYWORDS, PYTHON_KEYWORDS, SAFE_CPP_KEYWORDS from pxr import UsdGeom # ============================================================================================================== class TestDynamicAttributes(ogts.OmniGraphTestCase): """Testing to ensure dynamic attributes works""" TEST_GRAPH_PATH = "/World/TestGraph" # -------------------------------------------------------------------------------------------------------------- async def __test_dynamic_attributes(self, node_type: str): """Test basic creation and interaction with the dynamic attribute accessors, used in the test node compute""" controller = og.Controller() keys = og.Controller.Keys (test_graph, _, _, _) = controller.edit(self.TEST_GRAPH_PATH) async def test_helper(create_usd): node_path = f"{self.TEST_GRAPH_PATH}/TestNode{create_usd}" og.cmds.CreateNode( graph=test_graph, node_path=node_path, node_type=f"omni.graph.tutorials.{node_type}", create_usd=create_usd, ) test_node = controller.node(node_path) self.assertTrue(test_node.is_valid()) controller.edit(test_graph, {keys.SET_VALUES: (("inputs:value", test_node), 127)}) output = controller.attribute("outputs:result", test_node) # Although this test only requires a single node it cannot be done via the .ogn test generator as it # needs to perform dynamic attribute manipulation between evaluations. # First test confirms the initial value is copied unchanged await controller.evaluate(test_graph) self.assertEqual(127, og.Controller.get(output)) # Second test adds a bit manipulator and confirms the bit it defines is manipulated properly self.assertTrue(test_node.create_attribute("inputs:firstBit", og.Type(og.BaseDataType.UINT))) controller.edit(test_graph, {keys.SET_VALUES: (("inputs:firstBit", test_node), 3)}) await controller.evaluate(test_graph) self.assertEqual(119, og.Controller.get(output)) # Third test adds a second bit manipulator and confirms that both bits are manipulated properly self.assertTrue(test_node.create_attribute("inputs:secondBit", og.Type(og.BaseDataType.UINT))) controller.edit(test_graph, {keys.SET_VALUES: (("inputs:secondBit", test_node), 7)}) await controller.evaluate(test_graph) self.assertEqual(247, og.Controller.get(output)) # Fourth test removes the first bit manipulator and confirms the output adapts accordingly self.assertTrue(test_node.remove_attribute("inputs:firstBit")) await controller.evaluate(test_graph) self.assertEqual(255, og.Controller.get(output)) # Fifth test alters the value of the modified bit and confirms the output adapts accordingly controller.edit(test_graph, {keys.SET_VALUES: (("inputs:secondBit", test_node), 4)}) await controller.evaluate(test_graph) self.assertEqual(111, og.Controller.get(output)) # Final test adds in the inversion attribute, with timecode role solely for the sake of checking role access self.assertTrue( test_node.create_attribute( "inputs:invert", og.Type(og.BaseDataType.FLOAT, 1, 0, og.AttributeRole.TIMECODE) ) ) await controller.evaluate(test_graph) self.assertEqual(0xFFFFFFFF - 111, og.Controller.get(output)) await test_helper(True) await test_helper(False) # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attributes_py(self): """Test basic creation and interaction with the dynamic attribute accessors for the Python implementation""" await self.__test_dynamic_attributes("DynamicAttributesPy") # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attributes_bundle(self): """Test basic creation and interaction with a bundle dynamic attribute""" controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1)) UsdGeom.Xformable(cube).AddTranslateOp() (_, nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ReadPrimsBundle", "omni.graph.nodes.ReadPrimsBundle"), ("ExtractPrim", "omni.graph.nodes.ExtractPrim"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.SET_VALUES: [ ("ReadPrimsBundle.inputs:usePaths", True), ("ReadPrimsBundle.inputs:primPaths", {"value": "/World/Cube", "type": "path"}), ("ExtractPrim.inputs:primPath", "/World/Cube"), ], keys.CONNECT: [ ("ReadPrimsBundle.outputs_primsBundle", "ExtractPrim.inputs:prims"), ], }, ) # creates some attributes on the script node script = nodes[2] matrix_type = og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX) self.assertTrue( script.create_attribute( "inputs:bundle", og.Type(og.BaseDataType.RELATIONSHIP, 1, 0, og.AttributeRole.BUNDLE) ) ) self.assertTrue( script.create_attribute("outputs:matrix", matrix_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) ) # connect them controller.edit("/TestGraph", {keys.CONNECT: ("ExtractPrim.outputs_primBundle", "Script.inputs:bundle")}) # set a script that extract the matrix s = 'db.outputs.matrix = db.inputs.bundle.get_attribute_by_name("worldMatrix").get()' controller.edit("/TestGraph", {keys.SET_VALUES: ("Script.inputs:script", s)}) # evaluate await controller.evaluate() # check that we have a matrix matrix_attr = controller.attribute("outputs:matrix", script) matrix_val = matrix_attr.get() self.assertEqual(matrix_val[12], 0) self.assertEqual(matrix_val[13], 0) self.assertEqual(matrix_val[14], 0) attr = cube.GetAttribute("xformOp:translate") attr.Set((2, 3, 4)) # evaluate await controller.evaluate() # check that we have a new matrix matrix_val = matrix_attr.get() self.assertEqual(matrix_val[12], 2) self.assertEqual(matrix_val[13], 3) self.assertEqual(matrix_val[14], 4) # ---------------------------------------------------------------------- async def test_deprecated_dynamic_attributes_deprecated_bundle(self): """Test basic creation and interaction with a bundle dynamic attribute This is a backward compatibility test for deprecated ReadPrim. """ controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1)) UsdGeom.Xformable(cube).AddTranslateOp() (_, nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ReadPrimBundle", "omni.graph.nodes.ReadPrimBundle"), ("ExtractBundle", "omni.graph.nodes.ExtractBundle"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.SET_VALUES: [ ("ReadPrimBundle.inputs:usePath", True), ("ReadPrimBundle.inputs:primPath", "/World/Cube"), ], keys.CONNECT: [ ("ReadPrimBundle.outputs_primBundle", "ExtractBundle.inputs:bundle"), ], }, ) # creates some attributes on the script node script = nodes[2] matrix_type = og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX) self.assertTrue( script.create_attribute( "inputs:bundle", og.Type(og.BaseDataType.RELATIONSHIP, 1, 0, og.AttributeRole.BUNDLE) ) ) self.assertTrue( script.create_attribute("outputs:matrix", matrix_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) ) # connect them controller.edit("/TestGraph", {keys.CONNECT: ("ExtractBundle.outputs_passThrough", "Script.inputs:bundle")}) # set a script that extract the matrix s = 'db.outputs.matrix = db.inputs.bundle.get_attribute_by_name("worldMatrix").get()' controller.edit("/TestGraph", {keys.SET_VALUES: ("Script.inputs:script", s)}) # evaluate await controller.evaluate() # check that we have a matrix matrix_attr = controller.attribute("outputs:matrix", script) matrix_val = matrix_attr.get() self.assertEqual(matrix_val[12], 0) self.assertEqual(matrix_val[13], 0) self.assertEqual(matrix_val[14], 0) attr = cube.GetAttribute("xformOp:translate") attr.Set((2, 3, 4)) # evaluate await controller.evaluate() # check that we have a new matrix matrix_val = matrix_attr.get() self.assertEqual(matrix_val[12], 2) self.assertEqual(matrix_val[13], 3) self.assertEqual(matrix_val[14], 4) # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attributes_cpp(self): """Test basic creation and interaction with the dynamic attribute accessors for the C++ implementation""" await self.__test_dynamic_attributes("DynamicAttributes") # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attribute_load(self): """Test basic creation and interaction with the dynamic attribute accessors, used in the test node compute""" (result, error) = await ogts.load_test_file("TestDynamicAttributes.usda", use_caller_subdirectory=True) self.assertTrue(result, error) controller = og.Controller() keys = og.Controller.Keys # The files each contain a set of test nodes in the different configurations of their dynamic attributes. # The name indicates which dynamic attributes exist on the node, similar to what the above test uses. # Test data is a list of five elements: # Node to test # Should the firstBit attribute be present? # Should the secondBit attribute be present? # Should the invert attribute be present? # Expected output value when the input is set to 127 test_data = [ ["/graph/NoDynamicAttributes", False, False, False, 127], ["/graph/OnlyFirst", True, False, False, 119], ["/graph/FirstAndSecond", True, True, False, 103], ["/graph/SecondInvert", False, True, True, 0xFFFFFFFF - 111], ["/graph/NoDynamicAttributesPy", False, False, False, 127], ["/graph/OnlyFirstPy", True, False, False, 119], ["/graph/FirstAndSecondPy", True, True, False, 103], ["/graph/SecondInvertPy", False, True, True, 0xFFFFFFFF - 111], ] for node_name, first_expected, second_expected, invert_expected, result_expected in test_data: node = controller.node(node_name) controller.edit("/graph", {keys.SET_VALUES: (("inputs:value", node), 127)}) await controller.evaluate() output = controller.attribute("outputs:result", node) self.assertIsNotNone(output) # Test for the presence of the expected dynamic attributes attributes_actual = [a.get_name() for a in node.get_attributes()] first_actual = "inputs:firstBit" in attributes_actual self.assertEqual(first_actual, first_expected, f"Dynamic attribute firstBit presence in {node_name}") second_actual = "inputs:secondBit" in attributes_actual self.assertEqual(second_actual, second_expected, f"Dynamic attribute secondBit presence in {node_name}") invert_actual = "inputs:invert" in attributes_actual self.assertEqual(invert_actual, invert_expected, f"Dynamic attribute invert presence in {node_name}") # Test the correct output value self.assertEqual(result_expected, og.Controller.get(output)) # -------------------------------------------------------------------------------------------------------------- async def __remove_connected_attribute(self, use_controller: bool): """ Test what happens when removing dynamic attributes that have connections, both incoming and outgoing. Args: use_controller: If True then use the og.Controller methods rather than the direct commands (This is mostly possible due to the fact that the controller and the command take the same argument list.) """ controller = og.Controller() keys = og.Controller.Keys (_, (source_node, sink_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Source", "omni.graph.tutorials.DynamicAttributesPy"), ("Sink", "omni.graph.tutorials.DynamicAttributesPy"), ] }, ) def run_create(**kwargs): """Select and run the appropriate create attribute command""" if use_controller: return og.NodeController.create_attribute(**kwargs) is not None if not og.cmds.CreateAttr(**kwargs)[1]: raise og.OmniGraphError(f"Create attribute using {kwargs} failed") return True def run_remove(**kwargs): """Select and run the appropriate remove attribute command""" if use_controller: return og.NodeController.remove_attribute(**kwargs) if not og.cmds.RemoveAttr(**kwargs)[1]: raise og.OmniGraphError(f"Remove attribute using {kwargs} failed") return True # Set up dynamic attributes on both source and sink and connect them self.assertTrue( run_create( node=source_node, attr_name="source", attr_type="float", attr_port=og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) ) source_attr = source_node.get_attribute("outputs:source") self.assertIsNotNone(source_attr) self.assertTrue( run_create( node=sink_node, attr_name="sink", attr_type="float", attr_port=og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, ) ) sink_attr = sink_node.get_attribute("inputs:sink") self.assertIsNotNone(sink_attr) controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: (source_attr, sink_attr)}) self.assertEqual([source_attr], sink_attr.get_upstream_connections()) # Try to remove the source attribute, failing due to the connection existing with self.assertRaises(og.OmniGraphError): run_remove(attribute=source_attr) # Remove the connections, then remove the source attribute, which should now succeed (success, result) = og.cmds.DisconnectAllAttrs(attr=source_attr, modify_usd=True) self.assertTrue(success, f"Disconnect all from source - {result}") self.assertTrue(run_remove(attribute=source_attr), "Remove source") self.assertEqual(0, sink_attr.get_upstream_connection_count()) # Restore the attribute and confirm the connection has returned omni.kit.undo.undo() omni.kit.undo.undo() source_attr = source_node.get_attribute("outputs:source") self.assertEqual(1, sink_attr.get_upstream_connection_count()) self.assertEqual(1, source_attr.get_downstream_connection_count()) # Try to remove the source attribute, failing due to the connection existing with self.assertRaises(og.OmniGraphError): run_remove(attribute=sink_attr) # Remove the connection, then remove the sink attribute, which should now succeed (success, result) = og.cmds.DisconnectAllAttrs(attr=sink_attr, modify_usd=True) self.assertTrue(success, "Disconnect all from sink") self.assertTrue(run_remove(attribute=sink_attr), "Remove sink") # Restore the attribute and confirm the connection has returned omni.kit.undo.undo() omni.kit.undo.undo() sink_attr = sink_node.get_attribute("inputs:sink") self.assertEqual(1, sink_attr.get_upstream_connection_count()) self.assertEqual(1, source_attr.get_downstream_connection_count()) # Confirm that the attribute configuration hasn't changed self.assertEqual("outputs:source", source_attr.get_name()) self.assertEqual("float", source_attr.get_type_name()) self.assertEqual(og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, source_attr.get_port_type()) self.assertEqual(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, source_attr.get_extended_type()) # TODO: Check on the default once it has been added self.assertEqual(0.0, source_attr.get()) self.assertEqual("inputs:sink", sink_attr.get_name()) self.assertEqual("float", sink_attr.get_type_name()) self.assertEqual(og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, sink_attr.get_port_type()) self.assertEqual(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, sink_attr.get_extended_type()) # TODO: Check on the default once it has been added self.assertEqual(0.0, sink_attr.get()) # -------------------------------------------------------------------------------------------------------------- async def test_remove_connected_attribute_by_command(self): """Run the dynamic attribute removal tests by direct commands""" await self.__remove_connected_attribute(False) # -------------------------------------------------------------------------------------------------------------- async def test_remove_connected_attribute_by_controller(self): """Run the dynamic attribute removal tests by using the Controller class""" await self.__remove_connected_attribute(True) # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_extended_attribute_customdata(self): """Test that creating dynamic extended attribute types sets the extended types correctly""" controller = og.Controller() keys = og.Controller.Keys (_, (node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("Node", "omni.graph.tutorials.DynamicAttributesPy")} ) exec_attr = controller.create_attribute( node, "outputs:exec", og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) any_attr = controller.create_attribute( node, "outputs:any", "any", og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, ) union_attr = controller.create_attribute( node, "outputs:union", "[int, double[3], float[3]]", og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, None, (og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, ["int", "double[3]", "float[3]"]), ) int_attr = controller.create_attribute(node, "inputs:int", "int") stage = omni.usd.get_context().get_stage() node_prim = stage.GetPrimAtPath(node.get_prim_path()) exec_metadata = node_prim.GetAttribute(exec_attr.get_name()).GetCustomData() any_metadata = node_prim.GetAttribute(any_attr.get_name()).GetCustomData() union_metadata = node_prim.GetAttribute(union_attr.get_name()).GetCustomData() int_metadata = node_prim.GetAttribute(int_attr.get_name()).GetCustomData() self.assertEqual(exec_metadata, {"ExecutionType": True}) self.assertEqual(any_metadata, {"ExtendedAttributeType": "Any", "omni": {"graph": {"attrType": "Any"}}}) self.assertEqual( union_metadata, { "ExtendedAttributeType": "Union-->int,double[3],float[3]", "omni": {"graph": {"attrType": "Union-->int,double[3],float[3]"}}, }, ) self.assertEqual(int_metadata, {}) # -------------------------------------------------------------------------------------------------------------- async def test_load_dynamic_extended_attribute_customdata(self): """The test file uses the deprecated global implicit graph so this also tests automatic conversion""" (result, error) = await ogts.load_test_file("TestDynamicExtendedAttributes.usda", use_caller_subdirectory=True) self.assertTrue(result, error) controller = og.Controller() exec_attr = controller.attribute("outputs:exec", "/__graphUsingSchemas/node") any_attr = controller.attribute("outputs:any", "/__graphUsingSchemas/node") union_attr = controller.attribute("outputs:union", "/__graphUsingSchemas/node") self.assertEqual(exec_attr.get_resolved_type(), og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION)) self.assertEqual(any_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN)) self.assertEqual(union_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN)) self.assertEqual(exec_attr.get_extended_type(), og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR) self.assertEqual(any_attr.get_extended_type(), og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) self.assertEqual(union_attr.get_extended_type(), og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) self.assertEqual(exec_attr.get_union_types(), None) self.assertEqual(any_attr.get_union_types(), None) self.assertEqual(union_attr.get_union_types(), ["int", "double[3]", "float[3]"]) # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attributes_memory_location(self): """Test that modifying the memory location of dynamic attributes changes how the data is set or retrieved""" controller = og.Controller(undoable=False) keys = og.Controller.Keys (graph, (test_node, _, _, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("DynamicNode", "omni.graph.test.TestDynamicAttributeMemory"), ("ArrayDefault", "omni.graph.nodes.ConstantInt"), ("ArrayNode", "omni.graph.nodes.ConstructArray"), ("SimpleDefault", "omni.graph.nodes.ConstantDouble"), ], keys.SET_VALUES: [ ("ArrayDefault.inputs:value", 1), ("ArrayNode.inputs:arraySize", 5), ("ArrayNode.inputs:arrayType", "int[]"), ("SimpleDefault.inputs:value", 4.25), ], keys.CONNECT: [ ("ArrayDefault.inputs:value", "ArrayNode.inputs:input0"), ], }, ) await controller.evaluate() on_gpu_attr = controller.attribute("inputs:onGpu", test_node) use_gpu_attr = controller.attribute("inputs:gpuPtrsOnGpu", test_node) in_verify_attr = controller.attribute("outputs:inputMemoryVerified", test_node) out_verify_attr = controller.attribute("outputs:outputMemoryVerified", test_node) self.assertTrue(on_gpu_attr.is_valid()) self.assertTrue(use_gpu_attr.is_valid()) self.assertTrue(in_verify_attr.is_valid()) self.assertTrue(out_verify_attr.is_valid()) # Meta-test that the test node does not give false positives when no dynamic attributes exist self.assertFalse(controller.get(in_verify_attr)) self.assertFalse(controller.get(out_verify_attr)) # Add the dynamic attributes the test node will be looking for in_attr = controller.create_attribute(test_node, "inputs:simple", "double") self.assertTrue(in_attr is not None and in_attr.is_valid()) in_arr_attr = controller.create_attribute(test_node, "inputs:array", "int[]") self.assertTrue(in_arr_attr is not None and in_arr_attr.is_valid()) out_attr = controller.create_attribute(test_node, "outputs:simple", "double") self.assertTrue(out_attr is not None and out_attr.is_valid()) out_arr_attr = controller.create_attribute(test_node, "outputs:array", "int[]") self.assertTrue(out_arr_attr is not None and out_arr_attr.is_valid()) controller.edit(graph, {keys.CONNECT: ("ArrayNode.outputs:array", "DynamicNode.inputs:array")}) # Run through all of the legal memory locations, verifying the input and output memory locations for on_gpu in [False, True, True]: for use_gpu_ptr in [False, False, True]: controller.set(on_gpu_attr, on_gpu) controller.set(use_gpu_attr, use_gpu_ptr) await controller.evaluate() self.assertTrue(controller.get(in_verify_attr), f"on_gpu={on_gpu}, use_gpu_ptr={use_gpu_ptr}") self.assertTrue(controller.get(out_verify_attr), f"on_gpu={on_gpu}, use_gpu_ptr={use_gpu_ptr}") # ---------------------------------------------------------------------- async def test_illegal_dynamic_attributes(self): """Test that attempting to create illegal attributes correctly raises an exception""" keys = og.Controller.Keys (_, (test_node,), _, _) = og.Controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleDefault", "omni.graph.nodes.ConstantDouble"), ], }, ) for undoable in [False, True]: controller = og.Controller(undoable=undoable) # First addition works in_attr = controller.create_attribute(test_node, "inputs:simple", "double") self.assertTrue(in_attr is not None and in_attr.is_valid()) # Second addition raises an exception with self.assertRaises(og.OmniGraphError): with ogts.ExpectedError(): controller.create_attribute(test_node, "inputs:simple", "double") # First removal works controller.remove_attribute(in_attr) # Second removal raises an exception with self.assertRaises(og.OmniGraphError): with ogts.ExpectedError(): controller.remove_attribute("inputs:simple", test_node) # -------------------------------------------------------------------------------------------------------------- async def test_adding_keyword_attributes(self): """Confirm that attempting to add attributes that are language keywords is disallowed""" controller = og.Controller() keys = og.Controller.Keys # The exact node type doesn't matter for this test, only that one is implemented in Python and one is C++ (_, (py_node, cpp_node), _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("PyNode", "omni.graph.test.TestSubtract"), ("CppNode", "omni.graph.test.Add2IntegerArrays"), ] }, ) # First check that the Python node types rejects attributes named for Python keywords for kw in PYTHON_KEYWORDS: with ogts.ExpectedError(): with self.assertRaises(ValueError): py_node.create_attribute(f"inputs:{kw}", og.Type(og.BaseDataType.UINT)) carb.log_error(f"Incorrectly allowed addition of attribute named for Python keyword '{kw}'") # Now do the same for the C++ nodes, which have some "safe" keywords, though they do issue a warning for kw in CPP_KEYWORDS: if kw in SAFE_CPP_KEYWORDS: self.assertTrue( cpp_node.create_attribute(f"inputs:{kw}", og.Type(og.BaseDataType.UINT)), f"Trying to add attribute using C++ keyword '{kw}'", ) else: with ogts.ExpectedError(): with self.assertRaises(ValueError): cpp_node.create_attribute(f"inputs:{kw}", og.Type(og.BaseDataType.UINT)) carb.log_error(f"Incorrectly allowed addition of attribute named for C++ keyword '{kw}'") # -------------------------------------------------------------------------------------------------------------- async def test_output_raw_data_works(self): """Validate that dynamic output and state attributes accessed from the node DB allow writing the raw data pointer""" controller = og.Controller(undoable=False) keys = og.Controller.Keys (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("DynamicNode", "omni.graph.test.TestDynamicAttributeRawData"), ], }, ) # Evaluate the graph once to ensure the node has a Database created await controller.evaluate(graph) test_node = nodes[0] for i in range(10): controller.create_attribute( test_node, f"inputs:input{i}", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, i, ) controller.create_attribute( test_node, "outputs:output0", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, 0, ) controller.create_attribute( test_node, "state:state0", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE, 0, ) # Act: evaluate the graph await controller.evaluate(graph) # Assert: read the sum output and test that the dynamic attributes were included in the computation output_attr = controller.attribute("outputs:output0", test_node) self.assertEqual(45, controller.get(output_attr), "The dynamic output does not have the expected value") state_attr = controller.attribute("state:state0", test_node) self.assertEqual(45, controller.get(state_attr), "The dynamic state does not have the expected value")
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_all_types.py
"""Tests exercising every supported OGN data type""" from math import isnan from pathlib import Path from tempfile import TemporaryDirectory from typing import Set import carb import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.nodes.tests as ognts import omni.graph.tools.ogn as ogn import omni.kit.test import omni.usd # Fast lookup of matrix dimensions, to avoid sqrt call _MATRIX_DIMENSIONS = {4: 2, 9: 3, 16: 4} # ====================================================================== class TestOmniGraphAllTypes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises all of the data types supported by OmniGraph. These tests do not exercise any, union, or bundle types, which already have plenty of their own tests. """ # These are not part of the generated attribute pattern so they will be ignored. They could be tested separately # but that won't add any value to the tests. UNCHECKED_ATTRIBUTES = [ "node:type", "node:typeVersion", "NodeWithAllTypes", "inputs:doNotCompute", "inputs:a_target", "outputs:a_target", "state:a_target", "inputs:a_bundle", "outputs_a_bundle", "state_a_bundle", "state:a_stringEmpty", "state:a_firstEvaluation", ] TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- 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 # ---------------------------------------------------------------------- def __types_to_test(self) -> Set[str]: """Returns the set of attribute type names to be tested. This consists of every type accepted by OGN, minus a few that are tested separately""" # "any" types need a different set of tests as ultimately they only represent one of the other types. # "bundle" and "target" types have different tests as they are mainly concerned with membership rather than actual data # "transform" types are omitted as they are marked for deprecation in USD so we don't want to support them types_not_tested = ["any", "bundle", "target", "transform[4]", "transform[4][]"] return [type_name for type_name in ogn.supported_attribute_type_names() if type_name not in types_not_tested] # ---------------------------------------------------------------------- async def __verify_all_types_are_tested(self, node_type_name: str): """Meta-test to ensure that the list of types tested in the sample node is the same as the list of all supported types, according to the OGN node generator. It will use the full set of supported names, drawn from the generator, and compare against the set of attribute type names that appear on the given node, extracted from the node's ABI. Args: node_type_name: Registered node type name for the node to test """ # Get the list of types to test. supported_types = self.__types_to_test() nodes_attribute_types = [] controller = og.Controller() keys = og.Controller.Keys (_, (test_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("NodeWithAllTypes", node_type_name)} ) for attribute in test_node.get_attributes(): if attribute.get_port_type() != og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: continue attribute_name = attribute.get_name() if attribute_name in self.UNCHECKED_ATTRIBUTES: continue attribute_type = attribute.get_resolved_type() port_name = og.get_port_type_namespace(attribute.get_port_type()) expected_name = f"{port_name}:{self.__attribute_type_to_name(attribute_type)}" type_name = attribute_type.get_ogn_type_name() self.assertEqual( expected_name, attribute_name, f"Generated name differs from actual name, type {type_name}" ) nodes_attribute_types.append(type_name) self.assertCountEqual(supported_types, nodes_attribute_types) # ---------------------------------------------------------------------- async def test_all_types_tested_cpp(self): """Test that the C++ node exercising all allowed types has covered everything""" await self.__verify_all_types_are_tested("omni.graph.test.TestAllDataTypes") # ---------------------------------------------------------------------- async def test_all_types_tested_python(self): """Test that the Python node exercising all allowed types has covered everything""" await self.__verify_all_types_are_tested("omni.graph.test.TestAllDataTypesPy") # ---------------------------------------------------------------------- async def __test_all_data_types(self, node_type_name: str): """Test that sets values of all supported types on the node of the given type using automatic type generators. Both the name of the attribute and the sample values for an attribute of that type are supplied automatically. The node's only function should be to assign the input to the output, so all types can be validated by simply comparing the computed output against the values that were set on the input. It is assumed that actual compute operation and input/output correspondence is done elsewhere so this type of test is sufficient to validate that access to all data types as both an input and an output is correctly implemented. Args: node_type_name: Registered node type name for the node to test """ # Get the list of types to test. supported_types = self.__types_to_test() controller = og.Controller() keys = og.Controller.Keys (graph, (test_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("NodeWithAllTypes", node_type_name)} ) 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] for type_name in supported_types ] controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ ((f"inputs:{name}", test_node), value) for name, value in zip(attribute_names, expected_values) ] + [(("inputs:doNotCompute", test_node), False)] }, ) await controller.evaluate(graph) actual_values = [ og.Controller.get(controller.attribute(f"outputs:{name}", test_node)) for name in attribute_names ] for actual_value, expected_value, attribute_name in zip(actual_values, expected_values, attribute_names): ogts.verify_values(expected_value, actual_value, f"Testing output data types on {attribute_name}") actual_values = [ og.Controller.get(controller.attribute(f"state:{name}", test_node)) for name in attribute_names ] for actual_value, expected_value, attribute_name in zip(actual_values, expected_values, attribute_names): ogts.verify_values(expected_value, actual_value, f"Testing state data types on {attribute_name}") # ---------------------------------------------------------------------- async def test_all_data_types_cpp(self): """Test that the C++ node exercising all allowed types has covered everything""" await self.__test_all_data_types("omni.graph.test.TestAllDataTypes") # ---------------------------------------------------------------------- async def test_all_data_types_python(self): """Test that the Python node exercising all allowed types has covered everything""" await self.__test_all_data_types("omni.graph.test.TestAllDataTypesPy") # ---------------------------------------------------------------------- async def test_all_types_extended(self): """Tests that 'any' attribute can be resolved to and correctly read/write data of all types""" carb.log_warn("Warnings of the type 'No source has valid data' are expected during this test") # AllTypes resolves the types upstream through A and B. Then we set a value on A, and ensure # the value make it through to concrete AllTypes.inputs:attrib_name # 'Any' 'Any' # +------------+ +------------+ +-----------+ # | Extended A +---->| Extended B +---->|AllTypes | # +------------+ +------------+ +-----------+ controller = og.Controller() keys = og.Controller.Keys (_, (extended_node_a, extended_node_b, all_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ExtendedNodeA", "omni.graph.test.TypeResolution"), ("ExtendedNodeB", "omni.graph.test.TypeResolution"), ("AllTypes", "omni.graph.test.TestAllDataTypes"), ], keys.SET_VALUES: ("AllTypes.inputs:doNotCompute", False), }, ) any_in_a = controller.attribute("inputs:anyValueIn", extended_node_a) any_in_b = controller.attribute("inputs:anyValueIn", extended_node_b) any_out_a = controller.attribute("outputs:anyValue", extended_node_a) any_out_b = controller.attribute("outputs:anyValue", extended_node_b) async def test_type(attrib_name, expected_value): # Connect the 'any' output to the typed-input to get the 'any' input to be resolved. # Then set the value of the resolved input and measure the resolved output value (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CONNECT: [(any_out_b, (attrib_name, all_node)), (any_out_a, any_in_b)]} ) await controller.evaluate(graph) controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: (any_in_a, expected_value)}) await controller.evaluate(graph) actual_value_a = og.Controller.get(any_out_a) actual_value_b = og.Controller.get(any_out_b) actual_value_all = og.Controller.get(controller.attribute(attrib_name, all_node)) if isinstance(expected_value, str) or ( isinstance(expected_value, list) and isinstance(expected_value[0], str) ): self.assertEqual(expected_value, actual_value_a) self.assertEqual(expected_value, actual_value_b) self.assertEqual(expected_value, actual_value_all) else: expected_array = np.ravel(np.array(expected_value)) self.assertTrue(np.allclose(np.ravel(np.atleast_1d(actual_value_a)), expected_array)) self.assertTrue(np.allclose(np.ravel(np.atleast_1d(actual_value_b)), expected_array)) self.assertTrue(np.allclose(np.ravel(np.atleast_1d(actual_value_all)), expected_array)) # Node totally disconnects - type should be reverted to unknown controller.edit( self.TEST_GRAPH_PATH, {keys.DISCONNECT: [(any_out_b, (attrib_name, all_node)), (any_out_a, any_in_b)]} ) await controller.evaluate(graph) # objectId can not connect to 'any', so remove that from this test supported_types = [ type_name for type_name in self.__types_to_test() if type_name not in ["objectId", "objectId[]", "execution", "path"] ] attribute_names = [ self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name)) for type_name in supported_types ] # We can test 2 sets of sample values expected_values_set0 = [ ogn.get_attribute_manager_type(type_name).sample_values()[0] for type_name in supported_types ] expected_values_set1 = [ ogn.get_attribute_manager_type(type_name).sample_values()[1] for type_name in supported_types ] for attrib_name, value in sorted(zip(attribute_names, expected_values_set0)): await test_type(f"inputs:{attrib_name}", value) for attrib_name, value in sorted(zip(attribute_names, expected_values_set1)): await test_type(f"inputs:{attrib_name}", value) # ---------------------------------------------------------------------- async def test_all_usd_cast_types(self): """Test that checks that bundles with USD type casting works for all available USD types""" # Set up the contents for a prim with all types. Skip types that cannot be added to a prim bundle. supported_type_names = [ type_name for type_name in self.__types_to_test() if type_name not in ["execution", "objectId", "objectId[]"] ] supported_types = [og.AttributeType.type_from_ogn_type_name(type_name) for type_name in supported_type_names] attribute_names = [self.__attribute_type_to_name(supported_type) for supported_type in supported_types] expected_values = [ ogn.get_attribute_manager_type(type_name).sample_values()[0] for type_name in supported_type_names ] # This is the array of types for which the node will attempt USD casting, which should be all of the types # mentioned in omni/graph/core/ogn/UsdTypes.h usd_cast_types = [ "half", "token", "timecode", "half[]", "token[]", "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][]", # These are caught by the timecode cast "double", "double[]", # Roles are caught by the casts too since they are ignored at that point (and not checked in the node) "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][]", ] controller = og.Controller() keys = og.Controller.Keys (graph, (_, inspector_outputs_node, inspector_state_node, _), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("UsdCastingNode", "omni.graph.test.TestUsdCasting"), ("InspectorOutput", "omni.graph.nodes.BundleInspector"), ("InspectorState", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: [ ( "/World/Prim", { name: (type_name, value) for type_name, name, value in zip(supported_types, attribute_names, expected_values) }, ) ], keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/World/Prim", "PrimExtract"), keys.CONNECT: [ ("PrimExtract.outputs_primBundle", "UsdCastingNode.inputs:a_bundle"), ("UsdCastingNode.outputs_a_bundle", "InspectorOutput.inputs:bundle"), ("UsdCastingNode.state_a_bundle", "InspectorState.inputs:bundle"), ], }, ) await controller.evaluate(graph) expected_output = {} count = 1 for index, type_name in enumerate(supported_type_names): if type_name in usd_cast_types: count += 1 expected_output[attribute_names[index]] = [ supported_types[index].get_base_type_name(), supported_types[index].tuple_count, supported_types[index].array_depth, supported_types[index].get_role_name(), expected_values[index], ] # Add in the extra attributes that aren't explicit types expected_output["sourcePrimType"] = ["token", 1, 0, "none", "OmniGraphPrim"] expected_output["sourcePrimPath"] = ["token", 1, 0, "none", "/World/Prim"] expected_results = (len(expected_output), expected_output) ognts.verify_bundles_are_equal( ognts.filter_bundle_inspector_results( ognts.bundle_inspector_results(inspector_outputs_node), [], filter_for_inclusion=False ), expected_results, ) ognts.verify_bundles_are_equal( ognts.filter_bundle_inspector_results( ognts.bundle_inspector_results(inspector_state_node), [], filter_for_inclusion=False ), expected_results, ) # ---------------------------------------------------------------------- async def __test_read_all_types_default(self, node_type_name: str): """Test that saving and loading a file containing non-standard default values correctly brings back the default values for all types. Args: node_type_name: Registered node type name for the node to test """ # Create a file containing a node of the given type and save it controller = og.Controller() keys = og.Controller.Keys (graph, (test_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("NodeWithAllTypes", node_type_name)} ) await controller.evaluate(graph) test_node_path = test_node.get_prim_path() # Get the list of types to test. supported_types = self.__types_to_test() attribute_names = [ self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name)) for type_name in supported_types ] # Remember the default values in the node. A copy has to be made because otherwise the data will reference # Fabric data, which goes away when the stage is saved (because currently at that point OmniGraph is rebuilt). expected_default_values = [] for name in attribute_names: value = og.Controller.get(og.Controller.attribute(f"inputs:{name}", test_node)) if isinstance(value, np.ndarray): expected_default_values.append(value.copy()) else: expected_default_values.append(value) # -------------------------------------------------------------------------------------------------------------- # First test that the node that was saved with no values comes back in with the expected default values with TemporaryDirectory() as test_directory: tmp_file_path = Path(test_directory) / f"{node_type_name}.usda" (result, error, _) = await omni.usd.get_context().save_as_stage_async(str(tmp_file_path)) self.assertTrue(result, error) (result, error) = await omni.usd.get_context().reopen_stage_async() self.assertTrue(result, error) await og.Controller.evaluate() test_node = og.Controller.node(test_node_path) actual_values = [ og.Controller.get(controller.attribute(f"inputs:{name}", test_node)) for name in attribute_names ] for name in attribute_names: value = og.Controller.get(controller.attribute(f"inputs:{name}", test_node)) for actual, expected, name in zip(actual_values, expected_default_values, attribute_names): ogts.verify_values(expected, actual, f"Testing input data types on {name}") # ---------------------------------------------------------------------- async def test_read_all_types_default_cpp(self): """Test that the C++ node exercising all allowed types has covered everything""" await self.__test_read_all_types_default("omni.graph.test.TestAllDataTypes") # ---------------------------------------------------------------------- async def test_read_all_types_default_python(self): """Test that the Python node exercising all allowed types has covered everything""" await self.__test_read_all_types_default("omni.graph.test.TestAllDataTypesPy") # ---------------------------------------------------------------------- async def __test_read_all_types_modified(self, node_type_name: str): """Test that saving and loading a file containing non-default values correctly brings back the modified values for all types. Args: node_type_name: Registered node type name for the node to test """ node_type_base_name = node_type_name.split(".")[-1] # Get the list of all types to test. supported_types = self.__types_to_test() attribute_names = [ self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name)) for type_name in supported_types ] # Sample values from the attribute managers are known to not be the defaults of the AllNodeTypes nodes expected_sample_values = [ ogn.get_attribute_manager_type(type_name).sample_values()[0] for type_name in supported_types ] test_file_name = f"{node_type_base_name}.NonDefault.usda" (result, error) = await ogts.load_test_file(test_file_name, use_caller_subdirectory=True) self.assertTrue(result, error) test_node = og.Controller.node(f"/World/TestGraph/{node_type_base_name}") actual_values = [ og.Controller.get(og.Controller.attribute(f"inputs:{name}", test_node)) for name in attribute_names ] for actual, expected, name in zip(actual_values, expected_sample_values, attribute_names): ogts.verify_values(expected, actual, f"Testing input data types on {name}") # ---------------------------------------------------------------------- async def test_read_all_types_modified_cpp(self): """Test that the C++ node exercising all allowed types has covered everything""" await self.__test_read_all_types_modified("omni.graph.test.TestAllDataTypes") # ---------------------------------------------------------------------- async def test_read_all_types_modified_python(self): """Test that the Python node exercising all allowed types has covered everything""" await self.__test_read_all_types_modified("omni.graph.test.TestAllDataTypesPy") # ---------------------------------------------------------------------- def _sanity_check_union_values(self, types: dict): """Runs a series of tests to validate the given dictionary of unions contains expected values""" def validate_subset(subset: str, superset: str): self.assertIsNotNone(types.get(subset, None)) self.assertIsNotNone(types.get(superset, None)) subset_items = types[subset] superset_items = types[superset] for item in subset_items: self.assertIn(item, superset_items, f"Expected {item} to be in {superset}") def validate_array_form(scalar_form: str, array_form: str): self.assertIsNotNone(types.get(scalar_form, None)) self.assertIsNotNone(types.get(array_form, None)) scalar_items = types[scalar_form] array_items = types[array_form] for item in scalar_items: self.assertIn(item + "[]", array_items, f"Expected {item} to be in {array_form}") self.assertGreater(len(types), 0) for x in ["uchar", "int", "uint", "uint64", "int64"]: self.assertIn(x, types["integral_scalers"]) for x in ["int[2]", "int[3]", "int[4]"]: self.assertIn(x, types["integral_tuples"]) for x in ["double", "float", "half", "timecode"]: self.assertIn(x, types["decimal_scalers"]) for x in [ "double[2]", "double[3]", "double[4]", "float[2]", "float[3]", "float[4]", "half[2]", "half[3]", "half[4]", "colord[3]", "colord[4]", "colorf[3]", "colorf[4]", "colorh[3]", "colorh[4]", "normald[3]", "normalf[3]", "normalh[3]", "pointd[3]", "pointf[3]", "pointh[3]", "texcoordd[2]", "texcoordd[3]", "texcoordf[2]", "texcoordf[3]", "texcoordh[2]", "texcoordh[3]", "quatd[4]", "quatf[4]", "quath[4]", "vectord[3]", "vectorf[3]", "vectorh[3]", ]: self.assertIn(x, types["decimal_tuples"]) validate_subset("integral_scalers", "integral_array_elements") validate_subset("integral_tuples", "integral_array_elements") validate_array_form("integral_array_elements", "integral_arrays") validate_subset("integral_array_elements", "integrals") validate_subset("integral_arrays", "integrals") validate_subset("decimal_scalers", "decimal_array_elements") validate_subset("decimal_tuples", "decimal_array_elements") validate_array_form("decimal_array_elements", "decimal_arrays") validate_subset("decimal_array_elements", "decimals") validate_subset("decimal_arrays", "decimals") validate_subset("integral_scalers", "numeric_scalers") validate_subset("decimal_scalers", "numeric_scalers") validate_subset("integral_tuples", "numeric_tuples") validate_subset("decimal_tuples", "numeric_tuples") validate_subset("numeric_scalers", "numeric_array_elements") validate_subset("numeric_tuples", "numeric_array_elements") validate_subset("matrices", "numeric_array_elements") validate_array_form("numeric_array_elements", "numeric_arrays") validate_subset("numeric_array_elements", "numerics") validate_subset("numeric_arrays", "numerics") validate_subset("numeric_array_elements", "array_elements") validate_subset("numeric_arrays", "arrays") self.assertIn("token", types["array_elements"]) self.assertIn("token[]", types["arrays"]) # ---------------------------------------------------------------------- async def test_union_types_contain_expected_values(self): """Performs a sanity check on the attribute union values returned from the runtime""" # The same configuration file is used to populate dictionaries form both dlls. # Validate they contain the same entries # Test the dictionary loaded from omni.graph.core self._sanity_check_union_values(og.AttributeType.get_unions()) # Validate the entries are the same self.assertDictEqual(og.AttributeType.get_unions(), ogn.ATTRIBUTE_UNION_GROUPS) # ---------------------------------------------------------------------- async def __test_nan_values(self, node_type_name: str): """Test that evaluating NaN values correctly copies and extracts the values. This could not be done with a regular test sequence as NaN != NaN Args: node_type_name: Registered node type name for the node to test """ controller = og.Controller() keys = og.Controller.Keys (graph, (test_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("NodeWithNans", node_type_name)} ) await controller.evaluate(graph) nan_attributes = [ "colord3", "colord4", "colord3_array", "colord4_array", "colorf3", "colorf4", "colorf3_array", "colorf4_array", "colorh3", "colorh4", "colorh3_array", "colorh4_array", "double", "double2", "double3", "double4", "double_array", "double2_array", "double3_array", "double4_array", "float", "float2", "float3", "float4", "float_array", "float2_array", "float3_array", "float4_array", "frame4", "frame4_array", "half", "half2", "half3", "half4", "half_array", "half2_array", "half3_array", "half4_array", "matrixd2", "matrixd3", "matrixd4", "matrixd2_array", "matrixd3_array", "matrixd4_array", "normald3", "normald3_array", "normalf3", "normalf3_array", "normalh3", "normalh3_array", "pointd3", "pointd3_array", "pointf3", "pointf3_array", "pointh3", "pointh3_array", "quatd4", "quatd4_array", "quatf4", "quatf4_array", "quath4", "quath4_array", "texcoordd2", "texcoordd3", "texcoordd2_array", "texcoordd3_array", "texcoordf2", "texcoordf3", "texcoordf2_array", "texcoordf3_array", "texcoordh2", "texcoordh3", "texcoordh2_array", "texcoordh3_array", "timecode", "timecode_array", "vectord3", "vectord3_array", "vectorf3", "vectorf3_array", "vectorh3", "vectorh3_array", ] def __is_nan(value) -> bool: if isinstance(value, list): return all(__is_nan(element) for element in value) if isinstance(value, np.ndarray): return np.alltrue(np.isnan(value)) return isnan(value) for attribute_name in nan_attributes: attr = controller.attribute(f"outputs:a_{attribute_name}_nan", test_node) value = controller.get(attr) self.assertTrue(__is_nan(value)) attr = controller.attribute(f"outputs:a_{attribute_name}_snan", test_node) value = controller.get(attr) self.assertTrue(__is_nan(value)) # ---------------------------------------------------------------------- async def test_nan_values_cpp(self): """Test that the C++ node exercising all allowed types handles NaN values correctly""" await self.__test_nan_values("omni.graph.test.TestNanInf") # ---------------------------------------------------------------------- async def test_nan_values_python(self): """Test that the Python node exercising all allowed types handles NaN values correctly""" await self.__test_nan_values("omni.graph.test.TestNanInfPy") async def test_node_database_id_py(self): """Test if database id is not changing between graph evaluations""" controller = og.Controller() keys = og.Controller.Keys # Disconnected input bundle should be invalid (graph, (_, node_database), _, _) = controller.edit( "/World/Graph", { keys.CREATE_NODES: [ ("BundleConstructor", "omni.graph.nodes.BundleConstructor"), ("NodeDatabase", "omni.graph.test.NodeDatabasePy"), ], }, ) # database id remains the same because topology has not changed graph.evaluate() previous_id = node_database.get_attribute("outputs:id").get() graph.evaluate() current_id = node_database.get_attribute("outputs:id").get() self.assertTrue(previous_id == current_id) previous_id = current_id graph.evaluate() current_id = node_database.get_attribute("outputs:id").get() self.assertTrue(previous_id == current_id) # disconnect input connect rebuilds the database (graph, _, _, _) = controller.edit( "/World/Graph", { keys.CONNECT: [ ("BundleConstructor.outputs_bundle", "NodeDatabase.inputs:bundle"), ], }, ) graph.evaluate() current_id = node_database.get_attribute("outputs:id").get() self.assertTrue(previous_id != current_id) # subsequent evaluation does not change id previous_id = current_id graph.evaluate() current_id = node_database.get_attribute("outputs:id").get() self.assertTrue(previous_id == current_id)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/deprecated_module.py
"""Test module that exercises import-level deprecation""" import omni.graph.tools as ogt ogt.DeprecatedImport("Use 'import omni.graph.core as og' instead") def test_function(): pass
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_traversal.py
from typing import List, Set import omni.graph.core as og import omni.kit.test import omni.usd from omni.graph.core import traverse_downstream_graph, traverse_upstream_graph class TestTraversal(omni.graph.core.tests.OmniGraphTestCase): """Test cases for graph traversal functions.""" async def test_downstream_connections_works(self): """ Validate that downstream connections are collected correctly. """ stage = omni.usd.get_context().get_stage() # Test graph set up # [G1In1]-->[G1M1]-->[G1M2]--->[G1M4]--->[G1Out1] # [G1In2]---^ |---[G1M3]----| |--->[G1Out2] # # [G2In1]-->[G2M1]-->[G2Out1] # # [G3In1] controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("G1In1", "omni.graph.nodes.ConstantFloat"), ("G1In2", "omni.graph.nodes.ConstantFloat"), ("G1M1", "omni.graph.nodes.Add"), ("G1M2", "omni.graph.nodes.Add"), ("G1M3", "omni.graph.nodes.Add"), ("G1M4", "omni.graph.nodes.Add"), ("G1Out1", "omni.graph.nodes.Magnitude"), ("G1Out2", "omni.graph.nodes.Magnitude"), ("G2In1", "omni.graph.nodes.ConstantFloat"), ("G2M1", "omni.graph.nodes.Magnitude"), ("G2Out1", "omni.graph.nodes.Magnitude"), ("G3In1", "omni.graph.nodes.ConstantFloat"), ], keys.CONNECT: [ ("G1In1.inputs:value", "G1M1.inputs:a"), ("G1In2.inputs:value", "G1M1.inputs:b"), ("G1M1.outputs:sum", "G1M2.inputs:a"), ("G1M1.outputs:sum", "G1M2.inputs:b"), ("G1M1.outputs:sum", "G1M3.inputs:a"), ("G1M1.outputs:sum", "G1M3.inputs:b"), ("G1M2.outputs:sum", "G1M4.inputs:a"), ("G1M3.outputs:sum", "G1M4.inputs:b"), ("G1M4.outputs:sum", "G1Out1.inputs:input"), ("G1M4.outputs:sum", "G1Out2.inputs:input"), ("G2In1.inputs:value", "G2M1.inputs:input"), ("G2M1.outputs:magnitude", "G2Out1.inputs:input"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) _, _, _, _, g1m3, g1m4, g1out1, g1out2, _, g2m1, g2out1, _ = prims # Valdate the set of visited nodes expected = [g1m3, g1m4, g1out1, g1out2, g2m1, g2out1] visited = traverse_downstream_graph([g2m1, g1m3]) actual = [og.Controller.prim(n) for n in visited] self.assertCountEqual(expected, actual, "Unexpected set of visited nodes downstream") async def test_downstream_connections_can_include_compound_graph_prim(self): """Test that calling for downstream connections with compounds can include the compound graph prim.""" node_type = "omni.graph.nodes.Add" controller = og.Controller() keys = controller.Keys # Test graph set up # |============================| # [O1]->|->[I1]---->|I2|----->|I3|-->|--->|O2] # |---------->| | | # |--->[I4] | # | [I5]->[I6] | # |============================| (_, _, _, nodes) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("Outer1", node_type), ("Outer2", node_type), ( "Compound", { keys.CREATE_NODES: [ ("Inner1", node_type), ("Inner2", node_type), ("Inner3", node_type), ("Inner4", node_type), ("Inner5", node_type), ("Inner6", node_type), ], keys.PROMOTE_ATTRIBUTES: [ ("Inner1.inputs:a", "inputs:one"), ("Inner2.inputs:a", "inputs:two"), ("Inner3.outputs:sum", "outputs:value"), ("Inner4.inputs:a", "inputs:three"), ], keys.CONNECT: [ ("Inner1.outputs:sum", "Inner2.inputs:b"), ("Inner2.outputs:sum", "Inner3.inputs:a"), ("Inner5.outputs:sum", "Inner6.inputs:a"), ], }, ), ], keys.CONNECT: [ ("Outer1.outputs:sum", "Compound.inputs:one"), ("Compound.outputs:value", "Outer2.inputs:a"), ], }, ) def assert_valid_traversal(items: List, expected_results: Set[og.Node]): """Helper method to validate traversal results.""" prims = [og.Controller.prim(i) for i in items] actual_set = traverse_downstream_graph(prims) self.assertEquals(expected_results, actual_set, "Unexpected set of visited nodes downstream") def assert_invalid_traversal(items): prims = [og.Controller.prim(i) for i in items] with self.assertRaises(og.OmniGraphError): traverse_downstream_graph(prims) compound_graph = nodes["Compound"].get_compound_graph_instance() # test traversal with compound graph assert_valid_traversal([nodes["Outer1"]], {nodes["Outer1"], nodes["Compound"], nodes["Outer2"]}) # test with just the compound graph assert_valid_traversal([compound_graph], {nodes["Inner1"], nodes["Inner2"], nodes["Inner3"], nodes["Inner4"]}) # test with a node inside the compound graph assert_valid_traversal([compound_graph, nodes["Inner5"]], set(compound_graph.get_nodes())) # invalid traversals assert_invalid_traversal([nodes["Inner1"], nodes["Outer1"]]) # mixed graphs assert_invalid_traversal([compound_graph, nodes["Outer1"]]) # compound and outer node assert_invalid_traversal(["/World"]) # invalid node assert_invalid_traversal(["/World/Testgraph"]) # non compound graph async def test_upstream_connections_works(self): """ Validate that upstream connections are collected correctly. """ stage = omni.usd.get_context().get_stage() # Test graph set up # [G1In1]-->[G1M1]-->[G1M2]--->[G1M4]--->[G1Out1] # [G1In2]---^ |---[G1M3]----| |--->[G1Out2] # # [G2In1]-->[G2M1]-->[G2Out1] # # [G3In1] controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("G1In1", "omni.graph.nodes.ConstantFloat"), ("G1In2", "omni.graph.nodes.ConstantFloat"), ("G1M1", "omni.graph.nodes.Add"), ("G1M2", "omni.graph.nodes.Add"), ("G1M3", "omni.graph.nodes.Add"), ("G1M4", "omni.graph.nodes.Add"), ("G1Out1", "omni.graph.nodes.Magnitude"), ("G1Out2", "omni.graph.nodes.Magnitude"), ("G2In1", "omni.graph.nodes.ConstantFloat"), ("G2M1", "omni.graph.nodes.Magnitude"), ("G2Out1", "omni.graph.nodes.Magnitude"), ("G3In1", "omni.graph.nodes.ConstantFloat"), ], keys.CONNECT: [ ("G1In1.inputs:value", "G1M1.inputs:a"), ("G1In2.inputs:value", "G1M1.inputs:b"), ("G1M1.outputs:sum", "G1M2.inputs:a"), ("G1M1.outputs:sum", "G1M2.inputs:b"), ("G1M1.outputs:sum", "G1M3.inputs:a"), ("G1M1.outputs:sum", "G1M3.inputs:b"), ("G1M2.outputs:sum", "G1M4.inputs:a"), ("G1M3.outputs:sum", "G1M4.inputs:b"), ("G1M4.outputs:sum", "G1Out1.inputs:input"), ("G1M4.outputs:sum", "G1Out2.inputs:input"), ("G2In1.inputs:value", "G2M1.inputs:input"), ("G2M1.outputs:magnitude", "G2Out1.inputs:input"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) g1in1, g1in2, g1m1, _, g1m3, _, _, _, g2in1, g2m1, _, _ = prims # Validate the set of visited nodes expected = [g1m3, g1m1, g1in1, g1in2, g2m1, g2in1] visited = traverse_upstream_graph([g2m1, g1m3]) actual = [og.Controller.prim(n) for n in visited] self.assertCountEqual(expected, actual, "Unexpected set of visited nodes upstream") async def test_upstream_connections_can_include_compound_graph_prim(self): """Test that calling for uptream connections with compounds can include the compound graph prim.""" node_type = "omni.graph.nodes.Add" controller = og.Controller() keys = controller.Keys # Test graph set up # |============================| # [O1]->|->[I1]---->|I2|----->|I3|-->|--->|O2] # | | | | # | [I4]------------------->| # | [I5]->[I6] | # |============================| (_, _, _, nodes) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("Outer1", node_type), ("Outer2", node_type), ( "Compound", { keys.CREATE_NODES: [ ("Inner1", node_type), ("Inner2", node_type), ("Inner3", node_type), ("Inner4", node_type), ("Inner5", node_type), ("Inner6", node_type), ], keys.PROMOTE_ATTRIBUTES: [ ("Inner1.inputs:a", "inputs:value"), ("Inner3.outputs:sum", "outputs:one"), ("Inner4.outputs:sum", "outputs:two"), ], keys.CONNECT: [ ("Inner1.outputs:sum", "Inner2.inputs:b"), ("Inner2.outputs:sum", "Inner3.inputs:a"), ("Inner5.outputs:sum", "Inner6.inputs:a"), ], }, ), ], keys.CONNECT: [ ("Outer1.outputs:sum", "Compound.inputs:value"), ("Compound.outputs:one", "Outer2.inputs:a"), ], }, ) def assert_valid_traversal(items: List, expected_results: Set[og.Node]): """Helper method to validate traversal results.""" prims = [og.Controller.prim(i) for i in items] actual_set = traverse_upstream_graph(prims) self.assertEquals(expected_results, actual_set, "Unexpected set of visited nodes downstream") def assert_invalid_traversal(items): prims = [og.Controller.prim(i) for i in items] with self.assertRaises(og.OmniGraphError): traverse_upstream_graph(prims) compound_graph = nodes["Compound"].get_compound_graph_instance() # test traversal with compound graph assert_valid_traversal([nodes["Outer2"]], {nodes["Outer1"], nodes["Compound"], nodes["Outer2"]}) # test with just the compound graph assert_valid_traversal([compound_graph], {nodes["Inner1"], nodes["Inner2"], nodes["Inner3"], nodes["Inner4"]}) # test with a node inside the compound graph assert_valid_traversal([compound_graph, nodes["Inner6"]], set(compound_graph.get_nodes())) # invalid traversals assert_invalid_traversal([nodes["Inner1"], nodes["Outer2"]]) # mixed graphs assert_invalid_traversal([compound_graph, nodes["Outer2"]]) # compound and outer node assert_invalid_traversal(["/World"]) # invalid node assert_invalid_traversal(["/World/Testgraph"]) # non compound graph async def test_node_callback_works(self): """ Validate that the node predicate is applied correctly. """ stage = omni.usd.get_context().get_stage() # Test graph set up # [G1In1]-->[G1M1]-->[G1M2]--->[G1M4]--->[G1Out1] # [G1In2]---^ |---[G1M3]----| |--->[G1Out2] # # [G2In1]-->[G2M1]-->[G2Out1] # # [G3In1] controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("G1In1", "omni.graph.nodes.ConstantFloat"), ("G1In2", "omni.graph.nodes.ConstantFloat"), ("G1M1", "omni.graph.nodes.Add"), ("G1M2", "omni.graph.nodes.Add"), ("G1M3", "omni.graph.nodes.Add"), ("G1M4", "omni.graph.nodes.Add"), ("G1Out1", "omni.graph.nodes.Magnitude"), ("G1Out2", "omni.graph.nodes.Magnitude"), ("G2In1", "omni.graph.nodes.ConstantFloat"), ("G2M1", "omni.graph.nodes.Magnitude"), ("G2Out1", "omni.graph.nodes.Magnitude"), ("G3In1", "omni.graph.nodes.ConstantFloat"), ], keys.CONNECT: [ ("G1In1.inputs:value", "G1M1.inputs:a"), ("G1In2.inputs:value", "G1M1.inputs:b"), ("G1M1.outputs:sum", "G1M2.inputs:a"), ("G1M1.outputs:sum", "G1M2.inputs:b"), ("G1M1.outputs:sum", "G1M3.inputs:a"), ("G1M1.outputs:sum", "G1M3.inputs:b"), ("G1M2.outputs:sum", "G1M4.inputs:a"), ("G1M3.outputs:sum", "G1M4.inputs:b"), ("G1M4.outputs:sum", "G1Out1.inputs:input"), ("G1M4.outputs:sum", "G1Out2.inputs:input"), ("G2In1.inputs:value", "G2M1.inputs:input"), ("G2M1.outputs:magnitude", "G2Out1.inputs:input"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) _, _, _, _, g1m3, _, _, _, _, g2m1, _, _ = prims custom_accumulator = [] def convert_to_prim(node): """Convert the visited node to Prim""" nonlocal custom_accumulator custom_accumulator.append(og.Controller.prim(node)) # Validate the downstream traversal visited = traverse_downstream_graph([g2m1, g1m3], node_callback=convert_to_prim) expected = [og.Controller.prim(n) for n in visited] self.assertCountEqual( expected, custom_accumulator, "Unexpected effect of the node callback in downstream traversal" ) # Validate the upstream traversal custom_accumulator = [] visited = traverse_upstream_graph([g2m1, g1m3], node_callback=convert_to_prim) expected = [og.Controller.prim(n) for n in visited] self.assertCountEqual( expected, custom_accumulator, "Unexpected effect of the node callback in upstream traversal" ) async def test_attribute_predicate_works(self): """Validate that the attribute callback allows filtering connections""" stage = omni.usd.get_context().get_stage() # Test graph set up # [OnCustomEvent1]====>[Counter]==================>[Delay] # [OnCustomEvent2]=====^ |-->[Negate] ^ # [ConstantFloat]--| # Where # "==>" : execution connection # "-->" : data connection controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("OnCustomEvent1", "omni.graph.action.OnCustomEvent"), ("OnCustomEvent2", "omni.graph.action.OnCustomEvent"), ("Counter", "omni.graph.action.Counter"), ("Delay", "omni.graph.action.Delay"), ("Duration", "omni.graph.nodes.ConstantFloat"), ("Negate", "omni.graph.nodes.Negate"), ], keys.CONNECT: [ ("OnCustomEvent1.outputs:execOut", "Counter.inputs:execIn"), ("OnCustomEvent2.outputs:execOut", "Counter.inputs:reset"), ("Counter.outputs:execOut", "Delay.inputs:execIn"), ("Counter.outputs:count", "Negate.inputs:input"), ("Duration.inputs:value", "Delay.inputs:duration"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) on_custom_event1, on_custom_event2, counter, delay, _, _ = prims def is_execution(attr: og.Attribute) -> bool: return attr and attr.get_resolved_type().role == og.AttributeRole.EXECUTION visited = traverse_downstream_graph([on_custom_event1], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {on_custom_event1, counter, delay} self.assertSetEqual(expected, actual, "Unexpected sequence of nodes downstream") visited = traverse_upstream_graph([delay], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {delay, counter, on_custom_event1, on_custom_event2} self.assertSetEqual(expected, actual, "Unexpected sequence of nodes upstream") async def test_graph_with_cycles_works(self): """Validate that the traversal functions work on graphs with cycles / loops""" stage = omni.usd.get_context().get_stage() # Test graph set up # # [OnStageEvent]===>[ForLoop]<====================================== # | ||============>[Delay]========>[Branch]=|| # |--------------------->[Compare]--^ # [ConstantInt]------^ # # Where # "==>" : execution connection # "-->" : data connection controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("OnStageEvent", "omni.graph.action.OnStageEvent"), ("ForLoop", "omni.graph.action.ForLoop"), ("Delay", "omni.graph.action.Delay"), ("ConstantInt", "omni.graph.nodes.ConstantInt"), ("Compare", "omni.graph.nodes.Compare"), ("Branch", "omni.graph.action.Branch"), ], keys.CONNECT: [ ("OnStageEvent.outputs:execOut", "ForLoop.inputs:execIn"), ("ForLoop.outputs:loopBody", "Delay.inputs:execIn"), ("ForLoop.outputs:index", "Compare.inputs:a"), ("Delay.outputs:finished", "Branch.inputs:execIn"), ("ConstantInt.inputs:value", "Compare.inputs:b"), ("Compare.outputs:result", "Branch.inputs:condition"), ("Branch.outputs:execTrue", "ForLoop.inputs:breakLoop"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) on_stage_event, for_loop, delay, constant_int, _, branch = prims def is_execution(attr: og.Attribute) -> bool: return attr and attr.get_resolved_type().role == og.AttributeRole.EXECUTION visited = traverse_downstream_graph([delay], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {delay, branch, for_loop} self.assertSetEqual(expected, actual, "Unexpected sequence of nodes downstream") visited = traverse_upstream_graph([delay], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {delay, for_loop, branch, on_stage_event} self.assertSetEqual(expected, actual, "Unexpected sequence of nodes upstream") # The result of a traversal where the starting node has no matching attribute # is a set with only the node itself visited = traverse_downstream_graph([constant_int], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {constant_int} self.assertSetEqual(expected, actual, "Unexpected traversal when no connections are valid")
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_attribute_template_api.py
"""Tests related to the AttributeTemplate python APIs""" import tempfile from pathlib import Path from typing import Tuple import carb import numpy as np import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts import omni.graph.tools.ogn as ogn import omni.kit.test import omni.usd from pxr import Gf, Sdf, Vt # test data for metadata on attribute templates VALID_ATTRIBUTE_OGN_KEYS_AND_SAMPLES = { ogn.MetadataKeys.ALLOW_MULTI_INPUTS: "1", ogn.MetadataKeys.ALLOWED_TOKENS: "A,B,C", ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"A": "1", "B": "2", "C": "3"}', ogn.MetadataKeys.DESCRIPTION: "TestDescription", ogn.MetadataKeys.HIDDEN: "1", ogn.MetadataKeys.OPTIONAL: "1", ogn.MetadataKeys.OUTPUT_ONLY: "1", ogn.MetadataKeys.LITERAL_ONLY: "1", ogn.MetadataKeys.UI_NAME: "DisplayName", } class TestAttributeTemplateAPI(ogts.OmniGraphTestCase): """Tests that validate the attribute template API""" _simple_test_file = "TestCompoundGraph.usda" @classmethod def setUpClass(cls): # this is required when running a single test to make expectedError work correctly...not sure why carb.log_warn("This class expects error. This preflushes to avoid problems with ExpectedError") def validate_connections_match_usd(self, attribute: ogu.AttributeTemplate, path_to_rel: str): """ Helper that tests whether the connection list on the node type matches the corresponding USD relationship """ base_path = "/World/Compounds/TestType/Graph" stage = omni.usd.get_context().get_stage() relationship = stage.GetRelationshipAtPath(f"/World/Compounds/TestType.{path_to_rel}") self.assertTrue(relationship.IsValid()) # compare sets as the order isn't guaranteed attr_set = {Sdf.Path(f"{base_path}/{x}") for x in attribute.get_connections()} rel_set = set(relationship.GetTargets()) self.assertEqual(attr_set, rel_set) async def test_port_type_property(self): """ Tests the port type attribute on AttributeTemplates """ compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") for i in range(1, 20): compound_node_type.add_input(f"input_{i}", "int", True) compound_node_type.add_output(f"output_{i}", "float", True) for i in range(1, 20): input_type = compound_node_type.find_input(f"input_{i}") output_type = compound_node_type.find_output(f"output_{i}") self.assertEquals(input_type.port_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.assertEquals(output_type.port_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) async def test_extended_type_property(self): """ Test the attribute extended type property """ compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") regular_input = compound_node_type.add_input("input_0", "int", True, 1) union_input = compound_node_type.add_extended_input( "input_1", "int, float", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) any_input = compound_node_type.add_extended_input( "input_2", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) regular_output = compound_node_type.add_output("output_0", "int", True, 1) union_output = compound_node_type.add_extended_output( "output_1", "int, float", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) any_output = compound_node_type.add_extended_output( "output_2", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertTrue(regular_input.is_valid()) self.assertTrue(union_input.is_valid()) self.assertTrue(any_input.is_valid()) self.assertTrue(regular_output.is_valid()) self.assertTrue(union_output.is_valid()) self.assertTrue(any_output.is_valid()) self.assertEquals(regular_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR) self.assertEquals(union_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) self.assertEquals(any_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) self.assertEquals(regular_output.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR) self.assertEquals(union_output.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) self.assertEquals(any_output.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) async def test_get_types_method(self): """Test the get types methods returns the expected list values""" compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") regular_input = compound_node_type.add_input("input_0", "int", True, 1) union_input = compound_node_type.add_extended_input( "input_1", "int, float", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) any_input = compound_node_type.add_extended_input( "input_2", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) regular_output = compound_node_type.add_output("output_0", "float", True, 1) union_output = compound_node_type.add_extended_output( "output_1", "double[2], int[], normalf[3]", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) any_output = compound_node_type.add_extended_output( "output_2", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertTrue(regular_input.is_valid()) self.assertTrue(union_input.is_valid()) self.assertTrue(any_input.is_valid()) self.assertTrue(regular_output.is_valid()) self.assertTrue(union_output.is_valid()) self.assertTrue(any_output.is_valid()) self.assertEqual(regular_input.get_types(), [og.Type(og.BaseDataType.INT)]) self.assertEqual(regular_output.get_types(), [og.Type(og.BaseDataType.FLOAT)]) self.assertEqual(union_input.get_types(), [og.Type(og.BaseDataType.INT), og.Type(og.BaseDataType.FLOAT)]) self.assertEqual( union_output.get_types(), [ og.Type(og.BaseDataType.DOUBLE, 2), og.Type(og.BaseDataType.INT, 1, 1), og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.NORMAL), ], ) self.assertEqual(any_input.get_types(), []) self.assertEqual(any_output.get_types(), []) async def test_attribute_template_set_type(self): """Tests the set type and set extended type calls""" stage = omni.usd.get_context().get_stage() compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") prim = stage.GetPrimAtPath("/World/Compounds/TestType") regular_input = compound_node_type.add_input("input_0", "int", True, 1) regular_output = compound_node_type.add_output("output_0", "int", True, 2) input_rel = prim.GetRelationship("omni:graph:input:input_0") output_rel = prim.GetRelationship("omni:graph:output:output_0") self.assertTrue(regular_input.get_types(), [og.Type(og.BaseDataType.INT)]) self.assertTrue(regular_output.get_types(), [og.Type(og.BaseDataType.INT)]) self.assertTrue(input_rel.IsValid()) self.assertTrue(output_rel.IsValid()) self.assertEqual(input_rel.GetCustomDataByKey("omni:graph:default"), 1) self.assertEqual(output_rel.GetCustomDataByKey("omni:graph:default"), 2) # set to union or any type and validate the key is removed regular_input.set_extended_type(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, "numerics") regular_output.set_extended_type(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) self.assertEqual(regular_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) self.assertEqual(regular_output.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) self.assertGreater(len(regular_input.get_types()), 5) self.assertEqual(regular_output.get_types(), []) self.assertIsNone(input_rel.GetCustomDataByKey("omni:graph:default")) self.assertIsNone(output_rel.GetCustomDataByKey("omni:graph:default")) self.assertEqual(input_rel.GetCustomDataByKey("omni:graph:type"), "numerics") self.assertIsNone(output_rel.GetCustomDataByKey("omni:graph:type")) # validate setting a regular input with the wrong method has no effect with ogts.ExpectedError(): regular_input.set_extended_type(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "int") self.assertEqual(regular_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) regular_input.set_type(og.Type(og.BaseDataType.FLOAT, 3, 1), [(1, 2, 3), (4, 5, 6)]) self.assertEqual(regular_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR) self.assertEqual( input_rel.GetCustomDataByKey("omni:graph:default"), Vt.Vec3fArray([Gf.Vec3f(1, 2, 3), Gf.Vec3f(4, 5, 6)]) ) self.assertEqual(input_rel.GetCustomDataByKey("omni:graph:type"), "float[3][]") regular_output.set_type(og.Type(og.BaseDataType.FLOAT, 2)) self.assertEqual(output_rel.GetCustomDataByKey("omni:graph:default"), None) self.assertEqual(output_rel.GetCustomDataByKey("omni:graph:type"), "float[2]") async def test_connect_by_path(self): """Test the connect by path API call""" stage = omni.usd.get_context().get_stage() compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") prim = stage.GetPrimAtPath("/World/Compounds/TestType") graph_path = prim.GetPath().AppendChild("Graph") (_, (_add_node1, _add_node2), _, _) = og.Controller.edit( str(graph_path), {og.Controller.Keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add"), ("Add2", "omni.graph.nodes.Add")]}, ) node_path = graph_path.AppendChild("add_node") input_1 = compound_node_type.add_extended_input( "input_1", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) # invalid Paths will throw a value error with self.assertRaises(ValueError): input_1.connect_by_path(None) with self.assertRaises(ValueError): input_1.connect_by_path(2.0) with self.assertRaises(ValueError): input_1.connect_by_path("PATH WITH INVALID IDENTIFIERS - !@#$%^") # valid paths that are not part of the CNT graph produces errors and return false. with ogts.ExpectedError(): self.assertFalse(input_1.connect_by_path("/World")) # valid path, not part of the graph with ogts.ExpectedError(): self.assertFalse(input_1.connect_by_path(graph_path)) # valid SDFPath, not child of the graph full_attr_path = node_path.AppendProperty("inputs:a") rel_attr_path = "add.inputs:b" self.assertTrue(input_1.connect_by_path(full_attr_path)) self.assertTrue(input_1.connect_by_path(rel_attr_path)) self.assertEqual(len(input_1.get_connections()), 2) # existing connections don't append self.assertFalse(input_1.connect_by_path(node_path.AppendProperty("inputs:a"))) self.assertEqual(len(input_1.get_connections()), 2) output_1 = compound_node_type.add_extended_output( "output_1", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertTrue(output_1.connect_by_path(node_path.AppendProperty("outputs:sum"))) self.assertEqual(len(output_1.get_connections()), 1) self.assertTrue(output_1.connect_by_path("Add2.outputs:sum")) self.assertEqual(len(output_1.get_connections()), 1) self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") self.validate_connections_match_usd(output_1, "omni:graph:output:output_1") def create_test_node_with_input_and_output(self) -> Tuple[ogu.AttributeTemplate, ogu.AttributeTemplate]: """Creates a comound_node_type with two attributes with connections""" compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") graph_path = "/World/Compounds/TestType/Graph" (_, (_add_node1, _add_node2), _, _) = og.Controller.edit( graph_path, {og.Controller.Keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add"), ("Add2", "omni.graph.nodes.Add")]}, ) input_1 = compound_node_type.add_extended_input( "input_1", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertEqual(input_1.get_connections(), []) input_1.connect_by_path("/World/Compounds/TestType/Graph/Add.inputs:a") input_1.connect_by_path("Add.inputs:b") input_1.connect_by_path("Add2.inputs:a") input_1.connect_by_path("Add2.inputs:b") output_1 = compound_node_type.add_extended_output( "output_1", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertEqual(output_1.get_connections(), []) output_1.connect_by_path("Add.outputs:sum") return (input_1, output_1) async def test_get_connections(self): """ Test the get_connection member function returns the expected connection values """ (input_1, output_1) = self.create_test_node_with_input_and_output() self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") self.validate_connections_match_usd(output_1, "omni:graph:output:output_1") self.assertEqual(output_1.get_connections(), ["Add.outputs:sum"]) output_1.connect_by_path("Add2.outputs:sum") self.assertEqual(input_1.get_connections(), ["Add.inputs:a", "Add.inputs:b", "Add2.inputs:a", "Add2.inputs:b"]) self.assertEqual(output_1.get_connections(), ["Add2.outputs:sum"]) self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") self.validate_connections_match_usd(output_1, "omni:graph:output:output_1") async def test_disconnect_all(self): """Test the disconnect_all member function""" (input_1, output_1) = self.create_test_node_with_input_and_output() self.assertNotEqual(input_1.get_connections(), []) self.assertNotEqual(output_1.get_connections(), []) input_1.disconnect_all() self.assertEqual(input_1.get_connections(), []) input_1.disconnect_all() self.assertEqual(input_1.get_connections(), []) output_1.disconnect_all() self.assertEqual(output_1.get_connections(), []) self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") self.validate_connections_match_usd(output_1, "omni:graph:output:output_1") async def test_disconnect_by_path(self): """Tests disconnect_by_path API call""" (input_1, _) = self.create_test_node_with_input_and_output() self.assertEqual(len(input_1.get_connections()), 4) # non existing path self.assertFalse(input_1.disconnect_by_path("Add.omni:graph:input:not_valid")) # existing absolute path self.assertTrue(input_1.disconnect_by_path("/World/Compounds/TestType/Graph/Add.inputs:b")) self.assertTrue(input_1.disconnect_by_path("Add2.inputs:b")) self.assertEqual(input_1.get_connections(), ["Add.inputs:a", "Add2.inputs:a"]) self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") async def test_connections_are_set_when_loaded(self): """Tests that connections that are loaded from USD can be retrieved through the API""" (result, error) = await ogts.load_test_file(self._simple_test_file, use_caller_subdirectory=True) self.assertTrue(result, error) compound_node_type = ogu.find_compound_node_type_by_path("/World/Compounds/Compound") self.assertTrue(compound_node_type.is_valid()) input_a = compound_node_type.find_input("A") input_b = compound_node_type.find_input("B") output = compound_node_type.find_output("Value") self.assertTrue(input_a.is_valid()) self.assertTrue(input_b.is_valid()) self.assertTrue(output.is_valid()) self.assertEqual(input_a.get_connections(), ["Add_Node.inputs:a"]) self.assertEqual(input_b.get_connections(), ["Add_Node.inputs:b"]) self.assertEqual(output.get_connections(), ["Add_Node.outputs:sum"]) async def test_set_get_metadata(self): """Tests that validate the calls to set and retrieve metadata work as expected""" (input_1, output_1) = self.create_test_node_with_input_and_output() entries = VALID_ATTRIBUTE_OGN_KEYS_AND_SAMPLES for (key, value) in entries.items(): input_1.set_metadata(key, value) output_1.set_metadata(key, value) for (key, value) in entries.items(): self.assertTrue(input_1.get_metadata(key), value) self.assertTrue(output_1.get_metadata(key), value) # create a graph with the compound node and validate the values transfer (_, (node,), _, _) = og.Controller.edit( "/World/PushGraph", {og.Controller.Keys.CREATE_NODES: [("Node", "test.nodes.TestType")]} ) node_input = node.get_attribute("inputs:input_1") node_output = node.get_attribute("outputs:output_1") for (key, value) in entries.items(): self.assertEqual(node_input.get_metadata(key), value) self.assertEqual(node_output.get_metadata(key), value) async def test_set_get_metadata_reloads_from_file(self): """Tests that creating and setting metadata persists when the file reloads""" (input_1, output_1) = self.create_test_node_with_input_and_output() entries = VALID_ATTRIBUTE_OGN_KEYS_AND_SAMPLES for (key, value) in entries.items(): input_1.set_metadata(key, value) output_1.set_metadata(key, value) with tempfile.TemporaryDirectory() as tmpdirname: # save the file tmp_file_path = Path(tmpdirname) / "tmp.usda" result = omni.usd.get_context().save_as_stage(str(tmp_file_path)) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload the file back (result, error) = await ogts.load_test_file(str(tmp_file_path)) self.assertTrue(result, error) compound_node_type = ogu.find_compound_node_type_by_path("/World/Compounds/TestType") self.assertTrue(compound_node_type.is_valid()) input_1 = compound_node_type.find_input("input_1") output_1 = compound_node_type.find_output("output_1") self.assertTrue(input_1.is_valid()) self.assertTrue(output_1.is_valid()) for (key, value) in entries.items(): input_1.set_metadata(key, value) output_1.set_metadata(key, value) async def test_stress_test_add_input_output(self): """ Stress tests having many inputs and outputs on compound nodes. Validates that 'handles' maintain their correct object when internal movement of vectors is happening """ num_inputs = 1000 num_outputs = 1000 ogu.create_compound_node_type("TestType", "Graph", "test.nodes") node_type = og.get_node_type("test.nodes.TestType") self.assertTrue(node_type.is_valid()) compound_node_type = ogu.get_compound_node_type(node_type) self.assertTrue(compound_node_type.is_valid()) # build up a large number of inputs and outputs for i in range(0, num_inputs): compound_node_type.add_input(f"in_{i}", "int", True) for j in range(0, num_outputs): compound_node_type.add_output(f"out_{j}", "int", True) # validate the inputs and outputs return the correct object for i in range(0, num_inputs): input_attr = compound_node_type.find_input(f"in_{i}") self.assertTrue(input_attr.is_valid(), f"Failed at index {i}") self.assertEquals(input_attr.name, f"inputs:in_{i}") for j in range(0, num_outputs): output = compound_node_type.find_output(f"out_{j}") self.assertTrue(output.is_valid(), f"Failed at index {j}") self.assertEquals(output.name, f"outputs:out_{j}") # remove alternate inputs and outputs for i in range(1, num_inputs, 2): compound_node_type.remove_input_by_name(f"in_{i}") for j in range(1, num_outputs, 2): compound_node_type.remove_output_by_name(f"out_{j}") # verify everything is as expected. for i in range(0, num_inputs): input_attr = compound_node_type.find_input(f"in_{i}") if (i % 2) == 0: self.assertTrue(input_attr.is_valid(), f"Failed at index {i}") self.assertEquals(input_attr.name, f"inputs:in_{i}") else: self.assertFalse(input_attr.is_valid()) for j in range(0, num_outputs): output = compound_node_type.find_output(f"out_{j}") if (j % 2) == 0: self.assertTrue(output.is_valid(), f"Failed at index{j}") self.assertEquals(output.name, f"outputs:out_{j}") else: self.assertFalse(output.is_valid()) # ---------------------------------------------------------------------- async def test_default_data(self): """ Tests setting and getting default data through the attributetemplate ABI """ compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") name_index = 0 def validate_type(og_type, data): nonlocal name_index input_name = f"input_{name_index}" name_index = name_index + 1 attr_input = compound_node_type.add_input(input_name, og_type.get_ogn_type_name(), True, data) actual_data = attr_input.get_default_data() expected_data = data # special case for half floats where the precision can fail verify_values due to loss of precision if og_type.base_type == og.BaseDataType.HALF: if og_type.array_depth > 0 or og_type.tuple_count > 1: expected_data = np.array(np.array(data, dtype=np.float16), dtype=np.float32) else: expected_data = float(np.half(data)) ogts.verify_values( expected_data, actual_data, f"Comparison failed {str(actual_data)} vs {str(expected_data)}" ) validate_type(og.Type(og.BaseDataType.BOOL), True) validate_type(og.Type(og.BaseDataType.BOOL), False) validate_type(og.Type(og.BaseDataType.BOOL, 1, 1), [True, False]) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.COLOR), (1, 0, 0)) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 1, og.AttributeRole.COLOR), [(1, 0, 0), (0, 1, 0)]) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.COLOR), (1, 0, 0)) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.COLOR), [(1, 0, 0), (0, 1, 0)]) validate_type(og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.COLOR), (1, 0, 0)) validate_type(og.Type(og.BaseDataType.HALF, 3, 1, og.AttributeRole.COLOR), [(1, 0, 0), (0, 1, 0)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.COLOR), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 1, og.AttributeRole.COLOR), [(1, 0, 0, 1), (0, 1, 1, 0)]) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 0, og.AttributeRole.COLOR), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 1, og.AttributeRole.COLOR), [(1, 0, 0, 1), (0, 1, 1, 0)]) validate_type(og.Type(og.BaseDataType.HALF, 4, 0, og.AttributeRole.COLOR), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.HALF, 4, 1, og.AttributeRole.COLOR), [(1, 0, 0, 1), (0, 1, 1, 0)]) validate_type(og.Type(og.BaseDataType.DOUBLE), 1.5) validate_type(og.Type(og.BaseDataType.DOUBLE, 2), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.DOUBLE, 2, 1), [(1.5, 1.6), (2.5, 2.6)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 3), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 1), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 4), (1.5, 1.6, 1.7, 1.8)) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 1), [(1.5, 1.6, 1.7, 1.8), (2.5, 2.6, 2.7, 2.8)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 1, 1), [1.5, 1.6, 1.7]) validate_type(og.Type(og.BaseDataType.FLOAT), 1.5) validate_type(og.Type(og.BaseDataType.FLOAT, 2), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.FLOAT, 2, 1), [(1.5, 1.6), (2.5, 2.6)]) validate_type(og.Type(og.BaseDataType.FLOAT, 3), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 1), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.FLOAT, 4), (1.5, 1.6, 1.7, 1.8)) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 1), [(1.5, 1.6, 1.7, 1.8), (2.5, 2.6, 2.7, 2.8)]) validate_type(og.Type(og.BaseDataType.FLOAT, 1, 1), [1.5, 1.6, 1.7]) validate_type( og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.FRAME), ((1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3), (4, 0, 0, 4)), ) validate_type( og.Type(og.BaseDataType.DOUBLE, 16, 1, og.AttributeRole.FRAME), [ ((1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3), (4, 0, 0, 4)), ((5, 0, 0, 5), (6, 0, 0, 6), (7, 0, 0, 7), (8, 0, 0, 8)), ], ) validate_type(og.Type(og.BaseDataType.HALF), 1.5) validate_type(og.Type(og.BaseDataType.HALF, 2), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.HALF, 2, 1), [(1.5, 1.6), (2.5, 2.6)]) validate_type(og.Type(og.BaseDataType.HALF, 3), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.HALF, 3, 1), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.HALF, 4), (1.5, 1.6, 1.7, 1.8)) validate_type(og.Type(og.BaseDataType.HALF, 4, 1), [(1.5, 1.6, 1.7, 1.8), (2.5, 2.6, 2.7, 2.8)]) validate_type(og.Type(og.BaseDataType.HALF, 1, 1), [1.5, 1.6, 1.7]) validate_type(og.Type(og.BaseDataType.INT), 1) validate_type(og.Type(og.BaseDataType.INT, 2), (1, 2)) validate_type(og.Type(og.BaseDataType.INT, 2, 1), [(1, 2), (3, 4)]) validate_type(og.Type(og.BaseDataType.INT, 3), (1, 2, 3)) validate_type(og.Type(og.BaseDataType.INT, 3, 1), [(1, 2, 3), (3, 4, 5)]) validate_type(og.Type(og.BaseDataType.INT, 4), (1, 2, 3, 4)) validate_type(og.Type(og.BaseDataType.INT, 4, 1), [(1, 2, 3, 4), (3, 4, 5, 6)]) validate_type(og.Type(og.BaseDataType.INT64), 123456789012) validate_type(og.Type(og.BaseDataType.INT64, 1, 1), [123456789012, 345678901234]) validate_type(og.Type(og.BaseDataType.INT, 1, 1), [1, 2, 3, 4, 5, 6]) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.MATRIX), ((1, 2), (3, 4))) validate_type( og.Type(og.BaseDataType.DOUBLE, 4, 1, og.AttributeRole.MATRIX), [((1, 2), (3, 4)), ((5, 6), (7, 8))] ) validate_type(og.Type(og.BaseDataType.DOUBLE, 9, 0, og.AttributeRole.MATRIX), ((1, 2, 3), (4, 5, 6), (7, 8, 9))) validate_type( og.Type(og.BaseDataType.DOUBLE, 9, 1, og.AttributeRole.MATRIX), [((1, 2, 3), (4, 5, 6), (7, 8, 9)), ((0, 1, 2), (3, 4, 5), (6, 7, 8))], ) validate_type( og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX), ((1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3), (4, 0, 0, 4)), ) validate_type( og.Type(og.BaseDataType.DOUBLE, 16, 1, og.AttributeRole.MATRIX), [ ((1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3), (4, 0, 0, 4)), ((5, 0, 0, 5), (6, 0, 0, 6), (7, 0, 0, 7), (8, 0, 0, 8)), ], ) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.NORMAL), (0, 1, 0)) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 1, og.AttributeRole.NORMAL), [(1, 0.0, 0.0), (0, 1, 0.0)]) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.NORMAL), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.NORMAL), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.NORMAL), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.HALF, 3, 1, og.AttributeRole.NORMAL), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.POSITION), (1.5, 1.6, 1.7)) validate_type( og.Type(og.BaseDataType.DOUBLE, 3, 1, og.AttributeRole.POSITION), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)] ) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.POSITION), (1.5, 1.6, 1.7)) validate_type( og.Type(og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.POSITION), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)] ) validate_type(og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.POSITION), (1.5, 1.6, 1.7)) validate_type( og.Type(og.BaseDataType.HALF, 3, 1, og.AttributeRole.POSITION), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)] ) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.QUATERNION), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 1, og.AttributeRole.QUATERNION), [(1, 0, 0, 1), (0, 1, 0, 1)]) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 0, og.AttributeRole.QUATERNION), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 1, og.AttributeRole.QUATERNION), [(1, 0, 0, 1), (0, 1, 0, 1)]) validate_type(og.Type(og.BaseDataType.HALF, 4, 0, og.AttributeRole.QUATERNION), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.HALF, 4, 1, og.AttributeRole.QUATERNION), [(1, 0, 0, 1), (0, 1, 0, 1)]) validate_type(og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.TEXT), "text") validate_type(og.Type(og.BaseDataType.DOUBLE, 2, 0, og.AttributeRole.TEXCOORD), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.DOUBLE, 2, 1, og.AttributeRole.TEXCOORD), [(1.5, 1.6), (2.5, 2.6)]) validate_type(og.Type(og.BaseDataType.FLOAT, 2, 0, og.AttributeRole.TEXCOORD), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.FLOAT, 2, 1, og.AttributeRole.TEXCOORD), [(1.5, 1.6), (2.5, 2.6)])
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_auto_instancing.py
""" Tests for omnigraph instancing """ import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from pxr import OmniGraphSchemaTools, Sdf # ====================================================================== class TestAutoInstancing(ogts.OmniGraphTestCase): async def setUp(self): await super().setUp() timeline = omni.timeline.get_timeline_interface() timeline.set_fast_mode(True) # ---------------------------------------------------------------------- async def tick(self): # Auto instance merging happens globaly before any compute takes place, # but the decision of asking to be merged is a per-graph thing that can happen # at the beggining of each graph compute, when the pipeline is already running # So we need 2 frames in those tests to ensure that merging actually happens await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # ---------------------------------------------------------------------- def create_simple_graph(self, graph_path, prim_path, value: int): controller = og.Controller() keys = og.Controller.Keys # +------------+ +------------+ # | NewBundle |======>| InsertAttr | # +------------+ | | # ===>|val | # | +------------+ # | # | +---------------+ # | | WritePrimAttr | # +------+ | | | # |Const |=======>|value | # +------+ | | # | | # +------+ | | # |Const |=======>|path | # +------+ | | # | | # +------------+ | | # |ReadVariable|=======>|name | # +------------+ +---------------+ # # +--------------+ # |Tutorial State| # +--------------+ # The tutorial state allows to exercise internal states when using auto instancing # it does not need any connection to validate that it works as expected # create the target prim stage = omni.usd.get_context().get_stage() prim = stage.DefinePrim(prim_path) prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output2", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output3", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output4", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output5", Sdf.ValueTypeNames.Int).Set(0) # create the graph (graph, _, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("Path", "omni.graph.nodes.ConstantToken"), ("Value", "omni.graph.nodes.ConstantInt"), ("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"), ("State", "omni.graph.tutorials.State"), ("NewBundle", "omni.graph.nodes.BundleConstructor"), ("Insert", "omni.graph.nodes.InsertAttribute"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "WritePrimAttr.inputs:name"), ("Path.inputs:value", "WritePrimAttr.inputs:primPath"), ("Value.inputs:value", "WritePrimAttr.inputs:value"), ("NewBundle.outputs_bundle", "Insert.inputs:data"), ("Value.inputs:value", "Insert.inputs:attrToInsert"), ], keys.CREATE_VARIABLES: [ ("attrib_name", og.Type(og.BaseDataType.TOKEN)), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "attrib_name"), ("WritePrimAttr.inputs:usePath", True), ("Path.inputs:value", prim_path), ("Value.inputs:value", value), ("Insert.inputs:outputAttrName", "value"), ], }, ) # set the variable default value var = graph.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output") return graph # ---------------------------------------------------------------------- def create_instance_graph(self, graph_path, prim_root_path, inst_count, value: int): controller = og.Controller() keys = og.Controller.Keys # +------------+ +------------+ # | NewBundle |======>| InsertAttr | # +------------+ | | # ===>|val | # | +------------+ # | # | +---------------+ # | | WritePrimAttr | # +------+ | | | # |Const |=======>|value | # +------+ | | # | | # +------------+ | | # |GraphTarget |======>|path | # +------------+ | | # | | # +------------+ | | # |ReadVariable|=======>|name | # +------------+ +---------------+ # # +--------------+ # |Tutorial State| # +--------------+ (graph, _, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("Target", "omni.graph.nodes.GraphTarget"), ("Value", "omni.graph.nodes.ConstantInt"), ("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"), ("State", "omni.graph.tutorials.State"), ("NewBundle", "omni.graph.nodes.BundleConstructor"), ("Insert", "omni.graph.nodes.InsertAttribute"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "WritePrimAttr.inputs:name"), ("Target.outputs:primPath", "WritePrimAttr.inputs:primPath"), ("Value.inputs:value", "WritePrimAttr.inputs:value"), ("NewBundle.outputs_bundle", "Insert.inputs:data"), ("Value.inputs:value", "Insert.inputs:attrToInsert"), ], keys.CREATE_VARIABLES: [ ("attrib_name", og.Type(og.BaseDataType.TOKEN)), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "attrib_name"), ("WritePrimAttr.inputs:usePath", True), ("Value.inputs:value", value), ("Insert.inputs:outputAttrName", "value"), ], }, ) # set the variable default value var = graph.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output") # create instances stage = omni.usd.get_context().get_stage() for i in range(0, inst_count): prim_name = f"{prim_root_path}_{i}" prim = stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, graph_path) prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output2", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output3", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output4", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output5", Sdf.ValueTypeNames.Int).Set(0) return graph # ---------------------------------------------------------------------- async def setup_stage(self, use_usd, use_og_inst): stage = omni.usd.get_context().get_stage() inst_count = 4 int_range = range(1, 10) if use_usd: # main template main_template_path = "/World/Template" main_template_prim = f"{main_template_path}/Prim" main_template_graph = f"{main_template_path}/Graph" if use_og_inst: graph = self.create_instance_graph(main_template_graph, main_template_prim, inst_count, 1) else: graph = self.create_simple_graph(main_template_graph, main_template_prim, 1) for i in int_range: smart_asset_path = f"/World/SmartAsset_{i}" instance_prim = stage.DefinePrim(smart_asset_path) instance_prim.GetReferences().AddReference("", main_template_path) # give a chance to the graph to be created await self.tick() # setup the overs for i in int_range: smart_asset_path = f"/World/SmartAsset_{i}" # keep the first value inherited from template if i != 1: attr = stage.GetPrimAtPath(f"{smart_asset_path}/Graph/Value").GetAttribute("inputs:value") attr.Set(i) if use_og_inst is False: attr = stage.GetPrimAtPath(f"{smart_asset_path}/Graph/Path").GetAttribute("inputs:value") attr.Set(f"/World/SmartAsset_{i}/Prim") else: for i in int_range: if use_og_inst: graph = self.create_instance_graph(f"/World/TestGraph_{i}", f"/World/Prim_{i}", inst_count, i) else: graph = self.create_simple_graph(f"/World/TestGraph_{i}", f"/World/Prim_{i}", i) return graph # ---------------------------------------------------------------------- def validate_results_and_reset( self, use_usd: bool, use_og_inst: bool, output: str = "graph_output", first_sa: int = 1, last_sa: int = 10, first_og_inst: int = 0, last_og_inst: int = 4, mult: int = 1, ): if use_usd: graph_path = "/World/SmartAsset_{asset}/Graph" base_path = "/World/SmartAsset_{asset}/Prim" base_path_og = "/World/SmartAsset_{asset}/Prim_{inst}" else: graph_path = "/World/TestGraph_{asset}" base_path = "/World/Prim_{asset}" base_path_og = "/World/Prim_{asset}_{inst}" # for internals states checks: # all graph instances must have a different hundreds (ie. each has its own state) # all graph instances must have a same mode 100 (ie. each one has executed against its own state) state_hundreds_last_val = -1 state_last_mod100 = -1 stage = omni.usd.get_context().get_stage() found_master_sa = False for i in range(first_sa, last_sa): graph = og.Controller.graph(graph_path.format(asset=i)) state_out = og.Controller.attribute(graph_path.format(asset=i) + "/State.outputs:monotonic") insert_node = og.Controller.node(graph_path.format(asset=i) + "/Insert") self.assertTrue(graph.is_auto_instanced()) inst_count = graph.get_instance_count() if use_og_inst: if found_master_sa: self.assertTrue(inst_count == 4) else: if inst_count != 4: self.assertTrue(inst_count == 36) found_master_sa = True for j in range(first_og_inst, last_og_inst): prim_path = base_path_og.format(asset=i, inst=j) attr = stage.GetPrimAtPath(prim_path).GetAttribute(output) self.assertEqual(attr.Get(), i * mult) attr.Set(0) state_val = state_out.get(instance=j) self.assertNotEqual(state_val // 100, state_hundreds_last_val) state_hundreds_last_val = state_val // 100 if state_last_mod100 != -1: self.assertEqual(state_val % 100, state_last_mod100) state_last_mod100 = state_val % 100 bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data", j) bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), i * mult) else: if found_master_sa: self.assertTrue(inst_count == 0) else: if inst_count != 0: self.assertTrue(inst_count == 9) found_master_sa = True prim_path = base_path.format(asset=i) attr = stage.GetPrimAtPath(prim_path).GetAttribute(output) self.assertEqual(attr.Get(), i * mult) attr.Set(0) state_val = state_out.get() self.assertNotEqual(state_val // 100, state_hundreds_last_val) state_hundreds_last_val = state_val // 100 if state_last_mod100 != -1: self.assertEqual(state_val % 100, state_last_mod100) state_last_mod100 = state_val % 100 bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data") bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), i * mult) # ---------------------------------------------------------------------- async def test_auto_instance_no_usd_without_og_instancing(self): # Tests that we get a vectorized compute in smart asset situation await self.setup_stage(False, False) await self.tick() self.validate_results_and_reset(False, False) # ---------------------------------------------------------------------- async def test_auto_instance_no_usd_with_og_instancing(self): # Tests that we get a vectorized compute in smart asset situation where asset have OG instancing await self.setup_stage(False, True) await self.tick() self.validate_results_and_reset(False, True) # ---------------------------------------------------------------------- async def test_auto_instance_usd_without_og_instancing(self): # Tests that we get a vectorized compute in smart asset situation await self.setup_stage(True, False) await self.tick() self.validate_results_and_reset(True, False) # ---------------------------------------------------------------------- async def test_auto_instance_usd_with_og_instancing(self): # Tests that we get a vectorized compute in smart asset situation where asset have OG instancing await self.setup_stage(True, True) await self.tick() self.validate_results_and_reset(True, True) # ---------------------------------------------------------------------- async def test_auto_instance_variable_without_og_instancing(self): # Tests that variable changes are taken into account template = await self.setup_stage(True, False) # set the template to write to 2nd output var = template.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output2") await self.tick() self.validate_results_and_reset(True, False, "graph_output2") # change them 1 by 1 to write to 1st output for i in range(1, 10): graph = og.Controller.graph(f"/World/SmartAsset_{i}/Graph") var = graph.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output3") await self.tick() self.validate_results_and_reset(True, False, "graph_output3", 1, i + 1) if i != 9: self.validate_results_and_reset(True, False, "graph_output2", i + 1, 10) # ---------------------------------------------------------------------- async def test_auto_instance_variable_with_og_instancing(self): # Tests that variable changes are taken into account stage = omni.usd.get_context().get_stage() template = await self.setup_stage(True, True) await self.tick() self.validate_results_and_reset(True, True, "graph_output") # set the template to write to out2 template_var = template.find_variable("attrib_name") og.Controller.set_variable_default_value(template_var, "graph_output2") await self.tick() self.validate_results_and_reset(True, True, "graph_output2") # change first half of the OG template instances to write to out3 for i in range(0, 2): prim_path = f"/World/Template/Prim_{i}" prim = stage.GetPrimAtPath(prim_path) variable = prim.CreateAttribute("graph:variable:attrib_name", Sdf.ValueTypeNames.Token) variable.Set("graph_output3") await self.tick() self.validate_results_and_reset(True, True, "graph_output3", 1, 10, 0, 2) self.validate_results_and_reset(True, True, "graph_output2", 1, 10, 2, 4) # override half SA/Graph to write to out4 for i in range(1, 5): graph = og.Controller.graph(f"/World/SmartAsset_{i}/Graph") var = graph.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output4") await self.tick() # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 1, 5, 0, 2) # COMES FROM: SA/Graph self.validate_results_and_reset(True, True, "graph_output4", 1, 5, 2, 4) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 5, 10, 0, 2) # COMES FROM: Template/Graph self.validate_results_and_reset(True, True, "graph_output2", 5, 10, 2, 4) # Apply SA/OG_inst override to all known provenance for i in [1, 2, 5, 6]: for j in [0, 2]: prim_path = f"/World/SmartAsset_{i}/Prim_{j}" prim = stage.GetPrimAtPath(prim_path) variable = prim.CreateAttribute("graph:variable:attrib_name", Sdf.ValueTypeNames.Token) variable.Set("graph_output5") await self.tick() # COMES FROM: SA/OG_inst self.validate_results_and_reset(True, True, "graph_output5", 1, 3, 0, 1) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 1, 3, 1, 2) # COMES FROM: SA/OG_inst self.validate_results_and_reset(True, True, "graph_output5", 1, 3, 2, 3) # COMES FROM: SA/Graph self.validate_results_and_reset(True, True, "graph_output4", 1, 3, 3, 4) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 3, 5, 0, 2) # COMES FROM: SA/Graph self.validate_results_and_reset(True, True, "graph_output4", 3, 5, 2, 4) # COMES FROM: SA/OG_inst self.validate_results_and_reset(True, True, "graph_output5", 5, 7, 0, 1) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 5, 7, 1, 2) # COMES FROM: SA/OG_inst self.validate_results_and_reset(True, True, "graph_output5", 5, 7, 2, 3) # COMES FROM: Template/Graph self.validate_results_and_reset(True, True, "graph_output2", 5, 7, 3, 4) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 7, 10, 0, 2) # COMES FROM: Template/Graph self.validate_results_and_reset(True, True, "graph_output2", 7, 10, 2, 4) # ---------------------------------------------------------------------- async def test_auto_instance_value_without_og_instancing(self): # Tests that value changes are taken into account stage = omni.usd.get_context().get_stage() await self.setup_stage(True, False) await self.tick() self.validate_results_and_reset(True, False) for i in range(1, 5): smart_asset_path = f"/World/SmartAsset_{i}" attr = stage.GetPrimAtPath(f"{smart_asset_path}/Graph/Value").GetAttribute("inputs:value") attr.Set(i * 10) await self.tick() self.validate_results_and_reset(True, False, "graph_output", 1, 5, mult=10) self.validate_results_and_reset(True, False, "graph_output", 5, 10) # same, but through OG directly for i in range(1, 5): smart_asset_path = f"/World/SmartAsset_{i}" attr = og.Controller.attribute(f"{smart_asset_path}/Graph/Value.inputs:value") attr.set(i * 20) await self.tick() self.validate_results_and_reset(True, False, "graph_output", 1, 5, mult=20) self.validate_results_and_reset(True, False, "graph_output", 5, 10) # ---------------------------------------------------------------------- async def test_auto_instance_value_with_og_instancing(self): # Tests that a value change is taken into account stage = omni.usd.get_context().get_stage() await self.setup_stage(True, True) await self.tick() self.validate_results_and_reset(True, True) for i in range(1, 5): smart_asset_path = f"/World/SmartAsset_{i}" attr = stage.GetPrimAtPath(f"{smart_asset_path}/Graph/Value").GetAttribute("inputs:value") attr.Set(i * 10) await self.tick() self.validate_results_and_reset(True, True, "graph_output", 1, 5, mult=10) self.validate_results_and_reset(True, True, "graph_output", 5, 10) # same, but through OG directly for i in range(1, 5): smart_asset_path = f"/World/SmartAsset_{i}" attr = og.Controller.attribute(f"{smart_asset_path}/Graph/Value.inputs:value") attr.set(i * 20) await self.tick() self.validate_results_and_reset(True, True, "graph_output", 1, 5, mult=20) self.validate_results_and_reset(True, True, "graph_output", 5, 10) # ---------------------------------------------------------------------- def _check_value_and_reset(self, val1, val2, with_inst): stage = omni.usd.get_context().get_stage() states_out = [ og.Controller.attribute("/World/Graph1/State.outputs:monotonic"), og.Controller.attribute("/World/Graph2/State.outputs:monotonic"), ] # for internals states checks: # all graph instances must have a different hundreds (ie. each has its own state) # all graph instances must have a same mode 100 (ie. each one has executed against its own state) state_hundreds_last_val = -1 state_last_mod100 = -1 if with_inst: for i in range(0, 4): attr = stage.GetPrimAtPath(f"/World/Prim1_{i}").GetAttribute("graph_output") self.assertEqual(attr.Get(), val1) attr.Set(0) attr = stage.GetPrimAtPath(f"/World/Prim2_{i}").GetAttribute("graph_output") self.assertEqual(attr.Get(), val2) attr.Set(0) for state_out in states_out: state_val = state_out.get(instance=i) self.assertNotEqual(state_val // 100, state_hundreds_last_val) state_hundreds_last_val = state_val // 100 if state_last_mod100 != -1: self.assertEqual(state_val % 100, state_last_mod100) state_last_mod100 = state_val % 100 # bundle for graph 1 graph = og.Controller.graph("/World/Graph1") insert_node = og.Controller.node("/World/Graph1/Insert") bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data", i) bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), val1) # bundle for graph 2 graph = og.Controller.graph("/World/Graph2") insert_node = og.Controller.node("/World/Graph2/Insert") bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data", i) bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), val2) else: attr = stage.GetPrimAtPath("/World/Prim1").GetAttribute("graph_output") self.assertEqual(attr.Get(), val1) attr.Set(0) attr = stage.GetPrimAtPath("/World/Prim2").GetAttribute("graph_output") self.assertEqual(attr.Get(), val2) attr.Set(0) for state_out in states_out: state_val = state_out.get() self.assertNotEqual(state_val // 100, state_hundreds_last_val) state_hundreds_last_val = state_val // 100 if state_last_mod100 != -1: self.assertEqual(state_val % 100, state_last_mod100) state_last_mod100 = state_val % 100 # bundle for graph 1 graph = og.Controller.graph("/World/Graph1") insert_node = og.Controller.node("/World/Graph1/Insert") bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data") bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), val1) # bundle for graph 2 graph = og.Controller.graph("/World/Graph2") insert_node = og.Controller.node("/World/Graph2/Insert") bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data") bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), val2) # ---------------------------------------------------------------------- async def _change_check_reset(self, val1, val2, with_inst, with_usd): if with_usd: stage = omni.usd.get_context().get_stage() val_g1 = stage.GetPrimAtPath("/World/Graph1/Value").GetAttribute("inputs:value") val_g2 = stage.GetPrimAtPath("/World/Graph2/Value").GetAttribute("inputs:value") val_g1.Set(val1) val_g2.Set(val2) else: val_g1 = og.Controller.attribute("/World/Graph1/Value.inputs:value") val_g2 = og.Controller.attribute("/World/Graph2/Value.inputs:value") val_g1.set(val1) val_g2.set(val2) await self.tick() self._check_value_and_reset(val1, val2, with_inst) # ---------------------------------------------------------------------- async def _instantiation_test(self, use_og_inst): # create the graphs if use_og_inst: inst_count = 4 graph1 = self.create_instance_graph("/World/Graph1", "/World/Prim1", inst_count, 1) graph2 = self.create_instance_graph("/World/Graph2", "/World/Prim2", inst_count, 2) else: inst_count = 0 graph1 = self.create_simple_graph("/World/Graph1", "/World/Prim1", 1) graph2 = self.create_simple_graph("/World/Graph2", "/World/Prim2", 2) # add a variable to the first one graph1.create_variable("_tmp_", og.Type(og.BaseDataType.TOKEN)) # run a frame await self.tick() # check that the call was not vectorized self.assertFalse(graph1.is_auto_instanced()) self.assertTrue(graph1.get_instance_count() == inst_count) self.assertFalse(graph2.is_auto_instanced()) self.assertTrue(graph2.get_instance_count() == inst_count) # check results self._check_value_and_reset(1, 2, use_og_inst) # change values await self._change_check_reset(3, 4, use_og_inst, True) await self._change_check_reset(5, 6, use_og_inst, False) # add the same variable to graph2 graph2.create_variable("_tmp_", og.Type(og.BaseDataType.TOKEN)) # run a frame await self.tick() # check that the call is now vectorized self.assertTrue(graph1.is_auto_instanced()) self.assertTrue(graph2.is_auto_instanced()) ic1 = graph1.get_instance_count() ic2 = graph2.get_instance_count() if use_og_inst: self.assertTrue( (ic1 == 2 * inst_count and ic2 == inst_count) or (ic1 == inst_count and ic2 == 2 * inst_count) ) else: self.assertTrue((ic1 == 2 and ic2 == 0) or (ic1 == 0 and ic2 == 2)) # check results self._check_value_and_reset(5, 6, use_og_inst) # change values await self._change_check_reset(7, 8, use_og_inst, True) await self._change_check_reset(9, 10, use_og_inst, False) # force each graph to not use auto instancing for g in [graph1, graph2]: g.set_auto_instancing_allowed(False) await self.tick() # check that the call was not vectorized self.assertFalse(graph1.is_auto_instanced()) self.assertTrue(graph1.get_instance_count() == inst_count) self.assertFalse(graph2.is_auto_instanced()) self.assertTrue(graph2.get_instance_count() == inst_count) # check that it works # this also validates that the graph/bundle data has been properly migrated between master/slave self._check_value_and_reset(9, 10, use_og_inst) # change values await self._change_check_reset(11, 12, use_og_inst, True) await self._change_check_reset(13, 14, use_og_inst, False) # activate back auto instancing g.set_auto_instancing_allowed(True) await self.tick() # check that the call is now vectorized self.assertTrue(graph1.is_auto_instanced()) self.assertTrue(graph2.is_auto_instanced()) ic1 = graph1.get_instance_count() ic2 = graph2.get_instance_count() if use_og_inst: self.assertTrue( (ic1 == 2 * inst_count and ic2 == inst_count) or (ic1 == inst_count and ic2 == 2 * inst_count) ) else: self.assertTrue((ic1 == 2 and ic2 == 0) or (ic1 == 0 and ic2 == 2)) # check that it works self._check_value_and_reset(13, 14, use_og_inst) # change values await self._change_check_reset(15, 16, use_og_inst, True) # back to initial value (for next loop or next test) await self._change_check_reset(9, 10, use_og_inst, False) # add a new variable to graph1 graph1.create_variable("_tmp2_", og.Type(og.BaseDataType.TOKEN)) # run a frame await self.tick() # check that the call is now back to non-vectorized self.assertFalse(graph1.is_auto_instanced()) self.assertTrue(graph1.get_instance_count() == inst_count) self.assertFalse(graph2.is_auto_instanced()) self.assertTrue(graph2.get_instance_count() == inst_count) # check results self._check_value_and_reset(9, 10, use_og_inst) # change values await self._change_check_reset(11, 12, use_og_inst, True) await self._change_check_reset(13, 14, use_og_inst, False) # ---------------------------------------------------------------------- async def test_auto_instance_instantiation_without_og_instancing(self): # Tests that a graph modification can make it an auto instance await self._instantiation_test(False) # ---------------------------------------------------------------------- async def test_auto_instance_instantiation_with_og_instancing(self): # Tests that a graph modification can (un)make it an auto instance await self._instantiation_test(True) # ---------------------------------------------------------------------- async def test_auto_instance_signature_same_attrib(self): # Tests that 2 graphs that have a node with same attribute names don't get merged # the BooleanOr and BoolenAnd node has the same set of attributes: # inputs:a, inputs:b and outputs:result # 2 different graphs with the same topology but different nodes shouldn't get merged controller = og.Controller() keys = og.Controller.Keys # create the graphs (graph1, _, _, _) = controller.edit( "/World/TestGraph1", { keys.CREATE_NODES: [ ("/World/TestGraph1/Operation", "omni.graph.nodes.BooleanOr"), ], keys.SET_VALUES: [ ("/World/TestGraph1/Operation.inputs:a", {"type": "bool", "value": False}), ("/World/TestGraph1/Operation.inputs:b", {"type": "bool", "value": True}), ], }, ) (graph2, _, _, _) = controller.edit( "/World/TestGraph2", { keys.CREATE_NODES: [ ("/World/TestGraph2/Operation", "omni.graph.nodes.BooleanAnd"), ], keys.SET_VALUES: [ ("/World/TestGraph2/Operation.inputs:a", {"type": "bool", "value": False}), ("/World/TestGraph2/Operation.inputs:b", {"type": "bool", "value": True}), ], }, ) # run a frame await self.tick() # check results self.assertFalse(graph1.is_auto_instanced()) self.assertFalse(graph2.is_auto_instanced()) self.assertEqual(controller.attribute("/World/TestGraph1/Operation.outputs:result").get(), True) self.assertEqual(controller.attribute("/World/TestGraph2/Operation.outputs:result").get(), False) # ---------------------------------------------------------------------- async def test_auto_instance_signature_different_connection(self): # Tests that 2 graphs that have the same set of attributes with different connections don't get merged controller = og.Controller() keys = og.Controller.Keys # create the graphs (graph1, _, _, _) = controller.edit( "/World/TestGraph1", { keys.CREATE_NODES: [ ("Sub", "omni.graph.nodes.Subtract"), ("C1", "omni.graph.nodes.ConstantDouble"), ("C2", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("C1.inputs:value", "Sub.inputs:a"), ("C2.inputs:value", "Sub.inputs:b"), ], keys.SET_VALUES: [ ("C1.inputs:value", 10), ("C2.inputs:value", 5), ], }, ) # connected the other way around (graph2, _, _, _) = controller.edit( "/World/TestGraph2", { keys.CREATE_NODES: [ ("/World/TestGraph2/Sub", "omni.graph.nodes.Subtract"), ("/World/TestGraph2/C1", "omni.graph.nodes.ConstantDouble"), ("/World/TestGraph2/C2", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("/World/TestGraph2/C1.inputs:value", "/World/TestGraph2/Sub.inputs:b"), ("/World/TestGraph2/C2.inputs:value", "/World/TestGraph2/Sub.inputs:a"), ], keys.SET_VALUES: [ ("/World/TestGraph2/C1.inputs:value", 10), ("/World/TestGraph2/C2.inputs:value", 5), ], }, ) # run a frame await self.tick() # check results self.assertFalse(graph1.is_auto_instanced()) self.assertFalse(graph2.is_auto_instanced()) self.assertEqual(controller.attribute("/World/TestGraph1/Sub.outputs:difference").get(), 5) self.assertEqual(controller.attribute("/World/TestGraph2/Sub.outputs:difference").get(), -5)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_compound_nodes.py
# noqa: PLC0302 import itertools import math import os import re import tempfile from typing import List, Tuple import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts import omni.graph.tools.ogn as ogn import omni.kit.test import omni.usd from pxr import OmniGraphSchema, Sdf DESCRIPTION_METADATA_KEY = f"omni:graph:{ogn.MetadataKeys.DESCRIPTION}" DISPLAYNAME_METADATA_KEY = f"omni:graph:{ogn.MetadataKeys.UI_NAME}" # ------------------------------------------------------------------------ def get_node(graph: og.Graph, node_name: str) -> og.Node: return graph.get_node(graph.get_path_to_graph() + "/" + node_name) # ------------------------------------------------------------------------ def get_node_type_from_schema_prim(prim: OmniGraphSchema.OmniGraphCompoundNodeType) -> str: """Returns the node type from an omni graph prim""" return f"{prim.GetOmniGraphNamespaceAttr().Get()}.{prim.GetPrim().GetPath().name}" # ------------------------------------------------------------------------ class TestCompoundNodes(ogts.OmniGraphTestCase): _simple_test_file = "TestCompoundGraph.usda" _test_file_with_reference = "TestCompoundWithExternalReference.usda" _test_file_with_default_values = "TestCompoundDefaultValues.usda" _test_preschema_file = "TestPreSchemaCompoundNode.usda" _test_graph_path = "/World/TestGraph" _node_library_test_file = os.path.join(os.path.dirname(__file__), "data", "TestNodeLibrary.usda") _library_compound_paths = [ "/World/Compounds/Madd", "/World/Compounds/DebugString", "/World/Compounds/Deg2Rad", "/World/Compounds/CelciusToFahrenheit", ] # ------------------------------------------------------------------------- def get_compound_folder(self): return ogu.get_default_compound_node_type_folder() def get_compound_path(self): return f"{self.get_compound_folder()}/Compound" def get_compound_graph_path(self): return f"{self.get_compound_path()}/Graph" # ------------------------------------------------------------------------- async def tearDown(self): omni.timeline.get_timeline_interface().stop() await super().tearDown() # ------------------------------------------------------------------------- async def test_load_file_with_compound_node_def(self): """ Tests that a usd file containing a compound node definition loads the compound node and adds it to the node database """ (result, error) = await ogts.load_test_file(self._simple_test_file, use_caller_subdirectory=True) self.assertTrue(result, error) # load the node type by path node_type = og.get_node_type(self.get_compound_path()) self.assertIsNotNone(node_type) expected_node_type = "local.nodes." + self.get_compound_path().rsplit("/", maxsplit=1)[-1] self.assertEquals(node_type.get_node_type(), expected_node_type) metadata = node_type.get_all_metadata() # verify it has expected metadata self.assertEquals(metadata["__categories"], "Compounds") self.assertEquals(metadata["uiName"], "Compound") self.assertEquals(metadata["tags"], "Compounds") # ------------------------------------------------------------------------- async def test_usd_changes_reflect_in_node_type(self): """ Tests that changing OmniGraphCompoundNodeType values are reflected in the compound node """ stage = omni.usd.get_context().get_stage() ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) # Change the schema_prim values schema_prim = OmniGraphSchema.OmniGraphCompoundNodeType(stage.GetPrimAtPath(self.get_compound_path())) schema_prim.GetOmniGraphCategoriesAttr().Set(["CatA", "CatB"]) schema_prim.GetOmniGraphDescriptionAttr().Set("Changed description") schema_prim.GetOmniGraphTagsAttr().Set(["TagA", "TagB"]) schema_prim.GetOmniGraphUiNameAttr().Set("FakeUIName") # validate they are changed in the node type node_type = og.get_node_type(self.get_compound_path()) metadata = node_type.get_all_metadata() self.assertEquals(metadata["__categories"], "CatA,CatB") self.assertEquals(metadata["tags"], "CatA,CatB") self.assertEquals(metadata["__description"], "Changed description") self.assertEquals(metadata["uiName"], "FakeUIName") # ------------------------------------------------------------------------- async def test_create_node_types_save_and_load(self): """Tests that a created node types save to USD and reload correctly""" stage = omni.usd.get_context().get_stage() # create a compound node ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) with tempfile.TemporaryDirectory() as tmpdirname: # save the file tmp_file_path = os.path.join(tmpdirname, "tmp.usda") result = omni.usd.get_context().save_as_stage(tmp_file_path) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # validate the node type was unloaded with the stage self.assertFalse(og.get_node_type(self.get_compound_path()).is_valid()) # reload the file back (result, error) = await ogts.load_test_file(tmp_file_path) self.assertTrue(result, error) # load the node type by path node_type = og.get_node_type(self.get_compound_path()) self.assertIsNotNone(node_type) expected_node_type = "local.nodes." + self.get_compound_path().rsplit("/", maxsplit=1)[-1] self.assertEquals(node_type.get_node_type(), expected_node_type) # ------------------------------------------------------------------------- def _create_and_test_graph_from_add_compound( self, compound_path, input_a="input_a", input_b="input_b", output="value", should_add: bool = True ) -> og.Graph: """Create and test a graph around a simple compound of an add node""" # create a graph that uses the compound graph keys = og.Controller.Keys controller = og.Controller() (graph, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound", compound_path), ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("Constant_a.inputs:value", f"Compound.inputs:{input_a}"), ("Constant_b.inputs:value", f"Compound.inputs:{input_b}"), ], keys.SET_VALUES: [("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0)], }, ) self.assertTrue(nodes[0].get_attribute_exists(f"inputs:{input_a}")) self.assertTrue(nodes[0].get_attribute_exists(f"inputs:{input_b}")) self.assertTrue(nodes[0].get_attribute_exists(f"outputs:{output}")) graph.evaluate() result = nodes[0].get_attribute(f"outputs:{output}").get() if should_add: self.assertEquals(result, 3.0) return graph # ------------------------------------------------------------------------ def _create_graph_with_compound_node(self, compound_path: str) -> Tuple[og.Graph, og.Node]: """Create a graph that simply uses the compound node type specified.""" keys = og.Controller.Keys controller = og.Controller() (graph, nodes, _, _) = controller.edit( self._test_graph_path, {keys.CREATE_NODES: [("Compound", compound_path)]} ) return (graph, nodes[0]) # ------------------------------------------------------------------------ def _create_test_compound( self, compound_name, graph_name="Graph", namespace="local.nodes.", compound_dir=None, evaluator_type=None ): """Creates a compound node/graph that wraps an add node""" # create a compound node (success, schema_prim) = ogu.cmds.CreateCompoundNodeType( compound_name=compound_name, graph_name=graph_name, namespace=namespace, folder=compound_dir, evaluator_type=evaluator_type, ) if not success: raise og.OmniGraphError("CreateNodeType failed") compound_path = str(schema_prim.GetPrim().GetPath()) graph_path = f"{compound_path}/{graph_name}" node_path = f"{graph_path}/Add_Node" node_type = get_node_type_from_schema_prim(schema_prim) # Create a node in the sub graph og.cmds.CreateNode( graph=og.get_graph_by_path(graph_path), node_path=node_path, node_type="omni.graph.nodes.Add", create_usd=True, ) # assign inputs and outputs ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_a", attribute_path=Sdf.Path(f"{node_path}.inputs:a") ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_b", attribute_path=Sdf.Path(f"{node_path}.inputs:b") ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="value", attribute_path=Sdf.Path(f"{node_path}.outputs:sum") ) # ------------------------------------------------------------------------- async def test_create_and_use_compound_node(self): """Tests manual creation, assignment and evaluation of a compound node""" self._create_test_compound("Compound") self._create_and_test_graph_from_add_compound(f"{self.get_compound_folder()}/Compound") # ------------------------------------------------------------------------- async def test_create_and_use_compound_node_with_qualifiedname(self): """Tests that graphs can be referenced by the qualified name""" self._create_test_compound("Compound") self._create_and_test_graph_from_add_compound("local.nodes.Compound") # ------------------------------------------------------------------------- async def test_create_and_use_compound_node_with_namespace(self): """Tests that graphs can be referenced using a different namespace""" self._create_test_compound("Compound", "Graph", "test.nodes.") self._create_and_test_graph_from_add_compound("test.nodes.Compound") # ------------------------------------------------------------------------- async def test_create_and_rename_compound_node(self): """Tests created graphs can handle""" self._create_test_compound("Compound", "Graph") graph = self._create_and_test_graph_from_add_compound("local.nodes.Compound") stage = omni.usd.get_context().get_stage() # rename the compound node new_compound_path = f"{self.get_compound_folder()}/NewCompound" omni.kit.commands.execute("MovePrim", path_from=self.get_compound_path(), path_to=new_compound_path) await omni.kit.app.get_app().next_update_async() # validate the graph still updates node = graph.get_node(graph.get_path_to_graph() + "/Constant_a") node.get_attribute("inputs:value").set(2.0) graph.evaluate() node = graph.get_node(graph.get_path_to_graph() + "/Compound") self.assertEquals(node.get_attribute("outputs:value").get(), 4.0) # validate the node type is properly updated node = OmniGraphSchema.OmniGraphNode(stage.GetPrimAtPath(node.get_prim_path())) self.assertEquals("local.nodes.NewCompound", node.GetNodeTypeAttr().Get()) # ------------------------------------------------------------------------- async def test_change_compound_namespace(self): """Tests that changing the compound namespace is reflected in the nodes""" self._create_test_compound("Compound") graph = self._create_and_test_graph_from_add_compound(self.get_compound_path()) stage = omni.usd.get_context().get_stage() # change the node type namespace schema_prim = OmniGraphSchema.OmniGraphCompoundNodeType(stage.GetPrimAtPath(self.get_compound_path())) schema_prim.GetOmniGraphNamespaceAttr().Set("test.nodes") # validate the node type itself updates node = OmniGraphSchema.OmniGraphNode(stage.GetPrimAtPath(f"{self._test_graph_path}/Compound")) self.assertEquals("test.nodes.Compound", node.GetNodeTypeAttr().Get()) # validate the graph still updates node = graph.get_node(graph.get_path_to_graph() + "/Constant_a") node.get_attribute("inputs:value").set(2.0) graph.evaluate() node = graph.get_node(graph.get_path_to_graph() + "/Compound") self.assertEquals(node.get_attribute("outputs:value").get(), 4.0) # ------------------------------------------------------------------------- async def test_node_type_command_undo_redo(self): """Tests node type commands support undo/redo""" stage = omni.usd.get_context().get_stage() input_attribute_path = f"{self.get_compound_path()}.omni:graph:input:" output_attribute_path = f"{self.get_compound_path()}.omni:graph:output:" # create a compound node ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) self.assertTrue(stage.GetPrimAtPath(self.get_compound_graph_path()).IsValid()) omni.kit.undo.undo() self.assertFalse(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) self.assertFalse(stage.GetPrimAtPath(self.get_compound_graph_path()).IsValid()) omni.kit.undo.redo() self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) self.assertTrue(stage.GetPrimAtPath(self.get_compound_graph_path()).IsValid()) # Create a node in the sub graph og.cmds.CreateNode( graph=og.get_graph_by_path(self.get_compound_graph_path()), node_path=self.get_compound_graph_path() + "/Add_Node", node_type="omni.graph.nodes.Add", create_usd=True, ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=self.get_compound_path(), input_name="input_a", attribute_path=Sdf.Path(self.get_compound_path() + "/Graph/Add_Node.inputs:a"), ) self.assertTrue(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) omni.kit.undo.undo() self.assertFalse(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) omni.kit.undo.redo() self.assertTrue(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=self.get_compound_path(), output_name="value", attribute_path=Sdf.Path(self.get_compound_graph_path() + "/Add_Node.outputs:sum"), ) self.assertTrue(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) omni.kit.undo.undo() self.assertFalse(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) omni.kit.undo.redo() self.assertTrue(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) ogu.cmds.RemoveCompoundNodeTypeInput( node_type=self.get_compound_path(), input_name="input_a", ) self.assertFalse(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) omni.kit.undo.undo() self.assertTrue(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) ogu.cmds.RemoveCompoundNodeTypeOutput( node_type=self.get_compound_path(), output_name="value", ) self.assertFalse(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) omni.kit.undo.undo() self.assertTrue(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) # set up the second input and test to make sure the graph works ogu.cmds.CreateCompoundNodeTypeInput( node_type=self.get_compound_path(), input_name="input_b", attribute_path=Sdf.Path(self.get_compound_graph_path() + "/Add_Node.inputs:b"), ) self._create_and_test_graph_from_add_compound(self.get_compound_path()) # ------------------------------------------------------------------------- async def test_nested_compound_nodes(self): """Tests that nested compounds can be created and execute as expected""" # create an add compound for the inner node self._create_test_compound("innerCompound") inner_compound_path = f"{self.get_compound_folder()}/innerCompound" ogu.cmds.CreateCompoundNodeType(compound_name="outerCompound", graph_name="Graph") outer_compound_path = f"{self.get_compound_folder()}/outerCompound" outer_graph_path = f"{outer_compound_path}/Graph" outer_graph_node_path = f"{outer_graph_path}/Node" # Create a node in the sub graph that uses the inner compound og.cmds.CreateNode( graph=og.get_graph_by_path(outer_graph_path), node_path=outer_graph_node_path, node_type=inner_compound_path, create_usd=True, ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=outer_compound_path, input_name="a", attribute_path=Sdf.Path(f"{outer_graph_node_path}.inputs:input_a"), ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=outer_compound_path, input_name="b", attribute_path=Sdf.Path(f"{outer_graph_node_path}.inputs:input_b"), ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=outer_compound_path, output_name="result", attribute_path=Sdf.Path(f"{outer_graph_node_path}.outputs:value"), ) self._create_and_test_graph_from_add_compound(outer_compound_path, "a", "b", "result") # ------------------------------------------------------------------------- async def test_multiple_compounds_used(self): """Tests that multiple compounds of the same type can be used in a single graphs""" self._create_test_compound("Compound") # create a graph that uses the compound graph # ------------ ------------- # [Const a]->|Compound a| -------> |Compound b | # [Const b] | | [Const c]->| | # ------------ ------------- keys = og.Controller.Keys controller = og.Controller() (graph, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound_a", self.get_compound_path()), ("Compound_b", self.get_compound_path()), ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ("Constant_c", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Compound_a.inputs:input_a"), ("Constant_b.inputs:value", "Compound_a.inputs:input_b"), ("Compound_a.outputs:value", "Compound_b.inputs:input_a"), ("Constant_c.inputs:value", "Compound_b.inputs:input_b"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0), ("Constant_c.inputs:value", 3.0), ], }, ) self.assertTrue(nodes[0].get_attribute_exists("inputs:input_a")) self.assertTrue(nodes[0].get_attribute_exists("inputs:input_b")) self.assertTrue(nodes[0].get_attribute_exists("outputs:value")) self.assertTrue(nodes[1].get_attribute_exists("inputs:input_a")) self.assertTrue(nodes[1].get_attribute_exists("inputs:input_b")) self.assertTrue(nodes[1].get_attribute_exists("outputs:value")) graph.evaluate() # check intermediate result result = nodes[0].get_attribute("outputs:value").get() self.assertEquals(result, 3.0) # check final result result = nodes[1].get_attribute("outputs:value").get() self.assertEquals(result, 6.0) # ------------------------------------------------------------------------- async def test_compound_graph_does_not_run(self): """ Tests that when creating a compound graph, the compound graph itself does not evaluate """ compound_name = "Compound" graph_name = "Graph" # create a compound node ogu.cmds.CreateCompoundNodeType(compound_name=compound_name, graph_name=graph_name) compound_path = f"{self.get_compound_folder()}/{compound_name}" graph_path = f"{compound_path}/{graph_name}" keys = og.Controller.Keys controller = og.Controller() (_, (time_node, to_string_node), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("Time", "omni.graph.nodes.ReadTime"), ("ToString", "omni.graph.nodes.ToString"), ], keys.CONNECT: [("Time.outputs:timeSinceStart", "ToString.inputs:value")], }, ) for _ in range(1, 5): await omni.kit.app.get_app().next_update_async() self.assertEquals(time_node.get_compute_count(), 0) self.assertEquals(to_string_node.get_compute_count(), 0) # ------------------------------------------------------------------------- async def test_replace_with_compound_command(self): """Tests the replace with compound command under different scenarios""" graph_path = "/World/Graph" def build_graph(graph_path: str) -> Tuple[og.Node]: # [ConstA] -----> [Add]---v # [ConstB] -------^ [Add]---v # [ConstC] ---------------^ [Add]--->[Magnitude] # [ReadTime] ---------------------^ keys = og.Controller.Keys controller = og.Controller() (_graph, nodes, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), # 0 ("Constant_b", "omni.graph.nodes.ConstantDouble"), # 1 ("Constant_c", "omni.graph.nodes.ConstantDouble"), # 2 ("ReadTime", "omni.graph.nodes.ReadTime"), # 3 ("Add1", "omni.graph.nodes.Add"), # 4 ("Add2", "omni.graph.nodes.Add"), # 5 ("Add3", "omni.graph.nodes.Add"), # 6 ("Abs", "omni.graph.nodes.Magnitude"), # 7 ], keys.CONNECT: [ ("Constant_a.inputs:value", "Add1.inputs:a"), ("Constant_b.inputs:value", "Add1.inputs:b"), ("Add1.outputs:sum", "Add2.inputs:a"), ("Constant_c.inputs:value", "Add2.inputs:b"), ("Add2.outputs:sum", "Add3.inputs:a"), ("ReadTime.outputs:timeSinceStart", "Add3.inputs:b"), ("Add3.outputs:sum", "Abs.inputs:input"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0), ("Constant_c.inputs:value", 3.0), ], }, ) # Workaround...SET_VALUES does not set values in USD, which is needed to retain # values when nodes are copied stage = omni.usd.get_context().get_stage() stage.GetAttributeAtPath(graph_path + "/Constant_a.inputs:value").Set(1.0) stage.GetAttributeAtPath(graph_path + "/Constant_b.inputs:value").Set(2.0) stage.GetAttributeAtPath(graph_path + "/Constant_c.inputs:value").Set(3.0) return nodes async def validate_graph(all_nodes: Tuple[og.Node], node_indices: List[int]): # let the graph evaluate and cache the output value, which # should increase with each tick output_node = all_nodes[-1] output_attr = output_node.get_attribute("outputs:magnitude") await omni.kit.app.get_app().next_update_async() self.assertGreater(output_node.get_compute_count(), 0) self.assertGreater(output_attr.get(), 6.0) last_val = output_attr.get() # replace the given node set with a compound node all_node_paths = [Sdf.Path(node.get_prim_path()) for node in all_nodes] nodes = [all_nodes[i] for i in node_indices] node_paths = [Sdf.Path(node.get_prim_path()) for node in nodes] og.cmds.ReplaceWithCompound(nodes=node_paths) # verify the compound node was created compound_path = node_paths[0].GetParentPath().AppendChild("compound") compound_node = og.get_node_by_path(str(compound_path)) self.assertTrue(compound_node.is_valid()) # if the last node is not the compound if 7 not in node_indices: # re-fetch the node from a path, the previous og.node may have been invalidated abs_path = og.get_node_by_path(str(all_node_paths[7])) output_attr = abs_path.get_attribute("outputs:magnitude") await omni.kit.app.get_app().next_update_async() # note: the compute count gets reset when the replace with compound, so validate it has advanced self.assertGreater(abs_path.get_compute_count(), 0) self.assertGreater(output_attr.get(), last_val) else: self.assertGreater(compound_node.get_compute_count(), 0) # validate all nodes in the subgraph computed graph_path = compound_path.AppendChild("Graph") compound_graph = og.get_graph_by_path(str(graph_path)) self.assertTrue(compound_graph.is_valid()) compound_nodes = compound_graph.get_nodes() self.assertGreater(len(compound_nodes), 0) for compound_node in compound_nodes: # Quick check for constant nodes. TODO: Add a more robust method to # check for such nodes (check if a node has the "pure" scheduling # hint and only runtime-constant input attributes)? if "omni.graph.nodes.Constant" in compound_node.get_type_name(): self.assertEqual(compound_node.get_compute_count(), 0) else: self.assertGreater(compound_node.get_compute_count(), 0) # add nodes await validate_graph(build_graph(graph_path + "0"), [4, 5, 6]) # first two inputs + first add await validate_graph(build_graph(graph_path + "1"), [0, 1, 4]) # last const + read time + last two adds await validate_graph(build_graph(graph_path + "2"), [2, 3, 5, 6]) # all nodes except the last await validate_graph(build_graph(graph_path + "3"), [0, 1, 2, 3, 4, 5, 6]) # ------------------------------------------------------------------------- async def _load_node_library(self): stage = omni.usd.get_context().get_stage() root_layer = stage.GetRootLayer() # insert a subLayer with material.usda which contains just one material prim omni.kit.commands.execute( "CreateSublayer", layer_identifier=root_layer.identifier, sublayer_position=0, new_layer_path=self._node_library_test_file, transfer_root_content=False, create_or_insert=False, ) await omni.kit.app.get_app().next_update_async() # ------------------------------------------------------------------------- async def _unload_node_library(self): stage = omni.usd.get_context().get_stage() root_layer = stage.GetRootLayer() omni.kit.commands.execute("RemoveSublayer", layer_identifier=root_layer.identifier, sublayer_position=0) await omni.kit.app.get_app().next_update_async() # ------------------------------------------------------------------------ def _validate_library_nodes_loaded(self, are_loaded: bool): stage = omni.usd.get_context().get_stage() for path in self._library_compound_paths: prim = stage.GetPrimAtPath(Sdf.Path(path)) prim_loaded_and_valid = bool(prim) and prim.IsA(OmniGraphSchema.OmniGraphCompoundNodeType) self.assertEquals(are_loaded, prim_loaded_and_valid, f"Failed with {path}") self.assertEquals(are_loaded, og.get_node_type(path).is_valid()) # ------------------------------------------------------------------------- async def test_compound_nodes_load_from_layer(self): """ Tests that node libraries loaded from a separate layer correctly load and unload """ # load the library await self._load_node_library() self._validate_library_nodes_loaded(True) # unload await self._unload_node_library() self._validate_library_nodes_loaded(False) # reload the library await self._load_node_library() self._validate_library_nodes_loaded(True) # unload the whole stage await omni.usd.get_context().new_stage_async() self._validate_library_nodes_loaded(False) # ----------------------------------------------------------------------- async def test_compound_node_can_reference_layer(self): """ Tests that a compound node that references a compound graph located in a layer """ await self._load_node_library() # builds the graph # [const]-->[compound]------->[magnitude] # [const]---^ ^ # [const]------| keys = og.Controller.Keys controller = og.Controller() (_graph, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ("Constant_c", "omni.graph.nodes.ConstantDouble"), ("Madd", "/World/Compounds/Madd"), ("Abs", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Madd.inputs:a"), ("Constant_b.inputs:value", "Madd.inputs:b"), ("Constant_c.inputs:value", "Madd.inputs:c"), ("Madd.outputs:sum", "Abs.inputs:input"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0), ("Constant_c.inputs:value", 3.0), ], }, ) await omni.kit.app.get_app().next_update_async() for node in nodes: # Quick check for constant nodes. TODO: Add a more robust method to # check for such nodes (check if a node has the "pure" scheduling # hint and only runtime-constant input attributes)? if not node.is_compound_node() and "omni.graph.nodes.Constant" not in node.get_type_name(): self.assertGreater(node.get_compute_count(), 0, f"Expected {node.get_prim_path()} to be computed") attr = nodes[4].get_attribute("outputs:magnitude") self.assertEquals(attr.get(), 1.0 * 2.0 + 3.0) # ------------------------------------------------------------------------- async def test_compound_from_reference_runs(self): """ Tests that a graph containing a compound node with an external reference can be loaded and run """ # Loads a graph on disk that looks like: # where the compound references a graph from the TestNodeLibrary.usda (madd) # [const]-->[compound]------->[magnitude] # [const]---^ ^ # [const]------| (result, error) = await ogts.load_test_file(self._test_file_with_reference, use_caller_subdirectory=True) self.assertTrue(result, error) await omni.kit.app.get_app().next_update_async() graph = og.get_graph_by_path("/World/PushGraph") nodes = graph.get_nodes() self.assertGreater(len(nodes), 4, "Expected at least 5 nodes") for node in nodes: # Quick check for constant nodes. TODO: Add a more robust method to # check for such nodes (check if a node has the "pure" scheduling # hint and only runtime-constant input attributes)? if not node.is_compound_node() and "omni.graph.nodes.Constant" not in node.get_type_name(): self.assertGreater(node.get_compute_count(), 0, f"Expected {node.get_prim_path()} to be computed") output = og.get_node_by_path("/World/PushGraph/magnitude") attr = output.get_attribute("outputs:magnitude") self.assertEquals(attr.get(), 1.0 * 2.0 + 3.0) # ------------------------------------------------------------------------- async def test_nested_reference_compound(self): """ Tests that a nested compound node loaded from a compound library runs """ await self._load_node_library() keys = og.Controller.Keys controller = og.Controller() (_graph, (_constant, convert), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Convert", "/World/Compounds/CelciusToFahrenheit"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Convert.inputs:a"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ], }, ) await omni.kit.app.get_app().next_update_async() self.assertEquals(convert.get_attribute("outputs:value").get(), 33.8) # ------------------------------------------------------------------------- async def test_fan_out_to_compounds(self): """Tests that fan out into multiple compound nodes""" await self._load_node_library() # [Const] -> [Compound] -> [Add] # -> [Compound] -> keys = og.Controller.Keys controller = og.Controller() (_, (_, compound_a, compound_b, add), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Convert_a", "/World/Compounds/Deg2Rad"), ("Convert_b", "/World/Compounds/Deg2Rad"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Convert_a.inputs:a"), ("Constant_a.inputs:value", "Convert_b.inputs:a"), ("Convert_a.outputs:result", "Add.inputs:a"), ("Convert_b.outputs:result", "Add.inputs:b"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 180), ], }, ) await omni.kit.app.get_app().next_update_async() self.assertEquals(compound_a.get_attribute("outputs:result").get(), math.pi) self.assertEquals(compound_b.get_attribute("outputs:result").get(), math.pi) self.assertEquals(add.get_attribute("outputs:sum").get(), math.pi * 2.0) # ------------------------------------------------------------------------- async def test_fan_out_from_compounds(self): """Tests that fan out from a compound node works""" await self._load_node_library() # [Const] -> [Compound] -> [Abs] # -> [Abs] keys = og.Controller.Keys controller = og.Controller() (_, (_, _, abs_a, abs_b), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Convert_a", "/World/Compounds/Deg2Rad"), ("Abs_a", "omni.graph.nodes.Magnitude"), ("Abs_b", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Convert_a.inputs:a"), ("Convert_a.outputs:result", "Abs_a.inputs:input"), ("Convert_a.outputs:result", "Abs_b.inputs:input"), ], keys.SET_VALUES: [("Constant_a.inputs:value", 180)], }, ) await omni.kit.app.get_app().next_update_async() self.assertEquals(abs_a.get_attribute("outputs:magnitude").get(), math.pi) self.assertEquals(abs_b.get_attribute("outputs:magnitude").get(), math.pi) # ------------------------------------------------------------------------- async def test_register_compound_with_node_type_conflict(self): """ Tests that compound nodes registered with the same as built-in nodes produces error and does NOT override the default node usage """ # Create the compound node with ogts.ExpectedError(): self._create_test_compound("Add", "Graph", "omni.graph.nodes") # Validate the compound is still created stage = omni.usd.get_context().get_stage() self.assertTrue(stage.GetPrimAtPath(self.get_compound_folder() + "/Add_01").IsValid()) self.assertTrue(stage.GetPrimAtPath(self.get_compound_folder() + "/Add_01/Graph").IsValid()) # Validate the built-in node type is actually used keys = og.Controller.Keys controller = og.Controller() (graph, (_, _, add), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Add.inputs:a"), ("Constant_b.inputs:value", "Add.inputs:b"), ], keys.SET_VALUES: [("Constant_a.inputs:value", 1), ("Constant_b.inputs:value", 2)], }, ) await controller.evaluate(graph) self.assertEquals(add.get_attribute("outputs:sum").get(), 3) # ------------------------------------------------------------------------- async def test_register_compound_with_compound_conflict(self): """Tests errors when registering multiple compounds with the same name""" self._create_test_compound("Compound") with ogts.ExpectedError(): self._create_test_compound(compound_name="Compound", compound_dir=Sdf.Path("/World/Compound/SubDir")) self._create_and_test_graph_from_add_compound("local.nodes.Compound") # ------------------------------------------------------------------------- async def test_create_node_type_prevents_duplicates(self): """Tests that CreateNodeType prevents duplicates through renaming""" ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") ogu.cmds.CreateCompoundNodeType(compound_name="Add", graph_name="Graph", namespace="omni.graph.nodes") stage = omni.usd.get_context().get_stage() folder = stage.GetPrimAtPath(self.get_compound_folder()) self.assertEquals(len(folder.GetChildren()), 3) self.assertTrue(stage.GetPrimAtPath(self.get_compound_folder() + "/Compound").IsValid()) self.assertFalse(stage.GetPrimAtPath(self.get_compound_folder() + "/Add").IsValid()) # -------------------------------------------------------------------------- async def test_create_node_type_with_existing_node_name(self): """ Tests that creating a node type with a name conflict on an existing node in the graph functions does not break """ keys = og.Controller.Keys controller = og.Controller() (graph, (const_a, const_b, _, add, add_01), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ("Constant_c", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ("Add_01", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Add.inputs:a"), ("Constant_b.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "Add_01.inputs:a"), ("Constant_c.inputs:value", "Add_01.inputs:b"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0), ("Constant_c.inputs:value", 3.0), ], }, ) await og.Controller.evaluate(graph) self.assertEquals(add_01.get_attribute("outputs:sum").get(), 6.0) # replace the nodes with a node type that has the same name as an existing node node_paths = [Sdf.Path(node.get_prim_path()) for node in [const_a, const_b, add]] og.cmds.ReplaceWithCompound(nodes=node_paths, compound_name="Add_01") # validate add_01 = get_node(graph, "Add_01") compound_node = next(filter(lambda node: node.is_compound_node(), graph.get_nodes()), None) self.assertFalse(get_node(graph, "Constant_a").is_valid()) self.assertFalse(get_node(graph, "Constant_b").is_valid()) self.assertTrue(get_node(graph, "Constant_c").is_valid()) self.assertTrue(add_01.is_valid()) self.assertIsNotNone(compound_node) self.assertNotEquals(Sdf.Path(compound_node.get_prim_path()).name, "Add_01") # validate the graph await og.Controller.evaluate(graph) self.assertEquals(add_01.get_attribute("outputs:sum").get(), 6.0) # -------------------------------------------------------------------------- async def test_is_compound_node_type(self): """Simple test that validates nodetype.is_compound_node""" await self._load_node_library() # C++ nodes self.assertFalse(og.get_node_type("omni.graph.test.Add2IntegerArrays").is_compound_node_type()) self.assertFalse(og.get_node_type("omni.graph.test.ComputeErrorCpp").is_compound_node_type()) # python nodes self.assertFalse(og.get_node_type("omni.graph.test.ComputeErrorPy").is_compound_node_type()) self.assertFalse(og.get_node_type("omni.graph.test.TestAllDataTypesPy").is_compound_node_type()) # compound nodes self.assertTrue(og.get_node_type("local.nodes.Madd").is_compound_node_type()) self.assertTrue(og.get_node_type("local.nodes.DebugString").is_compound_node_type()) self.assertTrue(og.get_node_type("local.nodes.Deg2Rad").is_compound_node_type()) self.assertTrue(og.get_node_type("local.nodes.CelciusToFahrenheit").is_compound_node_type()) # -------------------------------------------------------------------------- async def test_compound_nodes_trigger_graph_registry_events(self): """Tests that changing compound node values triggers appropriate graph registry events""" node_type_t = OmniGraphSchema.OmniGraphCompoundNodeType await self._load_node_library() events = [] def on_changed(event): nonlocal events events.append(event) sub = og.GraphRegistry().get_event_stream().create_subscription_to_pop(on_changed) self.assertIsNotNone(sub) stage = omni.usd.get_context().get_stage() prims = [node_type_t(stage.GetPrimAtPath(path)) for path in self._library_compound_paths] for prim in prims: prim.GetOmniGraphCategoriesAttr().Set(["NewCategory"]) await omni.kit.app.get_app().next_update_async() self.assertEquals(len(events), len(self._library_compound_paths)) self.assertTrue(all(e.type == int(og.GraphRegistryEvent.NODE_TYPE_CATEGORY_CHANGED) for e in events)) events = [] for prim in prims: prim.GetOmniGraphNamespaceAttr().Set("other.namespace") await omni.kit.app.get_app().next_update_async() # Double the count because there will be two events per compound (node type added, namespace changed) self.assertEquals(len(events), len(self._library_compound_paths) * 2) add_events = [ int(og.GraphRegistryEvent.NODE_TYPE_NAMESPACE_CHANGED), int(og.GraphRegistryEvent.NODE_TYPE_ADDED), ] self.assertTrue(all(e.type in add_events for e in events)) sub = None # -------------------------------------------------------------------------- async def test_is_compound_graph(self): """Tests is_compound_graph returns true for compounds graphs""" (result, error) = await ogts.load_test_file(self._test_file_with_reference, use_caller_subdirectory=True) self.assertTrue(result, error) await omni.kit.app.get_app().next_update_async() graph = og.get_graph_by_path("/World/PushGraph") self.assertTrue(graph.is_valid()) self.assertFalse(graph.is_compound_graph()) graph = og.get_graph_by_path("/World/PushGraph/madd/Graph") self.assertTrue(graph.is_valid()) self.assertTrue(graph.is_compound_graph()) # --------------------------------------------------------------------- def _create_lazy_compound( self, compound_name, evaluator_type, graph_name="Graph", namespace="local.nodes.", compound_dir=None ): """Creates a compound node/graph that wraps an add node The output is the time from a ReadTime node """ # Create a compound node/graph that can be used to evaluate lazy graphs (success, schema_prim) = ogu.cmds.CreateCompoundNodeType( compound_name=compound_name, graph_name=graph_name, namespace=namespace, folder=compound_dir, evaluator_type=evaluator_type, ) if not success: raise og.OmniGraphError("CreateNodeType failed") compound_path = str(schema_prim.GetPrim().GetPath()) graph_path = f"{compound_path}/{graph_name}" node_path = f"{graph_path}/ReadTime_Node" node_type = get_node_type_from_schema_prim(schema_prim) # Create a node in the sub graph og.cmds.CreateNode( graph=og.get_graph_by_path(graph_path), node_path=node_path, node_type="omni.graph.nodes.ReadTime", create_usd=True, ) # assign inputs and outputs ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="value", attribute_path=Sdf.Path(f"{node_path}.outputs:timeSinceStart") ) # ------------------------------------------------------------------------- def _create_evaluation_graph( self, compound_name, evaluator_type, graph_name="Graph", namespace="local.nodes.", compound_dir=None ): """ Creates a compound node for an evaluation graph The underlying graph is [OnImpulse]->[TickCounter] and outputs the tick count """ (success, schema_prim) = ogu.cmds.CreateCompoundNodeType( compound_name=compound_name, graph_name=graph_name, namespace=namespace, folder=compound_dir, evaluator_type=evaluator_type, ) if not success: raise og.OmniGraphError("CreateNodeType failed") compound_path = str(schema_prim.GetPrim().GetPath()) graph_path = f"{compound_path}/{graph_name}" node_path = f"{graph_path}/TickCounter" node_type = get_node_type_from_schema_prim(schema_prim) keys = og.Controller.Keys controller = og.Controller() (_, (_impulse, _counter), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("OnImpulse", "omni.graph.action.OnImpulseEvent"), ("TickCounter", "omni.graph.action.Counter"), ], keys.CONNECT: [ ("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"), ], keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False), ("OnImpulse.state:enableImpulse", True)], }, ) # assign inputs and outputs ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="value", attribute_path=Sdf.Path(f"{node_path}.outputs:count") ) # ------------------------------------------------------------------------- async def __evaluate_graph_types(self, compound_type: str, runner_type: str): """Tests that graphs can be referenced using a different namespace""" if compound_type == "execution": self._create_evaluation_graph("Compound", compound_type) else: self._create_lazy_compound("Compound", compound_type) # create a graph that uses the compound graph keys = og.Controller.Keys controller = og.Controller() (graph, (_compound, abs_node), _, _) = controller.edit( {"graph_path": self._test_graph_path, "evaluator_name": runner_type}, { keys.CREATE_NODES: [ ("Compound", f"{self.get_compound_folder()}/Compound"), ("Abs", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Compound.outputs:value", "Abs.inputs:input"), ], }, ) await omni.kit.app.get_app().next_update_async() await og.Controller.evaluate(graph) result = abs_node.get_attribute("outputs:magnitude").get() return result > 0.0 # ------------------------------------------------------------------------- async def test_intermix_evaluator_types_in_compounds(self): """ Tests mixing evaluator types of graphs with compounds This test uses a compound with a given evaluator type and a single output connected to an outer graph """ # play the timeline so readtime nodes get updated omni.timeline.get_timeline_interface().play() outer_graph_modes = ["push", "dirty_push"] compound_modes = ["push", "dirty_push", "execution"] for (graph_type, compound_type) in itertools.product(outer_graph_modes, compound_modes): with self.subTest(compound_type=compound_type, graph_type=graph_type): success = await self.__evaluate_graph_types(compound_type, graph_type) self.assertTrue(success, f"Graph Type: '{graph_type}' with Compound Type: '{compound_type}'") await omni.usd.get_context().new_stage_async() # ------------------------------------------------------------------------- async def test_evaluator_types_in_compounds(self): """ Test different evaluator types of graphs with compounds that have inputs and outputs where the outer graph is a push graph """ compound_modes = ["push", "dirty_push", "execution"] for compound_type in compound_modes: with self.subTest(compound_type=compound_type): self._create_test_compound("Compound", evaluator_type=compound_type) should_add = compound_type in ("push", "dirty_push") self._create_and_test_graph_from_add_compound( f"{self.get_compound_folder()}/Compound", should_add=should_add ) await omni.usd.get_context().new_stage_async() # ---------------------------------------------------------------------------- async def test_deleted_compound_graph(self): """Basic test that validates a deleted compound doesn't cause a crash""" stage = omni.usd.get_context().get_stage() self._create_test_compound("Compound") graph = self._create_and_test_graph_from_add_compound("local.nodes.Compound") omni.kit.commands.execute("DeletePrims", paths=[self.get_compound_path()]) self.assertFalse(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) graph.evaluate() # ---------------------------------------------------------------------------- async def test_create_node_type_attributes_with_fixed_types(self): """ Tests the CreateNodeTypeInput and CreateNodeTypeOutput with predefined types, including extended types and validates the attributes are correctly created on the resulting node instances """ stage = omni.usd.get_context().get_stage() (_, schema_prim) = ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) node_type = get_node_type_from_schema_prim(schema_prim) og_types = [ og.AttributeType.type_from_ogn_type_name(type_name) for type_name in ogn.supported_attribute_type_names() ] str_inputs = ogn.supported_attribute_type_names() + list(ogn.ATTRIBUTE_UNION_GROUPS.keys()) # create attributes both from og.Type and ogn type strings (including "union" types) for idx, og_type in enumerate(og_types): name = re.sub(r"\W", "_", og_type.get_ogn_type_name()) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name=f"input_{name}_{idx}", attribute_path=None, default_type=og_type ) if og_type.role not in [og.AttributeRole.BUNDLE, og.AttributeRole.TARGET]: ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name=f"output_{name}_{idx}", attribute_path=None, default_type=og_type ) for idx, str_type in enumerate(str_inputs): name = re.sub(r"\W", "_", str_type) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name=f"input_s_{name}_{idx}", attribute_path=None, default_type=str_type ) if str_type not in ["bundle", "target"]: ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name=f"output_s_{name}_{idx}", attribute_path=None, default_type=str_type, ) # validate bundles don't work omni.kit.commands.set_logging_enabled(False) (result, _) = ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_bundle_a", attribute_path=None, default_type="bundle" ) self.assertFalse(result) (result, _) = ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_bundle_b", attribute_path=None, default_type=og.Type(og.BaseDataType.PRIM, 1, 0, og.AttributeRole.BUNDLE), ) self.assertFalse(result) omni.kit.commands.set_logging_enabled(True) # validate specifying no path or default_type still creates inputs and outputs ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_empty", attribute_path=None, default_type=None ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_empty", attribute_path=None, default_type=None ) # validate creation with list style unions float_type_subset = [ og.Type(og.BaseDataType.FLOAT), og.Type(og.BaseDataType.FLOAT, 2), og.Type(og.BaseDataType.FLOAT, 3), ] ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_union", attribute_path=None, default_type=float_type_subset ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_union", attribute_path=None, default_type=float_type_subset ) # create a graph that uses the compound graph (_, compound_node) = self._create_graph_with_compound_node(f"{self.get_compound_folder()}/Compound") # validate the attributes on the node have been created, and the resolved type matches where there is a regular type for idx, og_type in enumerate(og_types): name = re.sub(r"\W", "_", og_type.get_ogn_type_name()) input_name = f"inputs:input_{name}_{idx}" self.assertTrue(compound_node.get_attribute(input_name).is_valid(), input_name) self.assertEquals(compound_node.get_attribute(input_name).get_resolved_type(), og_type) if og_type.role not in [og.AttributeRole.BUNDLE, og.AttributeRole.TARGET]: output_name = f"outputs:output_{name}_{idx}" self.assertTrue(compound_node.get_attribute(output_name).is_valid(), output_name) self.assertEquals(compound_node.get_attribute(output_name).get_resolved_type(), og_type) for idx, str_type in enumerate(str_inputs): name = re.sub(r"\W", "_", str_type) input_name = f"inputs:input_s_{name}_{idx}" self.assertTrue(compound_node.get_attribute(input_name).is_valid(), input_name) if str_type not in ["bundle", "target"]: output_name = f"outputs:output_s_{name}_{idx}" self.assertTrue(compound_node.get_attribute(output_name).is_valid(), output_name) # empty inputs and outputs create self.assertTrue(compound_node.get_attribute("inputs:input_empty").is_valid()) self.assertTrue(compound_node.get_attribute("outputs:output_empty").is_valid()) # list-style unions self.assertTrue(compound_node.get_attribute("inputs:input_union").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_union").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) self.assertTrue(compound_node.get_attribute("outputs:output_union").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_union").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) # ---------------------------------------------------------------------------- async def test_create_node_type_attributes_with_fixed_types_and_connections(self): """ Tests CreateNodeTypeInput and CreateNodeTypeOutput when both an attribute_path and a fixed types are applied """ # create a compound node stage = omni.usd.get_context().get_stage() (_, schema_prim) = ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) node_path = f"{self.get_compound_graph_path()}/Node" union_path = f"{self.get_compound_graph_path()}/UnionNode" union_path_2 = f"{self.get_compound_graph_path()}/UnionNodeTwo" node_type = get_node_type_from_schema_prim(schema_prim) input_prefix = f"{node_path}.inputs:" output_prefix = f"{node_path}.outputs:" # Create a node in the sub graph that has many fixed types og.cmds.CreateNode( graph=og.get_graph_by_path(self.get_compound_graph_path()), node_path=node_path, node_type="omni.graph.test.TestAllDataTypes", create_usd=True, ) # And nodes with union types for path in [union_path, union_path_2]: og.cmds.CreateNode( graph=og.get_graph_by_path(self.get_compound_graph_path()), node_path=path, node_type="omni.graph.nodes.Add", create_usd=True, ) # attributes where the types match ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_bool", attribute_path=Sdf.Path(f"{input_prefix}a_bool"), default_type="bool", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_bool", attribute_path=Sdf.Path(f"{output_prefix}a_bool"), default_type="bool", ) # attributes where the defined type is a union, and the attribute type is not ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_float", attribute_path=Sdf.Path(f"{input_prefix}a_float"), default_type="numerics", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_float", attribute_path=Sdf.Path(f"{output_prefix}a_float"), default_type="numerics", ) # attributes where the defined type is fixed, and the attribute type is a union ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_double", attribute_path=Sdf.Path(f"{union_path}.inputs:a"), default_type="double", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_double", attribute_path=Sdf.Path(f"{union_path}.outputs:sum"), default_type="double", ) # attributes where the types don't match with ogts.ExpectedError(): ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_float_2", attribute_path=Sdf.Path(f"{input_prefix}a_token"), default_type="float[2]", ) with ogts.ExpectedError(): ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_float_2", attribute_path=Sdf.Path(f"{output_prefix}a_token"), default_type="float[2]", ) # union to union ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_union", attribute_path=Sdf.Path(f"{union_path}.inputs:b"), default_type="numerics", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_union", attribute_path=Sdf.Path(f"{union_path_2}.outputs:sum"), default_type="numerics", ) # create a graph that uses the compound graph (_, compound_node) = self._create_graph_with_compound_node(f"{self.get_compound_folder()}/Compound") # types match exactly self.assertTrue(compound_node.get_attribute("inputs:input_bool").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_bool").get_resolved_type(), og.Type(og.BaseDataType.BOOL) ) self.assertTrue(compound_node.get_attribute("outputs:output_bool").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_bool").get_resolved_type(), og.Type(og.BaseDataType.BOOL) ) # definition is a union, target is fixed self.assertTrue(compound_node.get_attribute("inputs:input_float").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_float").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) self.assertTrue(compound_node.get_attribute("outputs:output_float").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_float").get_resolved_type(), og.Type(og.BaseDataType.FLOAT) ) # definition is fixed, target is a union self.assertTrue(compound_node.get_attribute("inputs:input_double").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_double").get_resolved_type(), og.Type(og.BaseDataType.DOUBLE) ) self.assertTrue(compound_node.get_attribute("outputs:output_double").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_double").get_resolved_type(), og.Type(og.BaseDataType.DOUBLE) ) # attributes where the types don't match self.assertTrue(compound_node.get_attribute("inputs:input_float_2").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_float_2").get_resolved_type(), og.Type(og.BaseDataType.FLOAT, 2, 0), ) self.assertTrue(compound_node.get_attribute("outputs:output_float_2").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_float_2").get_resolved_type(), og.Type(og.BaseDataType.FLOAT, 2, 0), ) # both are unions self.assertTrue(compound_node.get_attribute("inputs:input_union").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_union").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) self.assertTrue(compound_node.get_attribute("outputs:output_union").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_union").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) # ---------------------------------------------------------------------------- async def test_compound_node_input_output_metadata(self): """ Validate that metadata created on the input/outputs of a Compound Node Type gets transferred to created nodes from those compounds """ stage = omni.usd.get_context().get_stage() (_, schema_prim) = ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) node_type = get_node_type_from_schema_prim(schema_prim) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_a", attribute_path=None, default_type="int", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_a", attribute_path=None, default_type="int", ) # get the relationship created as the type input and output input_rel = schema_prim.GetPrim().GetRelationship("omni:graph:input:input_a") output_rel = schema_prim.GetPrim().GetRelationship("omni:graph:output:output_a") self.assertTrue(input_rel.IsValid()) self.assertTrue(output_rel.IsValid()) # set the metadata on the relationships. input_rel.SetCustomDataByKey(DESCRIPTION_METADATA_KEY, "InputDescription") input_rel.SetCustomDataByKey(DISPLAYNAME_METADATA_KEY, "InputDisplayName") output_rel.SetCustomDataByKey(DESCRIPTION_METADATA_KEY, "OutputDescription") output_rel.SetCustomDataByKey(DISPLAYNAME_METADATA_KEY, "OutputDisplayName") # create a graph that uses the compound node type keys = og.Controller.Keys controller = og.Controller() (_, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound", f"{self.get_compound_folder()}/Compound"), ] }, ) node = nodes[0] # Validate that the resulting node contains the metadata transfered when the node is created input_attr = node.get_attribute("inputs:input_a") output_attr = node.get_attribute("outputs:output_a") self.assertEquals("InputDescription", input_attr.get_metadata(ogn.MetadataKeys.DESCRIPTION)) self.assertEquals("InputDisplayName", input_attr.get_metadata(ogn.MetadataKeys.UI_NAME)) self.assertEquals("OutputDescription", output_attr.get_metadata(ogn.MetadataKeys.DESCRIPTION)) self.assertEquals("OutputDisplayName", output_attr.get_metadata(ogn.MetadataKeys.UI_NAME)) # ------------------------------------------------------------------------- def assert_attribute_value(self, actual, expected): """ Helper method that deals with values returned from attributes, where lists may actually be numpy arrays. """ ogts.verify_values(expected, actual, f"Comparison failed {str(actual)} vs {str(expected)}") # ---------------------------------------------------------------------------- async def test_compound_node_input_defaults(self): """ Test that validates compound nodes that carry default values in their metadata initialize nodes with the default values. This validates the attribute is correctly loaded with the typed default value in the metadata of node type definition """ (result, error) = await ogts.load_test_file(self._test_file_with_default_values, use_caller_subdirectory=True) self.assertTrue(result, error) compound_node_type = ogu.find_compound_node_type_by_path("/World/Compounds/Compound") self.assert_attribute_value(compound_node_type.find_input("a_bool").get_default_data(), 0) self.assert_attribute_value(compound_node_type.find_input("a_bool_array").get_default_data(), [0, 1]) self.assert_attribute_value( compound_node_type.find_input("a_colord_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_colord_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_colord_4").get_default_data(), [0.01625, 0.14125, 0.26625, 0.39125] ) self.assert_attribute_value( compound_node_type.find_input("a_colord_4_array").get_default_data(), [[0.01625, 0.14125, 0.26625, 0.39125], [0.39125, 0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_colorf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_colorf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value( compound_node_type.find_input("a_colorf_4").get_default_data(), [0.125, 0.25, 0.375, 0.5] ) self.assert_attribute_value( compound_node_type.find_input("a_colorf_4_array").get_default_data(), [[0.125, 0.25, 0.375, 0.5], [0.5, 0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_colorh_3").get_default_data(), [0.5, 0.625, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_colorh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) self.assert_attribute_value( compound_node_type.find_input("a_colorh_4").get_default_data(), [0.5, 0.625, 0.75, 0.875] ) self.assert_attribute_value( compound_node_type.find_input("a_colorh_4_array").get_default_data(), [[0.5, 0.625, 0.75, 0.875], [0.875, 0.75, 0.625, 0.5]], ) self.assert_attribute_value(compound_node_type.find_input("a_double").get_default_data(), 4.125) self.assert_attribute_value(compound_node_type.find_input("a_double_2").get_default_data(), [4.125, 4.25]) self.assert_attribute_value( compound_node_type.find_input("a_double_2_array").get_default_data(), [[4.125, 4.25], [2.125, 2.25]] ) self.assert_attribute_value( compound_node_type.find_input("a_double_3").get_default_data(), [4.125, 4.25, 4.375] ) self.assert_attribute_value( compound_node_type.find_input("a_double_3_array").get_default_data(), [[4.125, 4.25, 4.375], [2.125, 2.25, 2.375]], ) self.assert_attribute_value( compound_node_type.find_input("a_double_4").get_default_data(), [4.125, 4.25, 4.375, 4.5] ) self.assert_attribute_value( compound_node_type.find_input("a_double_4_array").get_default_data(), [[4.125, 4.25, 4.375, 4.5], [2.125, 2.25, 2.375, 2.5]], ) self.assert_attribute_value(compound_node_type.find_input("a_double_array").get_default_data(), [4.125, 2.125]) self.assert_attribute_value(compound_node_type.find_input("a_execution").get_default_data(), 0) self.assert_attribute_value(compound_node_type.find_input("a_float").get_default_data(), 4.5) self.assert_attribute_value(compound_node_type.find_input("a_float_2").get_default_data(), [4.5, 4.625]) self.assert_attribute_value( compound_node_type.find_input("a_float_2_array").get_default_data(), [[4.5, 4.625], [2.5, 2.625]] ) self.assert_attribute_value(compound_node_type.find_input("a_float_3").get_default_data(), [4.5, 4.625, 4.75]) self.assert_attribute_value( compound_node_type.find_input("a_float_3_array").get_default_data(), [[4.5, 4.625, 4.75], [2.5, 2.625, 2.75]], ) self.assert_attribute_value( compound_node_type.find_input("a_float_4").get_default_data(), [4.5, 4.625, 4.75, 4.875] ) self.assert_attribute_value( compound_node_type.find_input("a_float_4_array").get_default_data(), [[4.5, 4.625, 4.75, 4.875], [2.5, 2.625, 2.75, 2.875]], ) self.assert_attribute_value(compound_node_type.find_input("a_float_array").get_default_data(), [4.5, 2.5]) self.assert_attribute_value( compound_node_type.find_input("a_frame_4").get_default_data(), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], ) self.assert_attribute_value( compound_node_type.find_input("a_frame_4_array").get_default_data(), [ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[2, 3, 3, 3], [3, 2, 3, 3], [3, 3, 2, 3], [3, 3, 3, 2]], ], ) self.assert_attribute_value(compound_node_type.find_input("a_half").get_default_data(), 2.5) self.assert_attribute_value(compound_node_type.find_input("a_half_2").get_default_data(), [2.5, 2.625]) self.assert_attribute_value( compound_node_type.find_input("a_half_2_array").get_default_data(), [[2.5, 2.625], [4.5, 4.625]] ) self.assert_attribute_value(compound_node_type.find_input("a_half_3").get_default_data(), [2.5, 2.625, 2.75]) self.assert_attribute_value( compound_node_type.find_input("a_half_3_array").get_default_data(), [[2.5, 2.625, 2.75], [4.5, 4.625, 4.75]] ) self.assert_attribute_value( compound_node_type.find_input("a_half_4").get_default_data(), [2.5, 2.625, 2.75, 2.875] ) self.assert_attribute_value( compound_node_type.find_input("a_half_4_array").get_default_data(), [[2.5, 2.625, 2.75, 2.875], [4.5, 4.625, 4.75, 4.875]], ) self.assert_attribute_value(compound_node_type.find_input("a_half_array").get_default_data(), [2.5, 4.5]) self.assert_attribute_value(compound_node_type.find_input("a_int").get_default_data(), -32) self.assert_attribute_value(compound_node_type.find_input("a_int64").get_default_data(), -46) self.assert_attribute_value(compound_node_type.find_input("a_int64_array").get_default_data(), [-46, -64]) self.assert_attribute_value(compound_node_type.find_input("a_int_2").get_default_data(), [-32, -31]) self.assert_attribute_value( compound_node_type.find_input("a_int_2_array").get_default_data(), [[-32, -31], [-23, -22]] ) self.assert_attribute_value(compound_node_type.find_input("a_int_3").get_default_data(), [-32, -31, -30]) self.assert_attribute_value( compound_node_type.find_input("a_int_3_array").get_default_data(), [[-32, -31, -30], [-23, -22, -21]] ) self.assert_attribute_value(compound_node_type.find_input("a_int_4").get_default_data(), [-32, -31, -30, -29]) self.assert_attribute_value( compound_node_type.find_input("a_int_4_array").get_default_data(), [[-32, -31, -30, -29], [-23, -22, -21, -20]], ) self.assert_attribute_value(compound_node_type.find_input("a_int_array").get_default_data(), [-32, -23]) self.assert_attribute_value(compound_node_type.find_input("a_matrixd_2").get_default_data(), [[1, 0], [0, 1]]) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_2_array").get_default_data(), [[[1, 0], [0, 1]], [[2, 3], [3, 2]]] ) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_3").get_default_data(), [[1, 0, 0], [0, 1, 0], [0, 0, 1]] ) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_3_array").get_default_data(), [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[2, 3, 3], [3, 2, 3], [3, 3, 2]]], ) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_4").get_default_data(), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], ) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_4_array").get_default_data(), [ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[2, 3, 3, 3], [3, 2, 3, 3], [3, 3, 2, 3], [3, 3, 3, 2]], ], ) self.assert_attribute_value( compound_node_type.find_input("a_normald_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_normald_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_normalf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_normalf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_normalh_3").get_default_data(), [0.5, 0.625, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_normalh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) self.assert_attribute_value(compound_node_type.find_input("a_objectId").get_default_data(), 46) self.assert_attribute_value(compound_node_type.find_input("a_objectId_array").get_default_data(), [46, 64]) self.assert_attribute_value(compound_node_type.find_input("a_path").get_default_data(), "/This/Is") self.assert_attribute_value( compound_node_type.find_input("a_pointd_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_pointd_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_pointf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_pointf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_pointh_3").get_default_data(), [0.5, 0.625, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_pointh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) self.assert_attribute_value( compound_node_type.find_input("a_quatd_4").get_default_data(), [0.01625, 0.14125, 0.26625, 0.78] ) self.assert_attribute_value( compound_node_type.find_input("a_quatd_4_array").get_default_data(), [[0.01625, 0.14125, 0.26625, 0.78], [0.14125, 0.26625, 0.39125, 0.51625]], ) self.assert_attribute_value( compound_node_type.find_input("a_quatf_4").get_default_data(), [0.125, 0.25, 0.375, 0.5] ) self.assert_attribute_value( compound_node_type.find_input("a_quatf_4_array").get_default_data(), [[0.125, 0.25, 0.375, 0.5], [0.25, 0.375, 0.5, 0.625]], ) self.assert_attribute_value(compound_node_type.find_input("a_quath_4").get_default_data(), [0, 0.25, 0.5, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_quath_4_array").get_default_data(), [[0, 0.25, 0.5, 0.75], [0.125, 0.375, 0.625, 0.875]], ) self.assert_attribute_value(compound_node_type.find_input("a_string").get_default_data(), "Anakin") self.assert_attribute_value( compound_node_type.find_input("a_texcoordd_2").get_default_data(), [0.01625, 0.14125] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordd_2_array").get_default_data(), [[0.01625, 0.14125], [0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordd_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordd_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(compound_node_type.find_input("a_texcoordf_2").get_default_data(), [0.125, 0.25]) self.assert_attribute_value( compound_node_type.find_input("a_texcoordf_2_array").get_default_data(), [[0.125, 0.25], [0.25, 0.125]] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_texcoordh_2").get_default_data(), [0.5, 0.625]) self.assert_attribute_value( compound_node_type.find_input("a_texcoordh_2_array").get_default_data(), [[0.5, 0.625], [0.625, 0.5]] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordh_3").get_default_data(), [0.5, 0.625, 0.75] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) self.assert_attribute_value(compound_node_type.find_input("a_timecode").get_default_data(), 5) self.assert_attribute_value(compound_node_type.find_input("a_timecode_array").get_default_data(), [5, 6]) self.assert_attribute_value(compound_node_type.find_input("a_token").get_default_data(), "Ahsoka") self.assert_attribute_value( compound_node_type.find_input("a_token_array").get_default_data(), ["Ahsoka", "Tano"] ) self.assert_attribute_value(compound_node_type.find_input("a_uchar").get_default_data(), 12) self.assert_attribute_value(compound_node_type.find_input("a_uchar_array").get_default_data(), [12, 8]) self.assert_attribute_value(compound_node_type.find_input("a_uint").get_default_data(), 32) self.assert_attribute_value(compound_node_type.find_input("a_uint64").get_default_data(), 46) self.assert_attribute_value(compound_node_type.find_input("a_uint64_array").get_default_data(), [46, 64]) self.assert_attribute_value(compound_node_type.find_input("a_uint_array").get_default_data(), [32, 23]) self.assert_attribute_value( compound_node_type.find_input("a_vectord_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_vectord_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_vectorf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_vectorf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_vectorh_3").get_default_data(), [0.5, 0.625, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_vectorh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) # create a graph that uses the compound graph keys = og.Controller.Keys controller = og.Controller() (_, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound", f"{self.get_compound_folder()}/Compound"), ] }, ) node = nodes[0] # validate that the generated nodes have the proper default set as well. self.assert_attribute_value(node.get_attribute("inputs:a_bool").get(), 0) self.assert_attribute_value(node.get_attribute("inputs:a_bool_array").get(), [0, 1]) self.assert_attribute_value(node.get_attribute("inputs:a_colord_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_colord_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_colord_4").get(), [0.01625, 0.14125, 0.26625, 0.39125]) self.assert_attribute_value( node.get_attribute("inputs:a_colord_4_array").get(), [[0.01625, 0.14125, 0.26625, 0.39125], [0.39125, 0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_colorf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_colorf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_colorf_4").get(), [0.125, 0.25, 0.375, 0.5]) self.assert_attribute_value( node.get_attribute("inputs:a_colorf_4_array").get(), [[0.125, 0.25, 0.375, 0.5], [0.5, 0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_colorh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_colorh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_colorh_4").get(), [0.5, 0.625, 0.75, 0.875]) self.assert_attribute_value( node.get_attribute("inputs:a_colorh_4_array").get(), [[0.5, 0.625, 0.75, 0.875], [0.875, 0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_double").get(), 4.125) self.assert_attribute_value(node.get_attribute("inputs:a_double_2").get(), [4.125, 4.25]) self.assert_attribute_value(node.get_attribute("inputs:a_double_2_array").get(), [[4.125, 4.25], [2.125, 2.25]]) self.assert_attribute_value(node.get_attribute("inputs:a_double_3").get(), [4.125, 4.25, 4.375]) self.assert_attribute_value( node.get_attribute("inputs:a_double_3_array").get(), [[4.125, 4.25, 4.375], [2.125, 2.25, 2.375]] ) self.assert_attribute_value(node.get_attribute("inputs:a_double_4").get(), [4.125, 4.25, 4.375, 4.5]) self.assert_attribute_value( node.get_attribute("inputs:a_double_4_array").get(), [[4.125, 4.25, 4.375, 4.5], [2.125, 2.25, 2.375, 2.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_double_array").get(), [4.125, 2.125]) self.assert_attribute_value(node.get_attribute("inputs:a_execution").get(), 0) self.assert_attribute_value(node.get_attribute("inputs:a_float").get(), 4.5) self.assert_attribute_value(node.get_attribute("inputs:a_float_2").get(), [4.5, 4.625]) self.assert_attribute_value(node.get_attribute("inputs:a_float_2_array").get(), [[4.5, 4.625], [2.5, 2.625]]) self.assert_attribute_value(node.get_attribute("inputs:a_float_3").get(), [4.5, 4.625, 4.75]) self.assert_attribute_value( node.get_attribute("inputs:a_float_3_array").get(), [[4.5, 4.625, 4.75], [2.5, 2.625, 2.75]] ) self.assert_attribute_value(node.get_attribute("inputs:a_float_4").get(), [4.5, 4.625, 4.75, 4.875]) self.assert_attribute_value( node.get_attribute("inputs:a_float_4_array").get(), [[4.5, 4.625, 4.75, 4.875], [2.5, 2.625, 2.75, 2.875]] ) self.assert_attribute_value(node.get_attribute("inputs:a_float_array").get(), [4.5, 2.5]) self.assert_attribute_value( node.get_attribute("inputs:a_frame_4").get(), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] ) self.assert_attribute_value( node.get_attribute("inputs:a_frame_4_array").get(), [ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[2, 3, 3, 3], [3, 2, 3, 3], [3, 3, 2, 3], [3, 3, 3, 2]], ], ) self.assert_attribute_value(node.get_attribute("inputs:a_half").get(), 2.5) self.assert_attribute_value(node.get_attribute("inputs:a_half_2").get(), [2.5, 2.625]) self.assert_attribute_value(node.get_attribute("inputs:a_half_2_array").get(), [[2.5, 2.625], [4.5, 4.625]]) self.assert_attribute_value(node.get_attribute("inputs:a_half_3").get(), [2.5, 2.625, 2.75]) self.assert_attribute_value( node.get_attribute("inputs:a_half_3_array").get(), [[2.5, 2.625, 2.75], [4.5, 4.625, 4.75]] ) self.assert_attribute_value(node.get_attribute("inputs:a_half_4").get(), [2.5, 2.625, 2.75, 2.875]) self.assert_attribute_value( node.get_attribute("inputs:a_half_4_array").get(), [[2.5, 2.625, 2.75, 2.875], [4.5, 4.625, 4.75, 4.875]] ) self.assert_attribute_value(node.get_attribute("inputs:a_half_array").get(), [2.5, 4.5]) self.assert_attribute_value(node.get_attribute("inputs:a_int").get(), -32) self.assert_attribute_value(node.get_attribute("inputs:a_int64").get(), -46) self.assert_attribute_value(node.get_attribute("inputs:a_int64_array").get(), [-46, -64]) self.assert_attribute_value(node.get_attribute("inputs:a_int_2").get(), [-32, -31]) self.assert_attribute_value(node.get_attribute("inputs:a_int_2_array").get(), [[-32, -31], [-23, -22]]) self.assert_attribute_value(node.get_attribute("inputs:a_int_3").get(), [-32, -31, -30]) self.assert_attribute_value( node.get_attribute("inputs:a_int_3_array").get(), [[-32, -31, -30], [-23, -22, -21]] ) self.assert_attribute_value(node.get_attribute("inputs:a_int_4").get(), [-32, -31, -30, -29]) self.assert_attribute_value( node.get_attribute("inputs:a_int_4_array").get(), [[-32, -31, -30, -29], [-23, -22, -21, -20]] ) self.assert_attribute_value(node.get_attribute("inputs:a_int_array").get(), [-32, -23]) self.assert_attribute_value(node.get_attribute("inputs:a_matrixd_2").get(), [[1, 0], [0, 1]]) self.assert_attribute_value( node.get_attribute("inputs:a_matrixd_2_array").get(), [[[1, 0], [0, 1]], [[2, 3], [3, 2]]] ) self.assert_attribute_value(node.get_attribute("inputs:a_matrixd_3").get(), [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assert_attribute_value( node.get_attribute("inputs:a_matrixd_3_array").get(), [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[2, 3, 3], [3, 2, 3], [3, 3, 2]]], ) self.assert_attribute_value( node.get_attribute("inputs:a_matrixd_4").get(), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] ) self.assert_attribute_value( node.get_attribute("inputs:a_matrixd_4_array").get(), [ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[2, 3, 3, 3], [3, 2, 3, 3], [3, 3, 2, 3], [3, 3, 3, 2]], ], ) self.assert_attribute_value(node.get_attribute("inputs:a_normald_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_normald_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_normalf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_normalf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_normalh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_normalh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_objectId").get(), 46) self.assert_attribute_value(node.get_attribute("inputs:a_objectId_array").get(), [46, 64]) self.assert_attribute_value(node.get_attribute("inputs:a_path").get(), "/This/Is") self.assert_attribute_value(node.get_attribute("inputs:a_pointd_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_pointd_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_pointf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_pointf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_pointh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_pointh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_quatd_4").get(), [0.01625, 0.14125, 0.26625, 0.78]) self.assert_attribute_value( node.get_attribute("inputs:a_quatd_4_array").get(), [[0.01625, 0.14125, 0.26625, 0.78], [0.14125, 0.26625, 0.39125, 0.51625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_quatf_4").get(), [0.125, 0.25, 0.375, 0.5]) self.assert_attribute_value( node.get_attribute("inputs:a_quatf_4_array").get(), [[0.125, 0.25, 0.375, 0.5], [0.25, 0.375, 0.5, 0.625]] ) self.assert_attribute_value(node.get_attribute("inputs:a_quath_4").get(), [0, 0.25, 0.5, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_quath_4_array").get(), [[0, 0.25, 0.5, 0.75], [0.125, 0.375, 0.625, 0.875]] ) self.assert_attribute_value(node.get_attribute("inputs:a_string").get(), "Anakin") self.assert_attribute_value(node.get_attribute("inputs:a_texcoordd_2").get(), [0.01625, 0.14125]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordd_2_array").get(), [[0.01625, 0.14125], [0.14125, 0.01625]] ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordd_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordd_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordf_2").get(), [0.125, 0.25]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordf_2_array").get(), [[0.125, 0.25], [0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordh_2").get(), [0.5, 0.625]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordh_2_array").get(), [[0.5, 0.625], [0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_timecode").get(), 5) self.assert_attribute_value(node.get_attribute("inputs:a_timecode_array").get(), [5, 6]) self.assert_attribute_value(node.get_attribute("inputs:a_token").get(), "Ahsoka") self.assert_attribute_value(node.get_attribute("inputs:a_token_array").get(), ["Ahsoka", "Tano"]) self.assert_attribute_value(node.get_attribute("inputs:a_uchar").get(), 12) self.assert_attribute_value(node.get_attribute("inputs:a_uchar_array").get(), [12, 8]) self.assert_attribute_value(node.get_attribute("inputs:a_uint").get(), 32) self.assert_attribute_value(node.get_attribute("inputs:a_uint64").get(), 46) self.assert_attribute_value(node.get_attribute("inputs:a_uint64_array").get(), [46, 64]) self.assert_attribute_value(node.get_attribute("inputs:a_uint_array").get(), [32, 23]) self.assert_attribute_value(node.get_attribute("inputs:a_vectord_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_vectord_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_vectorf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_vectorf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_vectorh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_vectorh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) def _create_test_action_compound( self, compound_name, graph_name="Graph", namespace="local.nodes.", compound_dir=None ): """Creates a compound node/graph that wraps an add node""" # create a compound node (success, schema_prim) = ogu.cmds.CreateCompoundNodeType( compound_name=compound_name, graph_name=graph_name, namespace=namespace, folder=compound_dir, evaluator_type="execution", ) if not success: raise og.OmniGraphError("CreateNodeType failed") compound_path = str(schema_prim.GetPrim().GetPath()) graph_path = f"{compound_path}/{graph_name}" node_type = get_node_type_from_schema_prim(schema_prim) keys = og.Controller.Keys controller = og.Controller() (_, _, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Branch", "omni.graph.action.Branch"), ("WriteTrue", "omni.graph.nodes.WritePrimAttribute"), ("WriteFalse", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Branch.inputs:execIn"), ("Branch.outputs:execTrue", "WriteTrue.inputs:execIn"), ("Branch.outputs:execFalse", "WriteFalse.inputs:execIn"), ], keys.CREATE_PRIMS: [("/World/Prim", {"val": ("double", 0.0)})], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("WriteTrue.inputs:name", "val"), ("WriteTrue.inputs:primPath", "/World/Prim"), ("WriteTrue.inputs:usePath", True), ("WriteFalse.inputs:name", "val"), ("WriteFalse.inputs:primPath", "/World/Prim"), ("WriteFalse.inputs:usePath", True), ], }, ) # assign inputs and outputs ogu.cmds.CreateCompoundNodeTypeInput(node_type=node_type, input_name="execIn", default_type="execution") ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="valTrue", attribute_path=Sdf.Path(f"{graph_path}/WriteTrue.inputs:value"), default_type="double", ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="valFalse", attribute_path=Sdf.Path(f"{graph_path}/WriteFalse.inputs:value"), default_type="double", ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="condition", attribute_path=Sdf.Path(f"{graph_path}/Branch.inputs:condition"), default_type="bool", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="execOut", attribute_path=Sdf.Path(f"{graph_path}/WriteTrue.outputs:execOut"), default_type="execution", ) return (compound_path, graph_path) async def test_action_compounds(self): """ Test Action Graph compound nodes """ compound_path, _ = self._create_test_action_compound("ExecCompound") self._create_test_compound("PushCompound") stage = omni.usd.get_context().get_stage() push_compound_path = f"{self.get_compound_folder()}/PushCompound" # create a graph that uses the compound graph keys = og.Controller.Keys controller = og.Controller() (graph, (exec_node, push_node, _, _, _, _), _, _) = controller.edit( {"graph_path": self._test_graph_path, "evaluator_name": "execution"}, { keys.CREATE_NODES: [ ("ExecCompound", compound_path), ("PushCompound", push_compound_path), ("OnTick", "omni.graph.action.OnTick"), ("Constant1", "omni.graph.nodes.ConstantDouble"), ("Constant2", "omni.graph.nodes.ConstantDouble"), ("ConstantBool", "omni.graph.nodes.ConstantBool"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "ExecCompound.inputs:execIn"), ("Constant1.inputs:value", "PushCompound.inputs:input_a"), ("Constant2.inputs:value", "PushCompound.inputs:input_b"), ("PushCompound.outputs:value", "ExecCompound.inputs:valTrue"), ("Constant2.inputs:value", "ExecCompound.inputs:valFalse"), ("ConstantBool.inputs:value", "ExecCompound.inputs:condition"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 1.0), ("Constant2.inputs:value", 2.0), ("ConstantBool.inputs:value", False), ("OnTick.inputs:onlyPlayback", False), ], }, ) await og.Controller.evaluate(graph) self.assertTrue(bool(exec_node.get_compound_graph_instance())) self.assertEqual(len(exec_node.get_compound_graph_instance().get_nodes()), 4) self.assertTrue(bool(push_node.get_compound_graph_instance())) stage = omni.usd.get_context().get_stage() self.assertEqual(stage.GetAttributeAtPath("/World/Prim.val").Get(), 2.0) # Set the Branch to go to WriteTrue, which will take the value from PushCompound.outputs:value # which should be 1.0 + 2.0 controller.edit(self._test_graph_path, {keys.SET_VALUES: ("ConstantBool.inputs:value", True)}) await og.Controller.evaluate(graph) self.assertEqual(stage.GetAttributeAtPath("/World/Prim.val").Get(), 3.0) # ------------------------------------------------------------------------- async def test_compound_node_upgrade_to_schema_api(self): """ Tests that loading a file with a compound node generated prior to the introduction of compoundNodeAPI gets properly migrated. """ # The preschema file contains a graph with a simple compound node # [Constant]->| Compound Node |->[Absolute] # [Constant]->| | # # With a compound defined as # [Add]->[Absolute] # The constants are set to 1 and 2, so the result trivially evaluates to 3 (result, error) = await ogts.load_test_file(self._test_preschema_file, use_caller_subdirectory=True) self.assertTrue(result, error) stage = omni.usd.get_context().get_stage() graph_prim_path = "/World/PushGraph" compound_path = f"{graph_prim_path}/Compound" result_path = f"{graph_prim_path}/absolute_01.outputs:absolute" # validate the graph evaluates as expeected graph = og.Controller.graph(graph_prim_path) await og.Controller.evaluate(graph) self.assertTrue(graph.is_valid()) attr = og.Controller.attribute(result_path) self.assertTrue(attr.is_valid()) self.assertEqual(3, og.Controller.get(attr)) # validate the compound node USD is upgraded as expected compound_node_prim = stage.GetPrimAtPath(compound_path) self.assertTrue(compound_node_prim.IsValid()) # the old relationship has been removed, and replaced with the schemaAPI self.assertFalse(compound_node_prim.GetRelationship("omni:graph:compound").IsValid()) self.assertTrue(compound_node_prim.HasAPI(OmniGraphSchema.CompoundNodeAPI)) schema_api = OmniGraphSchema.CompoundNodeAPI(compound_node_prim) self.assertGreater(len(schema_api.GetCompoundGraphRel().GetTargets()), 0) self.assertEqual(schema_api.GetCompoundTypeAttr().Get(), "nodetype") # ------------------------------------------------------------------------- async def test_enter_compound(self): """ Test that querying a node in a compound subgraph will pass validation. This exercises a code-path that is used by kit-graphs when you double-click and enter a compound. The graph itself remains the top-level graph (as this is set in the graph model), but we are able to step in and look at nodes in a child graph """ self._create_test_compound("Compound") self._create_and_test_graph_from_add_compound(f"{self.get_compound_folder()}/Compound") # Verify that we do not get an error in ObjectLookup __verify_graph node = og.Controller.node( f"{self._test_graph_path}/Compound/Graph/Add_Node", og.get_graph_by_path(self._test_graph_path) ) self.assertTrue(node.is_valid()) # ------------------------------------------------------------------------- async def test_get_owning_compound_node_api(self): """ Tests the og.graph.get_owning_compound_node_api available on og.Graph. """ controller = og.Controller(update_usd=True) keys = controller.Keys # Simple graph with nested compounds (graph, (compound_1, compound_2), _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound1", { keys.CREATE_NODES: [ ("Add1", "omni.graph.nodes.Add"), ( "Compound3", { keys.CREATE_NODES: [ ("Add3", "omni.graph.nodes.Add"), ] }, ), ], }, ), ( "Compound2", { keys.CREATE_NODES: [ ("Add2", "omni.graph.nodes.Add"), ] }, ), ], }, ) self.assertTrue(graph.is_valid()) self.assertFalse(graph.get_owning_compound_node().is_valid()) compound_graph_1 = compound_1.get_compound_graph_instance() compound_graph_2 = compound_2.get_compound_graph_instance() self.assertTrue(compound_graph_1.is_valid()) self.assertTrue(compound_graph_2.is_valid()) compound_3 = node_map["Compound3"] self.assertTrue(compound_3.is_valid()) compound_graph_3 = compound_3.get_compound_graph_instance() self.assertTrue(compound_graph_3.is_valid()) self.assertEqual(compound_graph_1.get_owning_compound_node(), compound_1) self.assertEqual(compound_graph_2.get_owning_compound_node(), compound_2) self.assertEqual(compound_graph_3.get_owning_compound_node(), compound_3) self.assertEqual(compound_3.get_graph().get_owning_compound_node(), compound_1) self.assertFalse(compound_1.get_graph().get_owning_compound_node().is_valid()) add1 = node_map["Add1"] self.assertEquals(add1.get_graph().get_owning_compound_node(), compound_1) add2 = node_map["Add2"] self.assertEquals(add2.get_graph().get_owning_compound_node(), compound_2) add3 = node_map["Add3"] self.assertEquals(add3.get_graph().get_owning_compound_node(), compound_3)
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_maneuver_nodes.py
"""Misc collection of tests for nodes in this extension""" from typing import List import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.stage_templates import omni.kit.test import omni.timeline import omni.usd from pxr import Gf, Sdf, Usd, UsdGeom # Result of this does not match the matrix by generating attributes individually def _generate_random_transform_matrix(): translate = Gf.Vec3d((np.random.rand(3) * 300).tolist()) euler = Gf.Vec3d((np.random.rand(3) * 360).tolist()) scale = Gf.Vec3d((np.random.rand(3) * 5).tolist()) rotation = ( Gf.Rotation(Gf.Vec3d.ZAxis(), euler[2]) * Gf.Rotation(Gf.Vec3d.YAxis(), euler[1]) * Gf.Rotation(Gf.Vec3d.XAxis(), euler[0]) ) return Gf.Matrix4d().SetScale(scale) * Gf.Matrix4d().SetRotate(rotation) * Gf.Matrix4d().SetTranslate(translate) def _generate_random_prim_transform_attributes(prim, use_orient, want_rotation): translate = Gf.Vec3d((np.random.random_integers(-100, 100, 3)).tolist()) euler = Gf.Vec3d((np.random.random_integers(0, 720, 3)).tolist()) if want_rotation else Gf.Vec3d() scale = Gf.Vec3d((np.random.random_integers(1, 10, 3)).tolist()) prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(translate) prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(scale) if use_orient: rotation = ( ( Gf.Rotation(Gf.Vec3d.XAxis(), euler[0]) * Gf.Rotation(Gf.Vec3d.YAxis(), euler[1]) * Gf.Rotation(Gf.Vec3d.ZAxis(), euler[2]) ) if want_rotation else Gf.Rotation().SetIdentity() ) quat = rotation.GetQuat() prim.CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set(quat) prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:orient", "xformOp:scale"] ) else: prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(euler) prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] ) return translate, euler, scale # TODO: fix the bug in OM-46746 related to non-uniform scale in parent def _generate_test_prims(stage, suffix: str, use_orient=True, want_rotation=True) -> List[Usd.Prim]: # No Hierarchy case source1 = stage.DefinePrim(f"/World/Cube{suffix}1", "Cube") _generate_random_prim_transform_attributes(source1, use_orient, want_rotation) # source1.GetAttribute("xformOp:scale").Set(Gf.Vec3d(1, 1, 1)) xform1 = stage.DefinePrim(f"/World/xform{suffix}1", "Cone") _generate_random_prim_transform_attributes(xform1, use_orient, want_rotation) xform1.GetAttribute("xformOp:scale").Set(Gf.Vec3d(1, 1, 1)) source2 = stage.DefinePrim(f"{xform1.GetPath()}/Cube{suffix}2", "Cube") _generate_random_prim_transform_attributes(source2, use_orient, want_rotation) xform2 = stage.DefinePrim(f"{xform1.GetPath()}/xform{suffix}2", "Xform") _generate_random_prim_transform_attributes(xform2, use_orient, want_rotation) xform2.GetAttribute("xformOp:scale").Set(Gf.Vec3d(1, 1, 1)) source3 = stage.DefinePrim(f"{xform2.GetPath()}/Cube{suffix}3", "Cube") _generate_random_prim_transform_attributes(source3, use_orient, want_rotation) # Negative Scale case source4 = stage.DefinePrim(f"/World/Cube{suffix}4", "Cube") _generate_random_prim_transform_attributes(source4, use_orient, want_rotation) source4.GetAttribute("xformOp:scale").Set(Gf.Vec3d(np.random.uniform(-2, 2, 3).tolist())) return [source1, source2, source3] def _add_inputs_prim(stage, node: og.Node, src_prim: Usd.Prim, attrib: str): """Connect the given prim to the given Node's input attrib""" omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{node.get_prim_path()}.inputs:{attrib}"), target=src_prim.GetPath(), ) def _remove_inputs_prim(stage, node: og.Node, target_prim: Usd.Prim, attrib: str): """Remove the given prim to the given Node's input attrib""" omni.kit.commands.execute( "RemoveRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{node.get_prim_path()}.inputs:{attrib}"), target=target_prim.GetPath(), ) # ====================================================================== class TestManeuverNodes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises nodes""" TEST_GRAPH_PATH = "/World/TestGraph" max_tries = 10 # max times to check if we have converged updates_per_try = 5 # number of frames to wait between checks async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) timeline = omni.timeline.get_timeline_interface() timeline.set_start_time(1.0) timeline.set_end_time(10.0) fps = 24.0 timeline.set_time_codes_per_second(fps) timeline.set_fast_mode(True) await omni.kit.app.get_app().next_update_async() np.random.seed(12345) # ------------------------------------------------------------------------ async def next_try_async(self): for _ in range(self.updates_per_try): await omni.kit.app.get_app().next_update_async() # ------------------------------------------------------------------------ async def test_move_to_target(self): """Test OgnMoveToTarget node""" keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() for use_orient_src, use_orient_target in [(True, True), (True, False)]: controller = og.Controller() sources = _generate_test_prims(stage, "Source", use_orient=use_orient_src) # We don't support interpolation rotation without orient want_rotation = use_orient_src targets = _generate_test_prims(stage, "Target", use_orient=use_orient_target, want_rotation=want_rotation) (graph, (_, move_to_target_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("MoveToTarget", "omni.graph.nodes.MoveToTarget"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "MoveToTarget.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("MoveToTarget.inputs:speed", 5), ], }, ) def check_progress(src: Usd.Prim, target: Usd.Prim) -> bool: xform_cache = UsdGeom.XformCache() final_transform = xform_cache.GetLocalToWorldTransform(src) target_transform = xform_cache.GetLocalToWorldTransform(target) ok = Gf.IsClose(target_transform.Transform(Gf.Vec3d()), final_transform.Transform(Gf.Vec3d()), 0.0001) if ok: rot = target_transform.ExtractRotation().Decompose( Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis() ) rot2 = final_transform.ExtractRotation().Decompose( Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis() ) ok = Gf.IsClose(rot, rot2, 0.0001) if ok: ok = ( Gf.IsClose( target_transform.Transform(Gf.Vec3d.XAxis()).GetLength(), final_transform.Transform(Gf.Vec3d.XAxis()).GetLength(), 0.0001, ) and Gf.IsClose( target_transform.Transform(Gf.Vec3d.YAxis()).GetLength(), final_transform.Transform(Gf.Vec3d.YAxis()).GetLength(), 0.0001, ) and Gf.IsClose( target_transform.Transform(Gf.Vec3d.ZAxis()).GetLength(), final_transform.Transform(Gf.Vec3d.ZAxis()).GetLength(), 0.0001, ) ) if ok: return True return False for src in sources: for target in targets: _add_inputs_prim(stage, move_to_target_node, src, "sourcePrim") _add_inputs_prim(stage, move_to_target_node, target, "targetPrim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() if check_progress(src, target): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, move_to_target_node, src, "sourcePrim") _remove_inputs_prim(stage, move_to_target_node, target, "targetPrim") omni.kit.commands.execute("DeletePrims", paths=[graph.get_path_to_graph()]) # ------------------------------------------------------------------------ async def test_move_to_transform(self): """Test OgnMoveToTransform node""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") target_transform = _generate_random_transform_matrix() (_, (_, move_to_transform_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("MoveToTransform", "omni.graph.nodes.MoveToTransform"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "MoveToTransform.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("MoveToTransform.inputs:speed", 5), ("MoveToTransform.inputs:target", target_transform), ], }, ) for src in sources: _add_inputs_prim(stage, move_to_transform_node, src, "prim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() src_xformable = UsdGeom.Xformable(src) # Move To Transform only moves to Local Transform final_transform = src_xformable.GetLocalTransformation() if Gf.IsClose(target_transform, final_transform, 0.00001): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, move_to_transform_node, src, "prim") # # ------------------------------------------------------------------------ async def test_scale_to_size(self): """Test OgnScaleToSize node""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") target_scale = Gf.Vec3f(np.random.rand(3).tolist()) (_, (_, scale_to_size_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("ScaleToSize", "omni.graph.nodes.ScaleToSize"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "ScaleToSize.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("ScaleToSize.inputs:speed", 5), ("ScaleToSize.inputs:target", target_scale), ], }, ) for src in sources: _add_inputs_prim(stage, scale_to_size_node, src, "prim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() final_scale = UsdGeom.XformCommonAPI(src).GetXformVectors(Usd.TimeCode.Default())[2] if Gf.IsClose(target_scale, final_scale, 0.00001): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, scale_to_size_node, src, "prim") # # ------------------------------------------------------------------------ async def test_translate_to_location(self): """Test OgnTranslateToLocation node""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() await omni.kit.app.get_app().next_update_async() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") target_translation = Gf.Vec3d(np.random.rand(3).tolist()) (_, (_, translate_to_location_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("TranslateToLocation", "omni.graph.nodes.TranslateToLocation"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "TranslateToLocation.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("TranslateToLocation.inputs:speed", 5), ("TranslateToLocation.inputs:target", target_translation), ], }, ) for src in sources: _add_inputs_prim(stage, translate_to_location_node, src, "prim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() final_translation = UsdGeom.XformCommonAPI(src).GetXformVectors(Usd.TimeCode.Default())[0] if Gf.IsClose(target_translation, final_translation, 0.00001): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, translate_to_location_node, src, "prim") # ------------------------------------------------------------------------ async def test_translate_to_target(self): """Test OgnTranslateToTarget node""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") targets = _generate_test_prims(stage, "Target") (_, (_, translate_to_target_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("TranslateToTarget", "omni.graph.nodes.TranslateToTarget"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "TranslateToTarget.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("TranslateToTarget.inputs:speed", 5), ], }, ) for src in sources: for target in targets: _add_inputs_prim(stage, translate_to_target_node, src, "sourcePrim") _add_inputs_prim(stage, translate_to_target_node, target, "targetPrim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() xform_cache = UsdGeom.XformCache() final_translation = Gf.Transform(xform_cache.GetLocalToWorldTransform(src)).GetTranslation() target_translation = Gf.Transform(xform_cache.GetLocalToWorldTransform(target)).GetTranslation() if Gf.IsClose(target_translation, final_translation, 0.00001): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, translate_to_target_node, src, "sourcePrim") _remove_inputs_prim(stage, translate_to_target_node, target, "targetPrim") # # ------------------------------------------------------------------------ async def test_rotate_to_orientation(self): """Test OgnRotateToOrientation node using orientation""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") target_rotation = Gf.Vec3f((np.random.rand(3) * 360).tolist()) (_, (_, rotate_to_orientation_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("RotateToOrientation", "omni.graph.nodes.RotateToOrientation"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "RotateToOrientation.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("RotateToOrientation.inputs:speed", 3), ("RotateToOrientation.inputs:target", target_rotation), ], }, ) for src in sources: _add_inputs_prim(stage, rotate_to_orientation_node, src, "prim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() final_rotation = UsdGeom.XformCommonAPI(src).GetXformVectors(Usd.TimeCode.Default())[1] for value in zip(target_rotation, final_rotation): target_angle = np.mod(value[0], 360) final_angle = np.mod(value[1], 360) if Gf.IsClose(target_angle, final_angle, 0.0001): done = True if done: break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, rotate_to_orientation_node, src, "prim") # ------------------------------------------------------------------------ async def test_rotate_to_target(self): """Test OgnRotateToTarget node using orientation""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") targets = _generate_test_prims(stage, "Target") (_, (_, rotate_to_target_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("RotateToTarget", "omni.graph.nodes.RotateToTarget"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "RotateToTarget.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("RotateToTarget.inputs:speed", 3), ], }, ) for src in sources: for target in targets: _add_inputs_prim(stage, rotate_to_target_node, src, "sourcePrim") _add_inputs_prim(stage, rotate_to_target_node, target, "targetPrim") done = False timeline.play() for _ in range(self.max_tries): await self.next_try_async() xform_cache = UsdGeom.XformCache() target_translation = ( Gf.Transform(xform_cache.GetLocalToWorldTransform(target)).GetRotation().GetQuaternion() ) final_translation = ( Gf.Transform(xform_cache.GetLocalToWorldTransform(src)).GetRotation().GetQuaternion() ) if Gf.IsClose(target_translation.GetReal(), final_translation.GetReal(), 0.00001) and Gf.IsClose( target_translation.GetImaginary(), final_translation.GetImaginary(), 0.00001 ): done = True break _remove_inputs_prim(stage, rotate_to_target_node, src, "sourcePrim") _remove_inputs_prim(stage, rotate_to_target_node, target, "targetPrim") self.assertTrue(done, "source never reached target")
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestCoW.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.000003978038478180679, 0.000007956076728987682, -0.0000039780385918675165) } 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: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 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"] } def OmniGraph "PushGraph" { token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 5) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "test_node_exercise_datamodel_features_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:arrayShouldMatch = 0 custom token inputs:attrib = "points" custom int inputs:bundleArraysThatShouldDiffer = 0 custom bool inputs:bundleShouldMatch = 1 custom point3f[] inputs:mutArray = [] prepend point3f[] inputs:mutArray.connect = </World/PushGraph/extract_bundle_01.outputs:points> custom bool inputs:mutateArray = 0 custom rel inputs:mutBundle = </World/PushGraph/read_prims/outputs_primsBundle> custom point3f[] inputs:refArray = [] custom rel inputs:refBundle = </World/PushGraph/read_prim_into_bundle/outputs_primBundle> token node:type = "omni.graph.test.TestDataModel" int node:typeVersion = 1 custom point3f[] outputs:array = [] uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (798.93054, 35.40151) def Output "outputs_bundle" { } } def OmniGraphNode "test_node_exercise_datamodel_features_02" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:arrayShouldMatch = 1 custom token inputs:attrib = "" custom int inputs:bundleArraysThatShouldDiffer = 1 custom bool inputs:bundleShouldMatch = 0 custom point3f[] inputs:mutArray = [] prepend point3f[] inputs:mutArray.connect = </World/PushGraph/test_node_exercise_datamodel_features_01.outputs:array> custom bool inputs:mutateArray = 1 custom rel inputs:mutBundle = </World/PushGraph/test_node_exercise_datamodel_features_01/outputs_bundle> custom point3f[] inputs:refArray = [] prepend point3f[] inputs:refArray.connect = </World/PushGraph/extract_bundle_01.outputs:points> custom rel inputs:refBundle = </World/PushGraph/read_prim_into_bundle/outputs_primBundle> token node:type = "omni.graph.test.TestDataModel" int node:typeVersion = 1 custom point3f[] outputs:array = [(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)] uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (1216.343, 504.63733) def Output "outputs_bundle" { } } def OmniGraphNode "test_node_exercise_datamodel_features_03" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:arrayShouldMatch = 0 custom token inputs:attrib = "" custom int inputs:bundleArraysThatShouldDiffer = 0 custom bool inputs:bundleShouldMatch = 1 custom point3f[] inputs:mutArray = [] prepend point3f[] inputs:mutArray.connect = </World/PushGraph/test_node_exercise_datamodel_features_02.outputs:array> custom bool inputs:mutateArray = 0 custom rel inputs:mutBundle = </World/PushGraph/test_node_exercise_datamodel_features_02/outputs_bundle> custom point3f[] inputs:refArray = [] prepend point3f[] inputs:refArray.connect = </World/PushGraph/test_node_exercise_datamodel_features_01.outputs:array> custom rel inputs:refBundle = </World/PushGraph/test_node_exercise_datamodel_features_02/outputs_bundle> token node:type = "omni.graph.test.TestDataModel" int node:typeVersion = 1 custom point3f[] outputs:array = [] uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (1630.563, 242.6192) def Output "outputs_bundle" { } } def OmniGraphNode "read_prims" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom string inputs:attrNamesToImport = "*" custom bool inputs:computeBoundingBox = 0 custom string inputs:pathPattern = "" custom rel inputs:prims prepend rel inputs:prims = </World/Cube> custom string inputs:typePattern = "*" custom timecode inputs:usdTimecode = -1 token node:type = "omni.graph.nodes.ReadPrims" int node:typeVersion = 1 custom string state:attrNamesToImport custom bool state:computeBoundingBox = 0 custom string state:pathPattern custom uint64[] state:primPath = [] custom string state:typePattern custom timecode state:usdTimecode = -1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-585.3621, 223.36116) def Output "outputs_primsBundle" { } } def OmniGraphNode "extract_prim" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom string inputs:primPath = "/World/Cube" custom rel inputs:prims prepend rel inputs:prims = </World/PushGraph/read_prims/outputs_primsBundle> token node:type = "omni.graph.nodes.ExtractPrim" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-222.911, -93.08474) def Output "outputs_primBundle" { } } def OmniGraphNode "extract_bundle_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom rel inputs:bundle prepend rel inputs:bundle = </World/PushGraph/extract_prim/outputs_primBundle> token node:type = "omni.graph.nodes.ExtractBundle" int node:typeVersion = 3 custom int[] outputs:faceVertexCounts custom int[] outputs:faceVertexIndices custom normal3f[] outputs:normals custom point3f[] outputs:points custom float2[] outputs:primvars:st custom token outputs:sourcePrimPath custom token outputs:sourcePrimType custom token outputs:subdivisionScheme custom matrix4d outputs:worldMatrix custom double3 outputs:xformOp:rotateXYZ custom double3 outputs:xformOp:scale custom double3 outputs:xformOp:translate custom token[] outputs:xformOpOrder uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (62.313892, -138.03423) def Output "outputs_passThrough" { } } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestSimCycleDependenciesDirtyPush.usda
#usda 1.0 ( doc = """Simulation Dependency Test""" metersPerUnit = 1 upAxis = "Y" ) def Xform "defaultPrim" { def ComputeNode "time" { custom token node:type = "omni.graph.test.Time" custom int node:typeVersion = 1 custom double outputs:time custom double outputs:frame custom double outputs:fps custom double outputs:elapsedTime } def Scope "changingData" { # This is the initial value of "a". int[] a = [0] # This connection is used to update the value of "a" from the # computed results. int[] a.connect = <../graph/addEveryTime.outputs:output> # This connection to time is just to mark this prim's data # dirty on every frame. This probably won't be necessary # once we have another explicit way to demarcate the beginning # and end of an iteration. double time.connect = <../time.outputs:elapsedTime> } def Scope "unchangingData" { int[] b = [-2] } def Scope "alsoUnchangingData" { int[] c.connect = <../graph/addOnce.outputs:output> } def Scope "graph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "dirty_push" } # This node should run only once, since its inputs # aren't marked dirty on every frame. def ComputeNode "addOnce" { custom token node:type = "omni.graph.nodes.Add2IntegerArrays" int node:typeVersion = 1 int[] inputs:a = [3] int[] inputs:b.connect = <../../unchangingData.b> int[] outputs:output } # This node should re-run every frame, since "changingData" # is marked dirty on every frame, and this node's # "inputs:a" has a connection to it. def ComputeNode "addEveryTime" { custom token node:type = "omni.graph.nodes.Add2IntegerArrays" int node:typeVersion = 1 int[] inputs:a.connect = <../../changingData.a> int[] inputs:b.connect = <../addOnce.outputs:output> int[] outputs:output } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestScriptNode.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 = { } } dictionary renderSettings = { } } 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 GlobalComputeGraph "ActionGraph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "execution" custom int2 fileFormatVersion = (1, 2) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStageSimulation" } def ComputeNode "script_node" { custom double inputs:data prepend double inputs:data.connect = </World/ActionGraph/constant_double.inputs:value> custom uint inputs:execIn prepend uint inputs:execIn.connect = </World/ActionGraph/on_impulse_event.outputs:execOut> custom double inputs:multiplier = 2 custom int outputs:asInt = 0 custom float state:asFloat = 0 custom string inputs:script = '''""" Test Script """ # output is multiplied by dynamic attrib defined in the USD db.outputs.data = db.inputs.data * db.inputs.multiplier db.outputs.asInt = int(db.outputs.data) db.state.asFloat = float(db.outputs.asInt) ''' custom token node:type = "omni.graph.scriptnode.ScriptNode" custom int node:typeVersion = 1 custom double outputs:data custom uint outputs:execOut } def ComputeNode "constant_double" { custom double inputs:value = 42 custom token node:type = "omni.graph.nodes.ConstantDouble" custom int node:typeVersion = 1 } def ComputeNode "on_impulse_event" { custom token node:type = "omni.graph.action.OnImpulseEvent" custom int node:typeVersion = 1 custom uint outputs:execOut custom bool state:enableImpulse } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestDynamicExtendedAttributes.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 = { } } dictionary renderSettings = { } } metersPerUnit = 0.01 timeCodesPerSecond = 24 upAxis = "Y" ) def ComputeNode "node" { custom uint inputs:value = 127 custom token node:type = "omni.graph.tutorials.DynamicAttributes" custom int node:typeVersion = 1 custom uint outputs:result custom uint outputs:exec ( customData = { bool ExecutionType = 1 } ) custom token outputs:any ( customData = { string ExtendedAttributeType = "Any" } ) custom token outputs:union ( customData = { string ExtendedAttributeType = "Union-->int,double[3],float[3]" } ) } def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 2) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStageSimulation" }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestBadNodeTypeName.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000.00111758711) double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (-0.0000039780381939635845, 0.000007956076956361358, -0.000003978038478180679) } dictionary Right = { double3 position = (-50000.00111758711, 0, 0) double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double3 position = (0, 50000.00111758711, 0) double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 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 OmniGraph "innerPushGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 4) def OmniGraphNode "test_node_subtract_double_c_" { custom double inputs:a = 0 custom double inputs:b = 0 token node:type = "omni.graph.FOO" # omni.graph.test.SubtractDoubleC int node:typeVersion = 1 custom double outputs:out } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestCompoundSubgraph.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.000003978038478180679, 0.000007956076728987682, -0.0000039780385918675165) } 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 = { string authoring_layer = "./TestCompoundSubgraph.usda" dictionary muteness = { } } dictionary renderSettings = { } } 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 OmniGraph "PushGraph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 6) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "compound" ( prepend apiSchemas = ["NodeGraphNodeAPI", "OmniGraphCompoundNodeAPI"] ) { custom token inputs:a ( customData = { string ExtendedAttributeType = "Union-->uchar,int,uint,uint64,int64,double,float,half,timecode,int[2],int[3],int[4],double[2],double[3],double[4],float[2],float[3],float[4],half[2],half[3],half[4],colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],quatd[4],quatf[4],quath[4],vectord[3],vectorf[3],vectorh[3],matrixd[3],matrixd[4],transform[4],frame[4],uchar[],int[],uint[],uint64[],int64[],double[],float[],half[],timecode[],int[2][],int[3][],int[4][],double[2][],double[3][],double[4][],float[2][],float[3][],float[4][],half[2][],half[3][],half[4][],colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],quatd[4][],quatf[4][],quath[4][],vectord[3][],vectorf[3][],vectorh[3][],matrixd[3][],matrixd[4][],transform[4][],frame[4][]" dictionary omni = { dictionary graph = { string attrType = "Union-->uchar,int,uint,uint64,int64,double,float,half,timecode,int[2],int[3],int[4],double[2],double[3],double[4],float[2],float[3],float[4],half[2],half[3],half[4],colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],quatd[4],quatf[4],quath[4],vectord[3],vectorf[3],vectorh[3],matrixd[3],matrixd[4],transform[4],frame[4],uchar[],int[],uint[],uint64[],int64[],double[],float[],half[],timecode[],int[2][],int[3][],int[4][],double[2][],double[3][],double[4][],float[2][],float[3][],float[4][],half[2][],half[3][],half[4][],colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],quatd[4][],quatf[4][],quath[4][],vectord[3][],vectorf[3][],vectorh[3][],matrixd[3][],matrixd[4][],transform[4][],frame[4][]" } } } ) prepend token inputs:a.connect = </World/PushGraph/constant_double.inputs:value> custom token inputs:b ( customData = { string ExtendedAttributeType = "Union-->uchar,int,uint,uint64,int64,double,float,half,timecode,int[2],int[3],int[4],double[2],double[3],double[4],float[2],float[3],float[4],half[2],half[3],half[4],colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],quatd[4],quatf[4],quath[4],vectord[3],vectorf[3],vectorh[3],matrixd[3],matrixd[4],transform[4],frame[4],uchar[],int[],uint[],uint64[],int64[],double[],float[],half[],timecode[],int[2][],int[3][],int[4][],double[2][],double[3][],double[4][],float[2][],float[3][],float[4][],half[2][],half[3][],half[4][],colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],quatd[4][],quatf[4][],quath[4][],vectord[3][],vectorf[3][],vectorh[3][],matrixd[3][],matrixd[4][],transform[4][],frame[4][]" dictionary omni = { dictionary graph = { string attrType = "Union-->uchar,int,uint,uint64,int64,double,float,half,timecode,int[2],int[3],int[4],double[2],double[3],double[4],float[2],float[3],float[4],half[2],half[3],half[4],colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],quatd[4],quatf[4],quath[4],vectord[3],vectorf[3],vectorh[3],matrixd[3],matrixd[4],transform[4],frame[4],uchar[],int[],uint[],uint64[],int64[],double[],float[],half[],timecode[],int[2][],int[3][],int[4][],double[2][],double[3][],double[4][],float[2][],float[3][],float[4][],half[2][],half[3][],half[4][],colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],quatd[4][],quatf[4][],quath[4][],vectord[3][],vectorf[3][],vectorh[3][],matrixd[3][],matrixd[4][],transform[4][],frame[4][]" } } } ) prepend token inputs:b.connect = </World/PushGraph/constant_double.inputs:value> token node:type = "omni.graph.nodes.CompoundSubgraph" int node:typeVersion = 1 rel omni:graph:compoundGraph = </World/PushGraph/compound/SubGraph_01> token omni:graph:compoundType = "nodetype" custom token outputs:sum ( customData = { string ExtendedAttributeType = "Union-->uchar,int,uint,uint64,int64,double,float,half,timecode,int[2],int[3],int[4],double[2],double[3],double[4],float[2],float[3],float[4],half[2],half[3],half[4],colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],quatd[4],quatf[4],quath[4],vectord[3],vectorf[3],vectorh[3],matrixd[3],matrixd[4],transform[4],frame[4],uchar[],int[],uint[],uint64[],int64[],double[],float[],half[],timecode[],int[2][],int[3][],int[4][],double[2][],double[3][],double[4][],float[2][],float[3][],float[4][],half[2][],half[3][],half[4][],colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],quatd[4][],quatf[4][],quath[4][],vectord[3][],vectorf[3][],vectorh[3][],matrixd[3][],matrixd[4][],transform[4][],frame[4][]" dictionary omni = { dictionary graph = { string attrType = "Union-->uchar,int,uint,uint64,int64,double,float,half,timecode,int[2],int[3],int[4],double[2],double[3],double[4],float[2],float[3],float[4],half[2],half[3],half[4],colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],quatd[4],quatf[4],quath[4],vectord[3],vectorf[3],vectorh[3],matrixd[3],matrixd[4],transform[4],frame[4],uchar[],int[],uint[],uint64[],int64[],double[],float[],half[],timecode[],int[2][],int[3][],int[4][],double[2][],double[3][],double[4][],float[2][],float[3][],float[4][],half[2][],half[3][],half[4][],colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],quatd[4][],quatf[4][],quath[4][],vectord[3][],vectorf[3][],vectorh[3][],matrixd[3][],matrixd[4][],transform[4][],frame[4][]" } } } ) prepend token outputs:sum.connect = </World/PushGraph/compound/SubGraph_01/Add_Node.outputs:sum> uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (176.20505, -4.6921196) def OmniGraph "SubGraph_01" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 6) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Add_Node" { custom token inputs:a prepend token inputs:a.connect = </World/PushGraph/compound.inputs:a> custom token inputs:b prepend token inputs:b.connect = </World/PushGraph/compound.inputs:b> token node:type = "omni.graph.nodes.Add" int node:typeVersion = 2 custom token outputs:sum } } } def OmniGraphNode "constant_double" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:value = 10 token node:type = "omni.graph.nodes.ConstantDouble" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-73.574936, 26.129522) } def OmniGraphNode "to_string" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:value prepend token inputs:value.connect = </World/PushGraph/compound.outputs:sum> token node:type = "omni.graph.nodes.ToString" int node:typeVersion = 1 custom string outputs:converted uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (411.59882, 12.6411705) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestCompoundWithExternalReference.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 = { } } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 subLayers = [ @./TestNodeLibrary.usda@ ] 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 OmniGraph "PushGraph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "madd" ( prepend apiSchemas = ["OmniGraphCompoundNodeAPI", "NodeGraphNodeAPI"] ) { custom token inputs:a prepend token inputs:a.connect = </World/PushGraph/constant_double.inputs:value> custom token inputs:b prepend token inputs:b.connect = </World/PushGraph/constant_double_01.inputs:value> custom token inputs:c prepend token inputs:c.connect = </World/PushGraph/constant_double_02.inputs:value> token node:type = "/World/Compounds/Madd" token node:type.connect = </World/Compounds/Madd> int node:typeVersion = 0 rel omni:graph:compoundGraph = </World/PushGraph/madd/Graph> token omni:graph:compoundType = "nodetype" custom token outputs:sum prepend token outputs:sum.connect = </World/PushGraph/madd/Graph/add.outputs:sum> uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (304, 112) def "Graph" ( prepend references = @./TestNodeLibrary.usda@</World/Compounds/Madd/Graph> ) { token evaluationMode = "Automatic" over "multiply" { custom token inputs:a prepend token inputs:a.connect = </World/PushGraph/madd.inputs:a> custom token inputs:b prepend token inputs:b.connect = </World/PushGraph/madd.inputs:b> } over "add" { custom token inputs:b prepend token inputs:b.connect = </World/PushGraph/madd.inputs:c> } } } def OmniGraphNode "constant_double" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:value = 1 token node:type = "omni.graph.nodes.ConstantDouble" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (21, 83) } def OmniGraphNode "constant_double_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:value = 2 token node:type = "omni.graph.nodes.ConstantDouble" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (19, 182) } def OmniGraphNode "constant_double_02" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:value = 3 token node:type = "omni.graph.nodes.ConstantDouble" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (15, 281) } def OmniGraphNode "magnitude" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:input prepend token inputs:input.connect = </World/PushGraph/madd.outputs:sum> 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 = (541, 123) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestAllDataTypes.NonDefault.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.00000397803842133726, 0.000007956076785831101, -0.000003978038307650422) } 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 = { int "rtx:hydra:curves:splits" = 2 double "rtx:hydra:points:defaultWidth" = 1 float3 "rtx:iray:environment_dome_rotation_axis" = (0, 1, 0) } } metersPerUnit = 0.01 timeCodesPerSecond = 24 upAxis = "Y" ) def "World" { def OmniGraph "TestGraph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "TestAllDataTypes" { custom bool inputs:a_bool = 0 custom bool[] inputs:a_bool_array = [0, 1] custom rel inputs:a_bundle custom color3d inputs:a_colord_3 = (0.01625, 0.14125, 0.26625) custom color3d[] inputs:a_colord_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom color4d inputs:a_colord_4 = (0.01625, 0.14125, 0.26625, 0.39125) custom color4d[] inputs:a_colord_4_array = [(0.01625, 0.14125, 0.26625, 0.39125), (0.39125, 0.26625, 0.14125, 0.01625)] custom color3f inputs:a_colorf_3 = (0.125, 0.25, 0.375) custom color3f[] inputs:a_colorf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom color4f inputs:a_colorf_4 = (0.125, 0.25, 0.375, 0.5) custom color4f[] inputs:a_colorf_4_array = [(0.125, 0.25, 0.375, 0.5), (0.5, 0.375, 0.25, 0.125)] custom color3h inputs:a_colorh_3 = (0.5, 0.625, 0.75) custom color3h[] inputs:a_colorh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom color4h inputs:a_colorh_4 = (0.5, 0.625, 0.75, 0.875) custom color4h[] inputs:a_colorh_4_array = [(0.5, 0.625, 0.75, 0.875), (0.875, 0.75, 0.625, 0.5)] custom double inputs:a_double = 4.125 custom double2 inputs:a_double_2 = (4.125, 4.25) custom double2[] inputs:a_double_2_array = [(4.125, 4.25), (2.125, 2.25)] custom double3 inputs:a_double_3 = (4.125, 4.25, 4.375) custom double3[] inputs:a_double_3_array = [(4.125, 4.25, 4.375), (2.125, 2.25, 2.375)] custom double4 inputs:a_double_4 = (4.125, 4.25, 4.375, 4.5) custom double4[] inputs:a_double_4_array = [(4.125, 4.25, 4.375, 4.5), (2.125, 2.25, 2.375, 2.5)] custom double[] inputs:a_double_array = [4.125, 2.125] custom uint inputs:a_execution = 0 custom float inputs:a_float = 4.5 custom float2 inputs:a_float_2 = (4.5, 4.625) custom float2[] inputs:a_float_2_array = [(4.5, 4.625), (2.5, 2.625)] custom float3 inputs:a_float_3 = (4.5, 4.625, 4.75) custom float3[] inputs:a_float_3_array = [(4.5, 4.625, 4.75), (2.5, 2.625, 2.75)] custom float4 inputs:a_float_4 = (4.5, 4.625, 4.75, 4.875) custom float4[] inputs:a_float_4_array = [(4.5, 4.625, 4.75, 4.875), (2.5, 2.625, 2.75, 2.875)] custom float[] inputs:a_float_array = [4.5, 2.5] custom frame4d inputs:a_frame_4 = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ) custom frame4d[] inputs:a_frame_4_array = [( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ), ( (2, 3, 3, 3), (3, 2, 3, 3), (3, 3, 2, 3), (3, 3, 3, 2) )] custom half inputs:a_half = 2.5 custom half2 inputs:a_half_2 = (2.5, 2.625) custom half2[] inputs:a_half_2_array = [(2.5, 2.625), (4.5, 4.625)] custom half3 inputs:a_half_3 = (2.5, 2.625, 2.75) custom half3[] inputs:a_half_3_array = [(2.5, 2.625, 2.75), (4.5, 4.625, 4.75)] custom half4 inputs:a_half_4 = (2.5, 2.625, 2.75, 2.875) custom half4[] inputs:a_half_4_array = [(2.5, 2.625, 2.75, 2.875), (4.5, 4.625, 4.75, 4.875)] custom half[] inputs:a_half_array = [2.5, 4.5] custom int inputs:a_int = -32 custom int64 inputs:a_int64 = -46 custom int64[] inputs:a_int64_array = [-46, -64] custom int2 inputs:a_int_2 = (-32, -31) custom int2[] inputs:a_int_2_array = [(-32, -31), (-23, -22)] custom int3 inputs:a_int_3 = (-32, -31, -30) custom int3[] inputs:a_int_3_array = [(-32, -31, -30), (-23, -22, -21)] custom int4 inputs:a_int_4 = (-32, -31, -30, -29) custom int4[] inputs:a_int_4_array = [(-32, -31, -30, -29), (-23, -22, -21, -20)] custom int[] inputs:a_int_array = [-32, -23] custom matrix2d inputs:a_matrixd_2 = ( (1, 0), (0, 1) ) custom matrix2d[] inputs:a_matrixd_2_array = [( (1, 0), (0, 1) ), ( (2, 3), (3, 2) )] custom matrix3d inputs:a_matrixd_3 = ( (1, 0, 0), (0, 1, 0), (0, 0, 1) ) custom matrix3d[] inputs:a_matrixd_3_array = [( (1, 0, 0), (0, 1, 0), (0, 0, 1) ), ( (2, 3, 3), (3, 2, 3), (3, 3, 2) )] custom matrix4d inputs:a_matrixd_4 = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ) custom matrix4d[] inputs:a_matrixd_4_array = [( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ), ( (2, 3, 3, 3), (3, 2, 3, 3), (3, 3, 2, 3), (3, 3, 3, 2) )] custom normal3d inputs:a_normald_3 = (0.01625, 0.14125, 0.26625) custom normal3d[] inputs:a_normald_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom normal3f inputs:a_normalf_3 = (0.125, 0.25, 0.375) custom normal3f[] inputs:a_normalf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom normal3h inputs:a_normalh_3 = (0.5, 0.625, 0.75) custom normal3h[] inputs:a_normalh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom uint64 inputs:a_objectId = 46 custom uint64[] inputs:a_objectId_array = [46, 64] custom string inputs:a_path = "/This/Is" custom point3d inputs:a_pointd_3 = (0.01625, 0.14125, 0.26625) custom point3d[] inputs:a_pointd_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom point3f inputs:a_pointf_3 = (0.125, 0.25, 0.375) custom point3f[] inputs:a_pointf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom point3h inputs:a_pointh_3 = (0.5, 0.625, 0.75) custom point3h[] inputs:a_pointh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom quatd inputs:a_quatd_4 = (0.78, 0.01625, 0.14125, 0.26625) custom quatd[] inputs:a_quatd_4_array = [(0.78, 0.01625, 0.14125, 0.26625), (0.51625, 0.14125, 0.26625, 0.39125)] custom quatf inputs:a_quatf_4 = (0.5, 0.125, 0.25, 0.375) custom quatf[] inputs:a_quatf_4_array = [(0.5, 0.125, 0.25, 0.375), (0.625, 0.25, 0.375, 0.5)] custom quath inputs:a_quath_4 = (0.75, 0, 0.25, 0.5) custom quath[] inputs:a_quath_4_array = [(0.75, 0, 0.25, 0.5), (0.875, 0.125, 0.375, 0.625)] custom string inputs:a_string = "Anakin" custom texCoord2d inputs:a_texcoordd_2 = (0.01625, 0.14125) custom texCoord2d[] inputs:a_texcoordd_2_array = [(0.01625, 0.14125), (0.14125, 0.01625)] custom texCoord3d inputs:a_texcoordd_3 = (0.01625, 0.14125, 0.26625) custom texCoord3d[] inputs:a_texcoordd_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom texCoord2f inputs:a_texcoordf_2 = (0.125, 0.25) custom texCoord2f[] inputs:a_texcoordf_2_array = [(0.125, 0.25), (0.25, 0.125)] custom texCoord3f inputs:a_texcoordf_3 = (0.125, 0.25, 0.375) custom texCoord3f[] inputs:a_texcoordf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom texCoord2h inputs:a_texcoordh_2 = (0.5, 0.625) custom texCoord2h[] inputs:a_texcoordh_2_array = [(0.5, 0.625), (0.625, 0.5)] custom texCoord3h inputs:a_texcoordh_3 = (0.5, 0.625, 0.75) custom texCoord3h[] inputs:a_texcoordh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom timecode inputs:a_timecode = 5 custom timecode[] inputs:a_timecode_array = [5, 6] custom token inputs:a_token = "Ahsoka" custom token[] inputs:a_token_array = ["Ahsoka", "Tano"] custom uchar inputs:a_uchar = 12 custom uchar[] inputs:a_uchar_array = [12, 8] custom uint inputs:a_uint = 32 custom uint64 inputs:a_uint64 = 46 custom uint64[] inputs:a_uint64_array = [46, 64] custom uint[] inputs:a_uint_array = [32, 23] custom vector3d inputs:a_vectord_3 = (0.01625, 0.14125, 0.26625) custom vector3d[] inputs:a_vectord_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom vector3f inputs:a_vectorf_3 = (0.125, 0.25, 0.375) custom vector3f[] inputs:a_vectorf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom vector3h inputs:a_vectorh_3 = (0.5, 0.625, 0.75) custom vector3h[] inputs:a_vectorh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom bool inputs:doNotCompute = 0 token node:type = "omni.graph.test.TestAllDataTypes" int node:typeVersion = 1 custom bool outputs:a_bool = 1 custom bool[] outputs:a_bool_array = [1, 0] custom color3d outputs:a_colord_3 = (1.5, 2.5, 3.5) custom color3d[] outputs:a_colord_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4d outputs:a_colord_4 = (1.5, 2.5, 3.5, 4.5) custom color4d[] outputs:a_colord_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom color3f outputs:a_colorf_3 = (1.5, 2.5, 3.5) custom color3f[] outputs:a_colorf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4f outputs:a_colorf_4 = (1.5, 2.5, 3.5, 4.5) custom color4f[] outputs:a_colorf_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom color3h outputs:a_colorh_3 = (1.5, 2.5, 3.5) custom color3h[] outputs:a_colorh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4h outputs:a_colorh_4 = (1.5, 2.5, 3.5, 4.5) custom color4h[] outputs:a_colorh_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom double outputs:a_double = 1.5 custom double2 outputs:a_double_2 = (1.5, 2.5) custom double2[] outputs:a_double_2_array = [(1.5, 2.5), (11.5, 12.5)] custom double3 outputs:a_double_3 = (1.5, 2.5, 3.5) custom double3[] outputs:a_double_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom double4 outputs:a_double_4 = (1.5, 2.5, 3.5, 4.5) custom double4[] outputs:a_double_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom double[] outputs:a_double_array = [1.5, 2.5] custom uint outputs:a_execution = 2 ( customData = { bool isExecution = 1 } ) custom float outputs:a_float = 1.5 custom float2 outputs:a_float_2 = (1.5, 2.5) custom float2[] outputs:a_float_2_array = [(1.5, 2.5), (11.5, 12.5)] custom float3 outputs:a_float_3 = (1.5, 2.5, 3.5) custom float3[] outputs:a_float_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom float4 outputs:a_float_4 = (1.5, 2.5, 3.5, 4.5) custom float4[] outputs:a_float_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom float[] outputs:a_float_array = [1.5, 2.5] custom frame4d outputs:a_frame_4 = ( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ) custom frame4d[] outputs:a_frame_4_array = [( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ), ( (11.5, 12.5, 13.5, 14.5), (15.5, 16.5, 17.5, 18.5), (19.5, 20.5, 21.5, 22.5), (23.5, 24.5, 25.5, 26.5) )] custom half outputs:a_half = 1.5 custom half2 outputs:a_half_2 = (1.5, 2.5) custom half2[] outputs:a_half_2_array = [(1.5, 2.5), (11.5, 12.5)] custom half3 outputs:a_half_3 = (1.5, 2.5, 3.5) custom half3[] outputs:a_half_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom half4 outputs:a_half_4 = (1.5, 2.5, 3.5, 4.5) custom half4[] outputs:a_half_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom half[] outputs:a_half_array = [1.5, 2.5] custom int outputs:a_int = 1 custom int64 outputs:a_int64 = 12345 custom int64[] outputs:a_int64_array = [12345, 23456] custom int2 outputs:a_int_2 = (1, 2) custom int2[] outputs:a_int_2_array = [(1, 2), (3, 4)] custom int3 outputs:a_int_3 = (1, 2, 3) custom int3[] outputs:a_int_3_array = [(1, 2, 3), (4, 5, 6)] custom int4 outputs:a_int_4 = (1, 2, 3, 4) custom int4[] outputs:a_int_4_array = [(1, 2, 3, 4), (5, 6, 7, 8)] custom int[] outputs:a_int_array = [1, 2] custom matrix2d outputs:a_matrixd_2 = ( (1.5, 2.5), (3.5, 4.5) ) custom matrix2d[] outputs:a_matrixd_2_array = [( (1.5, 2.5), (3.5, 4.5) ), ( (11.5, 12.5), (13.5, 14.5) )] custom matrix3d outputs:a_matrixd_3 = ( (1.5, 2.5, 3.5), (4.5, 5.5, 6.5), (7.5, 8.5, 9.5) ) custom matrix3d[] outputs:a_matrixd_3_array = [( (1.5, 2.5, 3.5), (4.5, 5.5, 6.5), (7.5, 8.5, 9.5) ), ( (11.5, 12.5, 13.5), (14.5, 15.5, 16.5), (17.5, 18.5, 19.5) )] custom matrix4d outputs:a_matrixd_4 = ( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ) custom matrix4d[] outputs:a_matrixd_4_array = [( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ), ( (11.5, 12.5, 13.5, 14.5), (15.5, 16.5, 17.5, 18.5), (19.5, 20.5, 21.5, 22.5), (23.5, 24.5, 25.5, 26.5) )] custom normal3d outputs:a_normald_3 = (1.5, 2.5, 3.5) custom normal3d[] outputs:a_normald_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom normal3f outputs:a_normalf_3 = (1.5, 2.5, 3.5) custom normal3f[] outputs:a_normalf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom normal3h outputs:a_normalh_3 = (1.5, 2.5, 3.5) custom normal3h[] outputs:a_normalh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom uint64 outputs:a_objectId = 2 custom uint64[] outputs:a_objectId_array = [2, 3] custom string outputs:a_path = "/Output" custom point3d outputs:a_pointd_3 = (1.5, 2.5, 3.5) custom point3d[] outputs:a_pointd_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom point3f outputs:a_pointf_3 = (1.5, 2.5, 3.5) custom point3f[] outputs:a_pointf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom point3h outputs:a_pointh_3 = (1.5, 2.5, 3.5) custom point3h[] outputs:a_pointh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom quatd outputs:a_quatd_4 = (4.5, 1.5, 2.5, 3.5) custom quatd[] outputs:a_quatd_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom quatf outputs:a_quatf_4 = (4.5, 1.5, 2.5, 3.5) custom quatf[] outputs:a_quatf_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom quath outputs:a_quath_4 = (4.5, 1.5, 2.5, 3.5) custom quath[] outputs:a_quath_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom string outputs:a_string = "Snoke" custom texCoord2d outputs:a_texcoordd_2 = (1.5, 2.5) custom texCoord2d[] outputs:a_texcoordd_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3d outputs:a_texcoordd_3 = (1.5, 2.5, 3.5) custom texCoord3d[] outputs:a_texcoordd_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom texCoord2f outputs:a_texcoordf_2 = (1.5, 2.5) custom texCoord2f[] outputs:a_texcoordf_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3f outputs:a_texcoordf_3 = (1.5, 2.5, 3.5) custom texCoord3f[] outputs:a_texcoordf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom texCoord2h outputs:a_texcoordh_2 = (1.5, 2.5) custom texCoord2h[] outputs:a_texcoordh_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3h outputs:a_texcoordh_3 = (1.5, 2.5, 3.5) custom texCoord3h[] outputs:a_texcoordh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom timecode outputs:a_timecode = 2.5 custom timecode[] outputs:a_timecode_array = [2.5, 3.5] custom token outputs:a_token = "Jedi" custom token[] outputs:a_token_array = ["Luke", "Skywalker"] custom uchar outputs:a_uchar = 2 custom uchar[] outputs:a_uchar_array = [2, 3] custom uint outputs:a_uint = 2 custom uint64 outputs:a_uint64 = 2 custom uint64[] outputs:a_uint64_array = [2, 3] custom uint[] outputs:a_uint_array = [2, 3] custom vector3d outputs:a_vectord_3 = (1.5, 2.5, 3.5) custom vector3d[] outputs:a_vectord_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom vector3f outputs:a_vectorf_3 = (1.5, 2.5, 3.5) custom vector3f[] outputs:a_vectorf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom vector3h outputs:a_vectorh_3 = (1.5, 2.5, 3.5) custom vector3h[] outputs:a_vectorh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom bool state:a_bool = 1 custom bool[] state:a_bool_array = [1, 0] custom color3d state:a_colord_3 = (1.5, 2.5, 3.5) custom color3d[] state:a_colord_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4d state:a_colord_4 = (1.5, 2.5, 3.5, 4.5) custom color4d[] state:a_colord_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom color3f state:a_colorf_3 = (1.5, 2.5, 3.5) custom color3f[] state:a_colorf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4f state:a_colorf_4 = (1.5, 2.5, 3.5, 4.5) custom color4f[] state:a_colorf_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom color3h state:a_colorh_3 = (1.5, 2.5, 3.5) custom color3h[] state:a_colorh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4h state:a_colorh_4 = (1.5, 2.5, 3.5, 4.5) custom color4h[] state:a_colorh_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom double state:a_double = 1.5 custom double2 state:a_double_2 = (1.5, 2.5) custom double2[] state:a_double_2_array = [(1.5, 2.5), (11.5, 12.5)] custom double3 state:a_double_3 = (1.5, 2.5, 3.5) custom double3[] state:a_double_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom double4 state:a_double_4 = (1.5, 2.5, 3.5, 4.5) custom double4[] state:a_double_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom double[] state:a_double_array = [1.5, 2.5] custom uint state:a_execution = 2 custom bool state:a_firstEvaluation = 1 custom float state:a_float = 1.5 custom float2 state:a_float_2 = (1.5, 2.5) custom float2[] state:a_float_2_array = [(1.5, 2.5), (11.5, 12.5)] custom float3 state:a_float_3 = (1.5, 2.5, 3.5) custom float3[] state:a_float_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom float4 state:a_float_4 = (1.5, 2.5, 3.5, 4.5) custom float4[] state:a_float_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom float[] state:a_float_array = [1.5, 2.5] custom frame4d state:a_frame_4 = ( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ) custom frame4d[] state:a_frame_4_array = [( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ), ( (11.5, 12.5, 13.5, 14.5), (15.5, 16.5, 17.5, 18.5), (19.5, 20.5, 21.5, 22.5), (23.5, 24.5, 25.5, 26.5) )] custom half state:a_half = 1.5 custom half2 state:a_half_2 = (1.5, 2.5) custom half2[] state:a_half_2_array = [(1.5, 2.5), (11.5, 12.5)] custom half3 state:a_half_3 = (1.5, 2.5, 3.5) custom half3[] state:a_half_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom half4 state:a_half_4 = (1.5, 2.5, 3.5, 4.5) custom half4[] state:a_half_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom half[] state:a_half_array = [1.5, 2.5] custom int state:a_int = 1 custom int64 state:a_int64 = 12345 custom int64[] state:a_int64_array = [12345, 23456] custom int2 state:a_int_2 = (1, 2) custom int2[] state:a_int_2_array = [(1, 2), (3, 4)] custom int3 state:a_int_3 = (1, 2, 3) custom int3[] state:a_int_3_array = [(1, 2, 3), (4, 5, 6)] custom int4 state:a_int_4 = (1, 2, 3, 4) custom int4[] state:a_int_4_array = [(1, 2, 3, 4), (5, 6, 7, 8)] custom int[] state:a_int_array = [1, 2] custom matrix2d state:a_matrixd_2 = ( (1.5, 2.5), (3.5, 4.5) ) custom matrix2d[] state:a_matrixd_2_array = [( (1.5, 2.5), (3.5, 4.5) ), ( (11.5, 12.5), (13.5, 14.5) )] custom matrix3d state:a_matrixd_3 = ( (1.5, 2.5, 3.5), (4.5, 5.5, 6.5), (7.5, 8.5, 9.5) ) custom matrix3d[] state:a_matrixd_3_array = [( (1.5, 2.5, 3.5), (4.5, 5.5, 6.5), (7.5, 8.5, 9.5) ), ( (11.5, 12.5, 13.5), (14.5, 15.5, 16.5), (17.5, 18.5, 19.5) )] custom matrix4d state:a_matrixd_4 = ( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ) custom matrix4d[] state:a_matrixd_4_array = [( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ), ( (11.5, 12.5, 13.5, 14.5), (15.5, 16.5, 17.5, 18.5), (19.5, 20.5, 21.5, 22.5), (23.5, 24.5, 25.5, 26.5) )] custom normal3d state:a_normald_3 = (1.5, 2.5, 3.5) custom normal3d[] state:a_normald_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom normal3f state:a_normalf_3 = (1.5, 2.5, 3.5) custom normal3f[] state:a_normalf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom normal3h state:a_normalh_3 = (1.5, 2.5, 3.5) custom normal3h[] state:a_normalh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom uint64 state:a_objectId = 2 custom uint64[] state:a_objectId_array = [2, 3] custom string state:a_path = "/State" custom point3d state:a_pointd_3 = (1.5, 2.5, 3.5) custom point3d[] state:a_pointd_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom point3f state:a_pointf_3 = (1.5, 2.5, 3.5) custom point3f[] state:a_pointf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom point3h state:a_pointh_3 = (1.5, 2.5, 3.5) custom point3h[] state:a_pointh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom quatd state:a_quatd_4 = (4.5, 1.5, 2.5, 3.5) custom quatd[] state:a_quatd_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom quatf state:a_quatf_4 = (4.5, 1.5, 2.5, 3.5) custom quatf[] state:a_quatf_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom quath state:a_quath_4 = (4.5, 1.5, 2.5, 3.5) custom quath[] state:a_quath_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom string state:a_string = "Snoke" custom string state:a_stringEmpty custom texCoord2d state:a_texcoordd_2 = (1.5, 2.5) custom texCoord2d[] state:a_texcoordd_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3d state:a_texcoordd_3 = (1.5, 2.5, 3.5) custom texCoord3d[] state:a_texcoordd_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom texCoord2f state:a_texcoordf_2 = (1.5, 2.5) custom texCoord2f[] state:a_texcoordf_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3f state:a_texcoordf_3 = (1.5, 2.5, 3.5) custom texCoord3f[] state:a_texcoordf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom texCoord2h state:a_texcoordh_2 = (1.5, 2.5) custom texCoord2h[] state:a_texcoordh_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3h state:a_texcoordh_3 = (1.5, 2.5, 3.5) custom texCoord3h[] state:a_texcoordh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom timecode state:a_timecode = 2.5 custom timecode[] state:a_timecode_array = [2.5, 3.5] custom token state:a_token = "Jedi" custom token[] state:a_token_array = ["Luke", "Skywalker"] custom uchar state:a_uchar = 2 custom uchar[] state:a_uchar_array = [2, 3] custom uint state:a_uint = 2 custom uint64 state:a_uint64 = 2 custom uint64[] state:a_uint64_array = [2, 3] custom uint[] state:a_uint_array = [2, 3] custom vector3d state:a_vectord_3 = (1.5, 2.5, 3.5) custom vector3d[] state:a_vectord_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom vector3f state:a_vectorf_3 = (1.5, 2.5, 3.5) custom vector3f[] state:a_vectorf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom vector3h state:a_vectorh_3 = (1.5, 2.5, 3.5) custom vector3h[] state:a_vectorh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] def Output "outputs_a_bundle" { } def Output "state_a_bundle" { } } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestBundleGraphReparent.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50050) double radius = 500 } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (-0.000003978038364493841, 0.000007956076899517939, -0.000003978038478180679) } dictionary Right = { double3 position = (-50050, 0, -1.1113332476497817e-11) double radius = 500 } dictionary Top = { double3 position = (-4.3341100614586435e-12, 50050, 1.1113332476497817e-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: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.009999999776482582 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 Cube "Cube" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double size = 118 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"] } def ComputeGraph "graph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 5) } def ComputeNode "tutorial_node_bundle_data" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom rel inputs:bundle = </World/graph/extract_prim/outputs_primBundle> custom token node:type = "omni.graph.tutorials.BundleData" custom int node:typeVersion = 1 uniform float2 ui:nodegraph:node:pos = (-18.452303, -19.4172) def Output "outputs_bundle" { } } def ComputeNode "bundle_inspector" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom rel inputs:bundle = </World/graph/extract_prim/outputs_primBundle> custom bool inputs:print = 0 custom token node:type = "omni.graph.nodes.BundleInspector" custom int node:typeVersion = 2 custom int[] outputs:arrayDepths = [0, 0, 0, 0, 0, 0, 1, 1, 0] custom uint64 outputs:attributeCount = 9 custom uint64 outputs:childCount = 0 custom uint64 outputs:count = 9 custom token[] outputs:names = ["size", "sourcePrimPath", "sourcePrimType", "xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale", "xformOpOrder", "extent", "worldMatrix"] custom token[] outputs:roles = ["none", "none", "none", "none", "none", "none", "none", "none", "matrix"] custom int[] outputs:tupleCounts = [1, 1, 1, 3, 3, 3, 1, 3, 16] custom token[] outputs:types = ["double", "token", "token", "double", "double", "double", "token", "float", "double"] custom token[] outputs:values = ["118.000000", '"/World/Cube"', '"Cube"', "(0.000000, 0.000000, 0.000000)", "(0.000000, 0.000000, 0.000000)", "(1.000000, 1.000000, 1.000000)", '["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]', "[(-50.000000, -50.000000, -50.000000), (50.000000, 50.000000, 50.000000)]", "((1.000000, 0.000000, 0.000000, 0.000000), (0.000000, 1.000000, 0.000000, 0.000000), (0.000000, 0.000000, 1.000000, 0.000000), (0.000000, 0.000000, 0.000000, 1.000000))"] uniform float2 ui:nodegraph:node:pos = (-1.413879, 296.66) def Output "outputs_bundle" { } } def ComputeNode "read_prims_into_bundle" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom string inputs:attrNamesToImport = "*" custom token inputs:primPath custom rel inputs:prims prepend rel inputs:prims = </World/Cube> custom timecode inputs:usdTimecode = -1 custom bool inputs:usePath = 0 custom token node:type = "omni.graph.nodes.ReadPrimsBundle" custom int node:typeVersion = 1 custom string state:attrNamesToImport custom uint64[] state:primPath = [] custom timecode state:usdTimecode = -1 custom bool state:usePath = 0 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-714.7697, 156.08829) def Output "outputs_primsBundle" { } } def ComputeNode "extract_prim" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom string inputs:primPath = "/World/Cube" custom rel inputs:prims prepend rel inputs:prims = </World/graph/read_prims_into_bundle/outputs_primsBundle> custom token node:type = "omni.graph.nodes.ExtractPrim" custom int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-423.08286, 198.28983) def Output "outputs_primBundle" { } } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestGraphVariables.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (65.9072522418954, 65.90725224189542, 65.90725224189532) 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 = { } } dictionary renderSettings = { } } 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 ComputeGraph "ComputeGraph" { custom bool not_a_variable = 0 custom bool graph:variable:var_bool = 1 custom bool[] graph:variable:var_bool_array = [1, 0, 1] custom color3d graph:variable:var_color3d = (1, 2, 3) custom color3d[] graph:variable:var_color3d_array = [(1, 2, 3), (11, 12, 13)] custom color3f graph:variable:var_color3f = (1, 2, 3) custom color3f[] graph:variable:var_color3f_array = [(1, 2, 3), (11, 12, 13)] custom color3h graph:variable:var_color3h = (1, 2, 3) custom color3h[] graph:variable:var_color3h_array = [(1, 2, 3), (11, 12, 13)] custom color4d graph:variable:var_color4d = (1, 2, 3, 4) custom color4d[] graph:variable:var_color4d_array = [(1, 2, 3, 4), (11, 12, 13, 14)] custom color4f graph:variable:var_color4f = (1, 2, 3, 4) custom color4f[] graph:variable:var_color4f_array = [(1, 2, 3, 4), (11, 12, 13, 14)] custom color4h graph:variable:var_color4h = (1, 2, 3, 4) custom color4h[] graph:variable:var_color4h_array = [(1, 2, 3, 4), (11, 12, 13, 14)] custom double graph:variable:var_double = 1 custom double2 graph:variable:var_double2 = (1, 2) custom double2[] graph:variable:var_double2_array = [(1, 2), (11, 12)] custom double3 graph:variable:var_double3 = (1, 2, 3) custom double3[] graph:variable:var_double3_array = [(1, 2, 3), (11, 12, 13)] custom double4 graph:variable:var_double4 = (1, 2, 3, 4) custom double4[] graph:variable:var_double4_array = [(1, 2, 3, 4), (11, 12, 13, 14)] custom double[] graph:variable:var_double_array = [1, 2] custom float graph:variable:var_float = 1 custom float2 graph:variable:var_float2 = (1, 2) custom float2[] graph:variable:var_float2_array = [(1, 2), (11, 12)] custom float3 graph:variable:var_float3 = (1, 2, 3) custom float3[] graph:variable:var_float3_array = [(1, 2, 3), (11, 12, 13)] custom float4 graph:variable:var_float4 = (1, 2, 3, 4) custom float4[] graph:variable:var_float4_array = [(1, 2, 3, 4), (11, 12, 13, 14)] custom float[] graph:variable:var_float_array = [1, 2] custom frame4d graph:variable:var_frame4d = ( (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16) ) custom frame4d[] graph:variable:var_frame4d_array = [( (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16) ), ( (11, 12, 13, 14), (15, 16, 17, 18), (19, 20, 21, 22), (23, 24, 25, 26) )] custom half graph:variable:var_half = 1 custom half2 graph:variable:var_half2 = (1, 2) custom half2[] graph:variable:var_half2_array = [(1, 2), (11, 12)] custom half3 graph:variable:var_half3 = (1, 2, 3) custom half3[] graph:variable:var_half3_array = [(1, 2, 3), (11, 12, 13)] custom half4 graph:variable:var_half4 = (1, 2, 3, 4) custom half4[] graph:variable:var_half4_array = [(1, 2, 3, 4), (11, 12, 13, 14)] custom half[] graph:variable:var_half_array = [1, 2] custom int graph:variable:var_int = 1 custom int2 graph:variable:var_int2 = (1, 2) custom int2[] graph:variable:var_int2_array = [(1, 2), (3, 4)] custom int3 graph:variable:var_int3 = (1, 2, 3) custom int3[] graph:variable:var_int3_array = [(1, 2, 3), (4, 5, 6)] custom int4 graph:variable:var_int4 = (1, 2, 3, 4) custom int4[] graph:variable:var_int4_array = [(1, 2, 3, 4), (5, 6, 7, 8)] custom int64 graph:variable:var_int64 = 12345 custom int64[] graph:variable:var_int64_array = [12345, 23456] custom int[] graph:variable:var_int_array = [1, 2] custom matrix2d graph:variable:var_matrix2d = ( (1, 2), (3, 4) ) custom matrix2d[] graph:variable:var_matrix2d_array = [( (1, 2), (3, 4) ), ( (11, 12), (13, 14) )] custom matrix3d graph:variable:var_matrix3d = ( (1, 2, 3), (4, 5, 6), (7, 8, 9) ) custom matrix3d[] graph:variable:var_matrix3d_array = [( (1, 2, 3), (4, 5, 6), (7, 8, 9) ), ( (11, 12, 13), (14, 15, 16), (17, 18, 19) )] custom matrix4d graph:variable:var_matrix4d = ( (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16) ) custom matrix4d[] graph:variable:var_matrix4d_array = [( (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16) ), ( (11, 12, 13, 14), (15, 16, 17, 18), (19, 20, 21, 22), (23, 24, 25, 26) )] custom normal3d graph:variable:var_normal3d = (1, 2, 3) custom normal3d[] graph:variable:var_normal3d_array = [(1, 2, 3), (11, 12, 13)] custom normal3f graph:variable:var_normal3f = (1, 2, 3) custom normal3f[] graph:variable:var_normal3f_array = [(1, 2, 3), (11, 12, 13)] custom normal3h graph:variable:var_normal3h = (1, 2, 3) custom normal3h[] graph:variable:var_normal3h_array = [(1, 2, 3), (11, 12, 13)] custom point3d graph:variable:var_point3d = (1, 2, 3) custom point3d[] graph:variable:var_point3d_array = [(1, 2, 3), (11, 12, 13)] custom point3f graph:variable:var_point3f = (1, 2, 3) custom point3f[] graph:variable:var_point3f_array = [(1, 2, 3), (11, 12, 13)] custom point3h graph:variable:var_point3h = (1, 2, 3) custom point3h[] graph:variable:var_point3h_array = [(1, 2, 3), (11, 12, 13)] custom quatd graph:variable:var_quatd = (1, 2, 3, 4) custom quatd[] graph:variable:var_quatd_array = [(1, 2, 3, 4), (11, 12, 13, 14)] custom quatf graph:variable:var_quatf = (1, 2, 3, 4) custom quatf[] graph:variable:var_quatf_array = [(1, 2, 3, 4), (11, 12, 13, 14)] custom quath graph:variable:var_quath = (1, 2, 3, 4) custom quath[] graph:variable:var_quath_array = [(1, 2, 3, 4), (11, 12, 13, 14)] custom string graph:variable:var_string = "Rey" custom texCoord2d graph:variable:var_texcoord2d = (1, 2) custom texCoord2d[] graph:variable:var_texcoord2d_array = [(1, 2), (11, 12)] custom texCoord2f graph:variable:var_texcoord2f = (1, 2) custom texCoord2f[] graph:variable:var_texcoord2f_array = [(1, 2), (11, 12)] custom texCoord2h graph:variable:var_texcoord2h = (1, 2) custom texCoord2h[] graph:variable:var_texcoord2h_array = [(1, 2), (11, 12)] custom texCoord3d graph:variable:var_texcoord3d = (1, 2, 3) custom texCoord3d[] graph:variable:var_texcoord3d_array = [(1, 2, 3), (11, 12, 13)] custom texCoord3f graph:variable:var_texcoord3f = (1, 2, 3) custom texCoord3f[] graph:variable:var_texcoord3f_array = [(1, 2, 3), (11, 12, 13)] custom texCoord3h graph:variable:var_texcoord3h = (1, 2, 3) custom texCoord3h[] graph:variable:var_texcoord3h_array = [(1, 2, 3), (11, 12, 13)] custom timecode graph:variable:var_timecode = 1 custom timecode[] graph:variable:var_timecode_array = [1, 2] custom token graph:variable:var_token = "Sith" custom token[] graph:variable:var_token_array = ["Kylo", "Ren"] custom uchar graph:variable:var_uchar = 1 custom uchar[] graph:variable:var_uchar_array = [1, 2] custom uint graph:variable:var_uint = 1 custom uint64 graph:variable:var_uint64 = 1 custom uint64[] graph:variable:var_uint64_array = [1, 2] custom uint[] graph:variable:var_uint_array = [1, 2] custom vector3d graph:variable:var_vector3d = (1, 2, 3) custom vector3d[] graph:variable:var_vector3d_array = [(1, 2, 3), (11, 12, 13)] custom vector3f graph:variable:var_vector3f = (1, 2, 3) custom vector3f[] graph:variable:var_vector3f_array = [(1, 2, 3), (11, 12, 13)] custom vector3h graph:variable:var_vector3h = (1, 2, 3) custom vector3d[] graph:variable:var_vector3h_array = [(1, 2, 3), (11, 12, 13)] def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 2) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStageSimulation" } def ComputeNode "constant_bool" { custom bool inputs:value = 0 custom token node:type = "omni.graph.nodes.ConstantBool" custom int node:typeVersion = 1 } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestGatherByPath.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (0, 0, 0) } dictionary Right = { double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 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 "Cube_01" { 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" float velocity = -316.66666 double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 45.72225930094726) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Mesh "Cube_02" { 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" float velocity = -316.66666 double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (120, 0, 45.72225930094726) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Mesh "Cube_00" { 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" float velocity = -316.66666 double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (240, 0, 45.72225930094726) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def ComputeGraph "graph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" } def ComputeNode "omnigraph_test_GetPrimPathsByType" { custom uint inputs:execIn = 0 custom token inputs:type = "Mesh" custom token node:type = "omni.graph.nodes.GetPrimPathsByType" custom int node:typeVersion = 1 custom uint outputs:execOut = 1 custom bool inputs:recursive = 1 custom token[] outputs:primPaths = ["/World/Cube_01", "/World/Cube_02", "/World/Cube_00"] } def ComputeNode "gatherbypath" { custom token[] inputs:primPaths prepend token[] inputs:primPaths.connect = </World/graph/omnigraph_test_GetPrimPathsByType.outputs:primPaths> custom token node:type = "omni.graph.nodes.GatherByPath" custom int node:typeVersion = 1 custom uint64 outputs:gatherId custom bool state:active = 1 } def ComputeNode "omnigraph_examples_bounceNoBundleCpu" { custom uint64 inputs:gatherId prepend uint64 inputs:gatherId.connect = </World/graph/gatherbypath.outputs:gatherId> custom token node:type = "omni.graph.examples.cpp.BounceNoBundleCpu" custom int node:typeVersion = 1 } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestExecutionConnections.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (48.54250523009243, 91.60622961173839, 859.7976063483281) double3 target = (1.9753088054130785e-12, 1.0089706847793423e-12, 3.751665644813329e-12) } dictionary Right = { double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } int refinementOverrideImplVersion = 0 dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } metersPerUnit = 0.009999999776482582 timeCodesPerSecond = 24 upAxis = "Y" ) def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "execution_pull" } def ComputeNode "SubtractDouble" { custom double inputs:a prepend double inputs:a.connect = </AbsDouble_01.outputs:out> custom double inputs:b ( customData = { token AttributeConnectionType = "Execution" } ) prepend double inputs:b.connect = </AbsDouble.outputs:out> custom token node:type = "omni.graph.examples.python.SubtractDouble" custom int node:typeVersion = 1 custom double outputs:out = 100 } def ComputeNode "AbsDouble" { custom double inputs:num = 100 custom token node:type = "omni.graph.examples.python.AbsDouble" custom int node:typeVersion = 1 custom double outputs:out } def Cube "Cube" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double size = 100 double3 xformOp:rotateZYX = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0.2, 0) ( customData = { token AttributeConnectionType = "Execution" } ) prepend double3 xformOp:translate.connect = </ComposeDouble3_01.outputs:double3> uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] } def ComputeNode "AbsDouble_01" { custom double inputs:num = 200 custom token node:type = "omni.graph.examples.python.AbsDouble" custom int node:typeVersion = 1 custom double outputs:out } def ComputeNode "ComposeDouble3" { custom double inputs:x ( customData = { token AttributeConnectionType = "Execution" } ) prepend double inputs:x.connect = </SubtractDouble.outputs:out> custom double inputs:y custom double inputs:z custom token node:type = "omni.graph.examples.python.ComposeDouble3" custom int node:typeVersion = 1 custom double3 outputs:double3 = (100, 0, 0) } def ComputeNode "CountTo" { custom double inputs:countTo = 50 custom double inputs:increment = 5.0 custom bool inputs:reset = 0 custom double3 inputs:trigger ( customData = { token AttributeConnectionType = "Execution" } ) prepend double3 inputs:trigger.connect = </ComposeDouble3.outputs:double3> custom token node:type = "omni.graph.examples.python.CountTo" custom int node:typeVersion = 1 custom double outputs:count = 0 } def ComputeNode "ComposeDouble3_01" { custom double inputs:x custom double inputs:y ( customData = { token AttributeConnectionType = "Execution" } ) prepend double inputs:y.connect = </CountTo.outputs:count> custom double inputs:z custom token node:type = "omni.graph.examples.python.ComposeDouble3" custom int node:typeVersion = 1 custom double3 outputs:double3 = (0, 50, 0) } def Cone "Cone" { uniform token axis = "Y" float3[] extent = [(-50, -50, -50), (50, 50, 50)] double height = 100 double radius = 50 custom bool refinementEnableOverride = 1 custom int refinementLevel = 2 double3 xformOp:rotateZYX = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) ( customData = { token AttributeConnectionType = "Execution" } ) prepend double3 xformOp:translate.connect = </ComposeDouble3.outputs:double3> uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestLoadUsingCachedConnectionsSetting.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 = { } } dictionary renderSettings = { } } 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 Cube "Cube" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double size = 100 double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (100, 0, 0) prepend double3 xformOp:translate.connect = </World/test_node_compose_double3_c_.outputs:double3> uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 2) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStageSimulation" } def ComputeNode "test_node_compose_double3_c_" { custom double inputs:x = 100 custom double inputs:y = 0 custom double inputs:z = 0 custom token node:type = "omni.graph.test.ComposeDouble3C" custom int node:typeVersion = 1 custom double3 outputs:double3 } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestPreSchemaCompoundNode.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.00000397803842133726, 0.000007956076785831101, -0.000003978038307650422) } 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:post:backgroundZeroAlpha:backgroundDefaultColor" = (0, 0, 0) 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) } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 30 upAxis = "Y" ) def Xform "World" { def OmniGraph "PushGraph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 6) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "constant_int" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:value = 1 token node:type = "omni.graph.nodes.ConstantInt" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (63, 47) } def OmniGraphNode "constant_int_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:value = 2 token node:type = "omni.graph.nodes.ConstantInt" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (59, 143) } def OmniGraphNode "absolute_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:input delete token inputs:input.connect = </World/PushGraph/absolute.outputs:absolute> prepend token inputs:input.connect = </World/PushGraph/Compound.outputs:absolute> token node:type = "omni.graph.nodes.Absolute" int node:typeVersion = 1 custom token outputs:absolute uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (767, 86) } def OmniGraphNode "Compound" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:a prepend token inputs:a.connect = </World/PushGraph/constant_int.inputs:value> custom token inputs:b prepend token inputs:b.connect = </World/PushGraph/constant_int_01.inputs:value> token node:type = "local.nodes.Compound" token node:type.connect = </World/Compounds/Compound> int node:typeVersion = 0 custom rel omni:graph:compound prepend rel omni:graph:compound = </World/PushGraph/Compound/Graph> custom token outputs:absolute prepend token outputs:absolute.connect = </World/PushGraph/Compound/Graph/absolute.outputs:absolute> uniform float2 ui:nodegraph:node:pos = (419.5, 77) def "Graph" ( prepend references = </World/Compounds/Compound/Graph> ) { token evaluationMode = "Automatic" over "add" { custom token inputs:a prepend token inputs:a.connect = </World/PushGraph/Compound.inputs:a> custom token inputs:b prepend token inputs:b.connect = </World/PushGraph/Compound.inputs:b> } } } } def Scope "Compounds" { def OmniGraphCompoundNodeType "Compound" { prepend rel omni:graph:asset = </World/Compounds/Compound/Graph> custom rel omni:graph:input:a append rel omni:graph:input:a = </World/Compounds/Compound/Graph/add.inputs:a> custom rel omni:graph:input:b append rel omni:graph:input:b = </World/Compounds/Compound/Graph/add.inputs:b> token omni:graph:namespace = "local.nodes" custom rel omni:graph:output:absolute append rel omni:graph:output:absolute = </World/Compounds/Compound/Graph/absolute.outputs:absolute> def OmniGraph "Graph" { token evaluationMode = "Instanced" int2 fileFormatVersion = (1, 6) token pipelineStage = "pipelineStageOnDemand" def OmniGraphNode "absolute" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:input prepend token inputs:input.connect = </World/Compounds/Compound/Graph/add.outputs:sum> token node:type = "omni.graph.nodes.Absolute" int node:typeVersion = 1 custom token outputs:absolute uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (535, 84) } def OmniGraphNode "add" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:a custom token inputs:b token node:type = "omni.graph.nodes.Add" int node:typeVersion = 2 custom token outputs:sum uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (304, 70) } } } } } def Xform "Environment" { 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"] def DistantLight "defaultLight" ( prepend apiSchemas = ["ShapingAPI"] ) { float inputs:angle = 1 float inputs:intensity = 3000 float inputs:shaping:cone:angle = 180 float inputs:shaping:cone:softness float inputs:shaping:focus color3f inputs:shaping:focusTint asset inputs: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"] } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestReparentGraph.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 = { } } dictionary renderSettings = { } } 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 Xform "Xform" { 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"] } def ComputeGraph "ActionGraph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "execution" custom int2 fileFormatVersion = (1, 3) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStageSimulation" } def ComputeNode "on_tick" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:framePeriod = 0 custom bool inputs:onlyPlayback = 1 custom token node:type = "omni.graph.action.OnTick" custom int node:typeVersion = 1 custom double outputs:absoluteSimTime custom double outputs:deltaSeconds custom double outputs:frame custom bool outputs:isPlaying custom uint outputs:tick ( customData = { bool isExecution = 1 } ) custom double outputs:time custom double outputs:timeSinceStart uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (74, 162) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestDynamicAttributes.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 = { } } dictionary renderSettings = { } } metersPerUnit = 0.01 timeCodesPerSecond = 24 upAxis = "Y" ) def OmniGraph "graph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 5) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "NoDynamicAttributes" { custom uint inputs:value = 127 token node:type = "omni.graph.tutorials.DynamicAttributes" int node:typeVersion = 1 custom uint outputs:result } def OmniGraphNode "OnlyFirst" { custom uint inputs:firstBit = 3 custom uint inputs:value = 127 token node:type = "omni.graph.tutorials.DynamicAttributes" int node:typeVersion = 1 custom uint outputs:result } def OmniGraphNode "FirstAndSecond" { custom uint inputs:firstBit = 3 custom uint inputs:secondBit = 4 custom uint inputs:value = 127 token node:type = "omni.graph.tutorials.DynamicAttributes" int node:typeVersion = 1 custom uint outputs:result } def OmniGraphNode "SecondInvert" { custom timecode inputs:invert custom uint inputs:secondBit = 4 custom uint inputs:value = 127 token node:type = "omni.graph.tutorials.DynamicAttributes" int node:typeVersion = 1 custom uint outputs:result } def OmniGraphNode "NoDynamicAttributesPy" { custom uint inputs:value = 127 token node:type = "omni.graph.tutorials.DynamicAttributesPy" int node:typeVersion = 1 custom uint outputs:result } def OmniGraphNode "OnlyFirstPy" { custom uint inputs:firstBit = 3 custom uint inputs:value = 127 token node:type = "omni.graph.tutorials.DynamicAttributesPy" int node:typeVersion = 1 custom uint outputs:result } def OmniGraphNode "FirstAndSecondPy" { custom uint inputs:firstBit = 3 custom uint inputs:secondBit = 4 custom uint inputs:value = 127 token node:type = "omni.graph.tutorials.DynamicAttributesPy" int node:typeVersion = 1 custom uint outputs:result } def OmniGraphNode "SecondInvertPy" { custom timecode inputs:invert custom uint inputs:secondBit = 4 custom uint inputs:value = 127 token node:type = "omni.graph.tutorials.DynamicAttributesPy" int node:typeVersion = 1 custom uint outputs:result } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestBundleSubgraphReparent.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50050) double radius = 500 } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (0, 0, 0) } dictionary Right = { double3 position = (-50050, 0, -1.1113332476497817e-11) double radius = 500 } dictionary Top = { double3 position = (-4.3341100614586435e-12, 50050, 1.1113332476497817e-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) float3 "rtx:sceneDb:ambientLightColor" = (0.1, 0.1, 0.1) } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 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 Cube "Cube" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double size = 118 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"] } def ComputeGraph "subgraph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 3) } def ComputeNode "read_prim_bundle" { custom rel inputs:prim = </World/Cube> custom token inputs:primPath custom bool inputs:usePath = 0 custom token node:type = "omni.graph.nodes.ReadPrimBundle" custom int node:typeVersion = 1 def Output "outputs_primBundle" { } } def ComputeNode "tutorial_node_bundle_data" { custom rel inputs:bundle = </World/subgraph/read_prim_bundle/outputs_primBundle> custom token node:type = "omni.graph.tutorials.BundleData" custom int node:typeVersion = 1 def Output "outputs_bundle" { } } def ComputeNode "bundle_inspector" { custom rel inputs:bundle = </World/subgraph/read_prim_bundle/outputs_primBundle> custom bool inputs:print = 0 custom token node:type = "omni.graph.nodes.BundleInspector" custom int node:typeVersion = 1 custom int[] outputs:arrayDepths = [0, 0, 0, 0, 0, 1, 1] custom uint64 outputs:count = 7 custom token[] outputs:names = ["size", "sourcePrimPath", "xformOp:rotateXYZ", "xformOp:scale", "xformOp:translate", "xformOpOrder", "extent"] custom token[] outputs:roles = ["none", "none", "none", "none", "none", "none", "none"] custom int[] outputs:tupleCounts = [1, 1, 3, 3, 3, 1, 3] custom token[] outputs:types = ["double", "token", "double", "double", "double", "token", "float"] custom token[] outputs:values = ["118.000000", '"/World/Cube"', "(0.000000, 0.000000, 0.000000)", "(1.000000, 1.000000, 1.000000)", "(0.000000, 0.000000, 0.000000)", '["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]', "[(-50.000000, -50.000000, -50.000000), (50.000000, 50.000000, 50.000000)]"] def Output "outputs_bundle" { } } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestEventTrigger.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (48.54250523009243, 91.60622961173839, 859.7976063483281) double3 target = (1.9753088054130785e-12, 1.0089706847793423e-12, 3.751665644813329e-12) } dictionary Right = { double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } int refinementOverrideImplVersion = 0 dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } metersPerUnit = 0.009999999776482582 timeCodesPerSecond = 24 upAxis = "Y" ) def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "execution_pull" } def ComputeNode "SubtractDouble" { custom double inputs:a prepend double inputs:a.connect = </AbsDouble_01.outputs:out> custom double inputs:b ( customData = { token AttributeConnectionType = "Execution" } ) prepend double inputs:b.connect = </AbsDouble.outputs:out> custom token node:type = "omni.graph.examples.python.SubtractDouble" custom int node:typeVersion = 1 custom double outputs:out = 100 } def ComputeNode "AbsDouble" { custom double inputs:num = 100 custom uint64 inputs:event ( customData = { token AttributeConnectionType = "Execution" } ) prepend uint64 inputs:event.connect = </_builtin_EventUpdateTick.outputs:event> custom token node:type = "omni.graph.examples.python.AbsDouble" custom int node:typeVersion = 1 custom double outputs:out } def ComputeNode "AbsDouble_01" { custom double inputs:num = 200 custom token node:type = "omni.graph.examples.python.AbsDouble" custom int node:typeVersion = 1 custom double outputs:out } def ComputeNode "ComposeDouble3" { custom double inputs:x ( customData = { token AttributeConnectionType = "Execution" } ) prepend double inputs:x.connect = </SubtractDouble.outputs:out> custom double inputs:y custom double inputs:z custom token node:type = "omni.graph.examples.python.ComposeDouble3" custom int node:typeVersion = 1 custom double3 outputs:double3 = (100, 0, 0) } def Cone "Cone" { uniform token axis = "Y" float3[] extent = [(-50, -50, -50), (50, 50, 50)] double height = 100 double radius = 50 custom bool refinementEnableOverride = 1 custom int refinementLevel = 2 double3 xformOp:rotateZYX = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) ( customData = { token AttributeConnectionType = "Execution" } ) prepend double3 xformOp:translate.connect = </ComposeDouble3.outputs:double3> uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] } def ComputeNode "_builtin_EventUpdateTick" { custom token node:type = "omni.graph.nodes.UpdateTickEvent" custom int node:typeVersion = 1 custom uint64 outputs:event }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestExtendedAttributes.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.00000397803842133726, 0.000007956076785831101, -0.000003978038307650422) } 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 = { } } } 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 OmniGraph "PushGraph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "make_array" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:arraySize = 2 custom token inputs:arrayType = "bool[]" ( allowedTokens = ["auto", "bool[]", "double[]", "float[]", "half[]", "int[]", "int64[]", "token[]", "uchar[]", "uint[]", "uint64[]", "double[2][]", "double[3][]", "double[4][]", "matrixd[3][]", "matrixd[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]", "int[2][]", "int[3][]", "int[4][]"] ) custom token inputs:input0 = "True" ( customData = { dictionary omni = { dictionary graph = { bool attrValue = 1 } } } ) custom token inputs:input1 = "False" ( customData = { dictionary omni = { dictionary graph = { string attrType = "Any" bool attrValue = 0 } } } ) token node:type = "omni.graph.nodes.ConstructArray" int node:typeVersion = 1 custom token outputs:array uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-0.42132604, 19.033934) } def OmniGraphNode "make_array_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:arraySize = 2 custom token inputs:arrayType = "double[]" ( allowedTokens = ["auto", "bool[]", "double[]", "float[]", "half[]", "int[]", "int64[]", "token[]", "uchar[]", "uint[]", "uint64[]", "double[2][]", "double[3][]", "double[4][]", "matrixd[3][]", "matrixd[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]", "int[2][]", "int[3][]", "int[4][]"] ) custom token inputs:input0 = "42.0" ( customData = { dictionary omni = { dictionary graph = { double attrValue = 42 } } } ) custom token inputs:input1 = "43.0" ( customData = { string ExtendedAttributeType = "Any" dictionary omni = { dictionary graph = { string attrType = "Any" double attrValue = 43 } } } ) token node:type = "omni.graph.nodes.ConstructArray" int node:typeVersion = 1 custom token outputs:array uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (315.1866, 27.056555) } def OmniGraphNode "make_array_02" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:arraySize = 2 custom token inputs:arrayType = "token[]" ( allowedTokens = ["auto", "bool[]", "double[]", "float[]", "half[]", "int[]", "int64[]", "token[]", "uchar[]", "uint[]", "uint64[]", "double[2][]", "double[3][]", "double[4][]", "matrixd[3][]", "matrixd[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]", "int[2][]", "int[3][]", "int[4][]"] ) custom token inputs:input0 = "FOO" ( customData = { dictionary omni = { dictionary graph = { token attrValue = "FOO" } } } ) custom token inputs:input1 = "BAR" ( customData = { string ExtendedAttributeType = "Any" dictionary omni = { dictionary graph = { string attrType = "Any" token attrValue = "BAR" } } } ) token node:type = "omni.graph.nodes.ConstructArray" int node:typeVersion = 1 custom token outputs:array uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (315.1866, 27.056555) } def OmniGraphNode "make_array_03" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:arraySize = 2 custom token inputs:arrayType = "double[2][]" ( allowedTokens = ["auto", "bool[]", "double[]", "float[]", "half[]", "int[]", "int64[]", "token[]", "uchar[]", "uint[]", "uint64[]", "double[2][]", "double[3][]", "double[4][]", "matrixd[3][]", "matrixd[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]", "int[2][]", "int[3][]", "int[4][]"] ) custom token inputs:input0 = "(1, 2)" ( customData = { dictionary omni = { dictionary graph = { double2 attrValue = (1, 2) } } } ) custom token inputs:input1 = "(3, 4)" ( customData = { string ExtendedAttributeType = "Any" dictionary omni = { dictionary graph = { string attrType = "Any" double2 attrValue = (3, 4) } } } ) token node:type = "omni.graph.nodes.ConstructArray" int node:typeVersion = 1 custom token outputs:array uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (315.1866, 27.056555) } def OmniGraphNode "make_array_04" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:arraySize = 2 custom token inputs:arrayType = "int[2][]" ( allowedTokens = ["auto", "bool[]", "double[]", "float[]", "half[]", "int[]", "int64[]", "token[]", "uchar[]", "uint[]", "uint64[]", "double[2][]", "double[3][]", "double[4][]", "matrixd[3][]", "matrixd[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]", "int[2][]", "int[3][]", "int[4][]"] ) custom token inputs:input0 = "(1, 2)" ( customData = { dictionary omni = { dictionary graph = { int2 attrValue = (1, 2) } } } ) custom token inputs:input1 = "(3, 4)" ( customData = { string ExtendedAttributeType = "Any" dictionary omni = { dictionary graph = { string attrType = "Any" int2 attrValue = (3, 4) } } } ) token node:type = "omni.graph.nodes.ConstructArray" int node:typeVersion = 1 custom token outputs:array uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (315.1866, 27.056555) } def OmniGraphNode "make_array_05" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:arraySize = 2 custom token inputs:arrayType = "half[]" ( allowedTokens = ["auto", "bool[]", "double[]", "float[]", "half[]", "int[]", "int64[]", "token[]", "uchar[]", "uint[]", "uint64[]", "double[2][]", "double[3][]", "double[4][]", "matrixd[3][]", "matrixd[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]", "int[2][]", "int[3][]", "int[4][]"] ) custom token inputs:input0 = "42.0" ( customData = { dictionary omni = { dictionary graph = { half attrValue = 42 } } } ) custom token inputs:input1 = "43.0" ( customData = { string ExtendedAttributeType = "Any" dictionary omni = { dictionary graph = { string attrType = "Any" half attrValue = 43 } } } ) token node:type = "omni.graph.nodes.ConstructArray" int node:typeVersion = 1 custom token outputs:array uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (315.1866, 27.056555) } def OmniGraphNode "make_array_06" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:arraySize = 2 custom token inputs:arrayType = "matrixd[3][]" ( allowedTokens = ["auto", "bool[]", "double[]", "float[]", "half[]", "int[]", "int64[]", "token[]", "uchar[]", "uint[]", "uint64[]", "double[2][]", "double[3][]", "double[4][]", "matrixd[3][]", "matrixd[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]", "int[2][]", "int[3][]", "int[4][]"] ) custom token inputs:input0 = "42.0" ( customData = { string ExtendedAttributeType = "Any" dictionary omni = { dictionary graph = { string attrType = "Any" matrix3d attrValue = ( (1, 2, 3), (4, 5, 6), (7, 8, 9) ) } } } ) custom token inputs:input1 = "43.0" ( customData = { string ExtendedAttributeType = "Any" dictionary omni = { dictionary graph = { string attrType = "Any" matrix3d attrValue = ( (1, 2, 3), (4, 5, 6), (7, 8, 9) ) } } } ) token node:type = "omni.graph.nodes.ConstructArray" int node:typeVersion = 1 custom token outputs:array uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (315.1866, 27.056555) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestSubgraphDisable.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (0, 0, 0) } dictionary Right = { double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 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 Cube "Cube" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double size = 100 double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) prepend double3 xformOp:translate.connect = </World/innerPushGraph/omnigraph_examples_composeDouble3C.outputs:double3> uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def ComputeGraph "innerPushGraph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" bool disable = true } def ComputeNode "omnigraph_examples_decomposeDouble3C" { custom double3 inputs:double3 = (0, 0, 0) prepend double3 inputs:double3.connect = </World/Cube.xformOp:translate> custom token node:type = "omni.graph.test.DecomposeDouble3C" custom int node:typeVersion = 1 custom double outputs:x = 0 custom double outputs:y = 0 custom double outputs:z = 0 } def ComputeNode "omnigraph_examples_subtractDoubleC" { custom double inputs:a = 0 prepend double inputs:a.connect = </World/innerPushGraph/omnigraph_examples_decomposeDouble3C.outputs:x> custom double inputs:b = 1 custom token node:type = "omni.graph.test.SubtractDoubleC" custom int node:typeVersion = 1 custom double outputs:out = 0 } def ComputeNode "omnigraph_examples_composeDouble3C" { custom double inputs:x = 0 prepend double inputs:x.connect = </World/innerPushGraph/omnigraph_examples_subtractDoubleC.outputs:out> custom double inputs:y = 0 prepend double inputs:y.connect = </World/innerPushGraph/omnigraph_examples_decomposeDouble3C.outputs:y> custom double inputs:z = 0 prepend double inputs:z.connect = </World/innerPushGraph/omnigraph_examples_decomposeDouble3C.outputs:z> custom token node:type = "omni.graph.test.ComposeDouble3C" custom int node:typeVersion = 1 custom double3 outputs:double3 = (0, 0, 0) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestNodeWithUnknownType.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (0, 0, 0) } dictionary Right = { double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } int refinementOverrideImplVersion = 0 dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 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 float3 xformOp:rotateXYZ = (315, 0, 0) double3 xformOp:scale = (1, 1, 1) float3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def OmniGraph "Graph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 5) def OmniGraphNode "SomeUnknownNode" { token node:type = "unknown_type" int node:typeVersion = 1 custom token outputs:out = "union type of numeric" def ComputeNodeMetaData "metaData" { custom token outputs:out = "ExtendedAttributeType-->Union-->numeric" } } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestUSDTimeCode.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (0, 0, 0) } dictionary Right = { double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def Cube "Cube" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double size.timeSamples = { 0:100, 25:50, 50:1, 75:50, 99:100 } 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.graph.test/omni/graph/test/tests/data/TestResolvedString.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (843.4123832885864, 269.4967499032287, 333.09752132580235) double3 target = (190.50767649434965, 85.85421331977298, -90.52846443934146) } 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) bool "rtx:flow:enabled" = 1 bool "rtx:flow:pathTracingEnabled" = 1 bool "rtx:flow:rayTracedReflectionsEnabled" = 1 bool "rtx:flow:rayTracedTranslucencyEnabled" = 1 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) bool "rtx:useViewLightingMode" = 1 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def Scope "dataStructure" { def Xform "category" { custom string currentOption = "snickerdoodle" } } def OmniGraph "Graph" { token evaluationMode = "Automatic" token evaluator:type = "execution" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 5) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "write_prim" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execIn custom token inputs:name = "currentOption" custom rel inputs:prim prepend rel inputs:prim = </World/dataStructure/category> custom token inputs:primPath custom bool inputs:usdWriteBack = 1 custom bool inputs:usePath = 0 custom token inputs:value = "chocolateChip" ( customData = { dictionary omni = { dictionary graph = { uchar[] attrValue = [99, 104, 111, 99, 111, 108, 97, 116, 101, 67, 104, 105, 112] string resolvedType = "string" } } } ) token node:type = "omni.graph.nodes.WritePrimAttribute" int node:typeVersion = 1 custom uint outputs:execOut ( customData = { bool isExecution = 1 } ) uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (1218.1555, 1283.5999) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestFloorOutput.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.00000397803842133726, 0.000007956076785831101, -0.000003978038307650422) } 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 renderSettings = { } } 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 OmniGraph "TestGraph" { token evaluator:type = "execution" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 3) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "constant_double" { custom double inputs:value = 10.3 token node:type = "omni.graph.nodes.ConstantDouble" int node:typeVersion = 1 } def OmniGraphNode "constant_float" { custom float inputs:value = 10.3 token node:type = "omni.graph.nodes.ConstantFloat" int node:typeVersion = 1 } def OmniGraphNode "constant_half" { custom half inputs:value = 10.2969 token node:type = "omni.graph.nodes.ConstantHalf" int node:typeVersion = 1 } def OmniGraphNode "floor_double" { custom token inputs:a prepend token inputs:a.connect = </World/TestGraph/constant_double.inputs:value> token node:type = "omni.graph.nodes.Floor" int node:typeVersion = 1 custom int outputs:result } def OmniGraphNode "floor_float" { custom token inputs:a prepend token inputs:a.connect = </World/TestGraph/constant_float.inputs:value> token node:type = "omni.graph.nodes.Floor" int node:typeVersion = 1 custom int outputs:result } def OmniGraphNode "floor_half" { custom token inputs:a prepend token inputs:a.connect = </World/TestGraph/constant_half.inputs:value> token node:type = "omni.graph.nodes.Floor" int node:typeVersion = 1 custom int outputs:result } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestRewireExecInput.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 = { } } dictionary renderSettings = { } } 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 ComputeGraph "ActionGraph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "execution" custom int2 fileFormatVersion = (1, 3) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStageSimulation" } def ComputeNode "execinputenabledtest" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execInA = 0 prepend uint inputs:execInA.connect = </World/ActionGraph/on_impulse_event_A1.outputs:execOut> custom uint inputs:execInB = 0 prepend uint inputs:execInB.connect = </World/ActionGraph/on_impulse_event_B.outputs:execOut> custom token node:type = "omni.graph.test.ExecInputEnabledTest" custom int node:typeVersion = 1 custom uint outputs:execOutA ( customData = { bool isExecution = 1 } ) custom uint outputs:execOutB ( customData = { bool isExecution = 1 } ) uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (265, 127) } def ComputeNode "on_impulse_event_A1" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:onlyPlayback = 0 custom token node:type = "omni.graph.action.OnImpulseEvent" custom int node:typeVersion = 2 custom uint outputs:execOut = 0 ( customData = { bool isExecution = 1 } ) custom bool state:enableImpulse = 0 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-1, 43) } def ComputeNode "on_impulse_event_A2" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:onlyPlayback = 0 custom token node:type = "omni.graph.action.OnImpulseEvent" custom int node:typeVersion = 2 custom uint outputs:execOut = 0 ( customData = { bool isExecution = 1 } ) custom bool state:enableImpulse = 0 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (0, 154) } def ComputeNode "on_impulse_event_B" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:onlyPlayback = 0 custom token node:type = "omni.graph.action.OnImpulseEvent" custom int node:typeVersion = 2 custom uint outputs:execOut = 0 ( customData = { bool isExecution = 1 } ) custom bool state:enableImpulse = 0 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-2, 270) } def ComputeNode "counter_A" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execIn = 0 prepend uint inputs:execIn.connect = </World/ActionGraph/execinputenabledtest.outputs:execOutA> custom uint inputs:reset custom token node:type = "omni.graph.action.Counter" custom int node:typeVersion = 1 custom int outputs:count custom uint outputs:execOut ( customData = { bool isExecution = 1 } ) custom int state:count uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (525, 73) } def ComputeNode "counter_B" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execIn = 0 prepend uint inputs:execIn.connect = </World/ActionGraph/execinputenabledtest.outputs:execOutB> custom uint inputs:reset custom token node:type = "omni.graph.action.Counter" custom int node:typeVersion = 1 custom int outputs:count custom uint outputs:execOut ( customData = { bool isExecution = 1 } ) custom int state:count uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (528, 238) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestNodeLibrary.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.0000039780381939635845, 0.000007956076956361358, -0.000003978038478180679) } 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 = { } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def Scope "Compounds" { def OmniGraphCompoundNodeType "Madd" { prepend rel omni:graph:asset = </World/Compounds/Madd/Graph> custom rel omni:graph:input:a = </World/Compounds/Madd/Graph/multiply.inputs:a> custom rel omni:graph:input:b = </World/Compounds/Madd/Graph/multiply.inputs:b> custom rel omni:graph:input:c = </World/Compounds/Madd/Graph/add.inputs:b> custom rel omni:graph:output:sum = </World/Compounds/Madd/Graph/add.outputs:sum> def OmniGraph "Graph" { token evaluationMode = "Instanced" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "add" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:a prepend token inputs:a.connect = </World/Compounds/Madd/Graph/multiply.outputs:product> custom token inputs:b 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 = (620, 125) } def OmniGraphNode "multiply" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:a custom token inputs:b token node:type = "omni.graph.nodes.Multiply" int node:typeVersion = 1 custom token outputs:product uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (377, 40) } } } def OmniGraphCompoundNodeType "DebugString" { prepend rel omni:graph:asset = </World/Compounds/DebugString/Graph> custom rel omni:graph:input:value = </World/Compounds/DebugString/Graph/to_string.inputs:value> def OmniGraph "Graph" { token evaluationMode = "Instanced" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "to_string" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:value token node:type = "omni.graph.nodes.ToString" int node:typeVersion = 1 custom string outputs:converted uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (520, 90) } def OmniGraphNode "append_string" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:suffix prepend token inputs:suffix.connect = </World/Compounds/DebugString/Graph/to_string.outputs:converted> custom token inputs:value prepend token inputs:value.connect = </World/Compounds/DebugString/Graph/constant_string.inputs:value> token node:type = "omni.graph.nodes.AppendString" int node:typeVersion = 1 custom token outputs:value uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (812, 128) } def OmniGraphNode "constant_string" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom string inputs:value = "[DEBUG] " token node:type = "omni.graph.nodes.ConstantString" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (519, 232) } def OmniGraphNode "to_string_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:value prepend token inputs:value.connect = </World/Compounds/DebugString/Graph/append_string.outputs:value> token node:type = "omni.graph.nodes.ToString" int node:typeVersion = 1 custom string outputs:converted uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (1080.8212, 132.8374) } } } def OmniGraphCompoundNodeType "Deg2Rad" { prepend rel omni:graph:asset = </World/Compounds/Deg2Rad/Graph> custom rel omni:graph:input:a = </World/Compounds/Deg2Rad/Graph/multiply.inputs:a> custom rel omni:graph:output:result = </World/Compounds/Deg2Rad/Graph/divide.outputs:result> def OmniGraph "Graph" { token evaluationMode = "Instanced" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "constant_pi" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:factor = 2 token node:type = "omni.graph.nodes.ConstantPi" int node:typeVersion = 1 custom double outputs:value uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (318, 181) } def OmniGraphNode "multiply" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:a custom token inputs:b prepend token inputs:b.connect = </World/Compounds/Deg2Rad/Graph/constant_pi.outputs:value> token node:type = "omni.graph.nodes.Multiply" int node:typeVersion = 1 custom token outputs:product uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (619, 47) } def OmniGraphNode "constant_double_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:value = 360 token node:type = "omni.graph.nodes.ConstantDouble" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (620, 187) } def OmniGraphNode "divide" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:a prepend token inputs:a.connect = </World/Compounds/Deg2Rad/Graph/multiply.outputs:product> custom token inputs:b prepend token inputs:b.connect = </World/Compounds/Deg2Rad/Graph/constant_double_01.inputs:value> token node:type = "omni.graph.nodes.Divide" int node:typeVersion = 1 custom token outputs:result uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (871, 50) } } } def OmniGraphCompoundNodeType "CelciusToFahrenheit" { prepend rel omni:graph:asset = </World/Compounds/CelciusToFahrenheit/Graph> custom rel omni:graph:input:a = </World/Compounds/CelciusToFahrenheit/Graph/madd.inputs:a> custom rel omni:graph:output:value = </World/Compounds/CelciusToFahrenheit/Graph/madd.outputs:sum> def OmniGraph "Graph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "madd" ( prepend apiSchemas = ["NodeGraphNodeAPI", "OmniGraphCompoundNodeAPI"] ) { custom token inputs:a custom token inputs:b prepend token inputs:b.connect = </World/Compounds/CelciusToFahrenheit/Graph/constant_double_02.inputs:value> custom token inputs:c prepend token inputs:c.connect = </World/Compounds/CelciusToFahrenheit/Graph/constant_double_01.inputs:value> token node:type = "local.nodes.Madd" token node:type.connect = </World/Compounds/Madd> int node:typeVersion = 1 rel omni:graph:compoundGraph = </World/Compounds/CelciusToFahrenheit/Graph/madd/Graph> token omni:graph:compoundType = "nodetype" custom token outputs:sum prepend token outputs:sum.connect = </World/Compounds/CelciusToFahrenheit/Graph/madd/Graph/add.outputs:sum> uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (436, 81) def "Graph" ( prepend references = </World/Compounds/Madd/Graph> ) { token evaluationMode = "Automatic" over "multiply" { custom token inputs:a prepend token inputs:a.connect = </World/Compounds/CelciusToFahrenheit/Graph/madd.inputs:a> custom token inputs:b prepend token inputs:b.connect = </World/Compounds/CelciusToFahrenheit/Graph/madd.inputs:b> } over "add" { custom token inputs:b prepend token inputs:b.connect = </World/Compounds/CelciusToFahrenheit/Graph/madd.inputs:c> } } } def OmniGraphNode "constant_double_02" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:value = 1.8 token node:type = "omni.graph.nodes.ConstantDouble" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (51, 149) } def OmniGraphNode "constant_double_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:value = 32 token node:type = "omni.graph.nodes.ConstantDouble" int node:typeVersion = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (48, 251) } } } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestObjectIdentification.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (65.9072522418954, 65.90725224189542, 65.90725224189532) double3 target = (-5.243631449047825e-7, 0.000001048726346652984, -5.243632159590561e-7) } 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 = { string authoring_layer = "./TestObjectIdentification.usda" dictionary muteness = { } } dictionary renderSettings = { float3 "rtx:debugView:pixelDebug:textColor" = (0, 1e18, 0) float3 "rtx:fog:fogColor" = (0.75, 0.75, 0.75) float3 "rtx:index:regionOfInterestMax" = (0, 0, 0) float3 "rtx:index:regionOfInterestMin" = (0, 0, 0) float3 "rtx:post:backgroundZeroAlpha:backgroundDefaultColor" = (0, 0, 0) 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 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 OmniGraph "OuterGraph1" { int2 fileFormatVersion = (1, 7) custom bool graph:variable:variable_bool = 1 custom double graph:variable:variable_double = 1 custom float graph:variable:variable_float = 1 def OmniGraph "InnerGraph1" { int2 fileFormatVersion = (1, 7) def OmniGraphNode "constant_float" { custom float inputs:value = 0 token node:type = "omni.graph.nodes.ConstantFloat" int node:typeVersion = 1 } } def OmniGraph "InnerGraph2" { int2 fileFormatVersion = (1, 7) def OmniGraphNode "constant_int" { custom int inputs:value = 0 token node:type = "omni.graph.nodes.ConstantInt" int node:typeVersion = 1 } } def OmniGraphNode "constant_bool" { custom bool inputs:value = 0 token node:type = "omni.graph.nodes.ConstantBool" int node:typeVersion = 1 } def OmniGraphNode "constant_prims" { custom rel inputs:value ( customData = { dictionary omni = { dictionary graph = { string relType = "target" } } } ) token node:type = "omni.graph.nodes.ConstantPrims" int node:typeVersion = 2 } def OmniGraphNode "extract_bundle" { custom rel inputs:bundle token node:type = "omni.graph.nodes.ExtractBundle" int node:typeVersion = 3 def Output "outputs_passThrough" { } } def OmniGraphNode "get_prims_at_path" { custom token inputs:path token node:type = "omni.graph.nodes.GetPrimsAtPath" int node:typeVersion = 1 custom rel outputs:prims ( customData = { dictionary omni = { dictionary graph = { string relType = "target" } } } ) custom token state:path } } def OmniGraph "OuterGraph2" { int2 fileFormatVersion = (1, 7) def OmniGraphNode "constant_double" { custom double inputs:value = 0 token node:type = "omni.graph.nodes.ConstantDouble" int node:typeVersion = 1 } def OmniGraph "InnerGraph1" { int2 fileFormatVersion = (1, 7) def OmniGraphNode "constant_uint" { custom uint inputs:value = 0 token node:type = "omni.graph.nodes.ConstantUInt" int node:typeVersion = 1 } } def OmniGraph "InnerGraph2" { int2 fileFormatVersion = (1, 7) def OmniGraphNode "constant_uint64" { custom uint64 inputs:value = 0 token node:type = "omni.graph.nodes.ConstantUInt64" int node:typeVersion = 1 } } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestCompoundDefaultValues.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.00000397803842133726, 0.000007956076785831101, -0.00000397803842133726) } 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:fog:fogColor" = (0.75, 0.75, 0.75) 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 "Compound" { prepend rel omni:graph:asset = </World/Compounds/Compound/Graph> custom rel omni:graph:input:a_bool ( customData = { dictionary omni = { dictionary graph = { string type = "bool" bool default = 0 } } } ) custom rel omni:graph:input:a_bool_array ( customData = { dictionary omni = { dictionary graph = { string type = "bool[]" bool[] default = [0, 1] } } } ) custom rel omni:graph:input:a_colord_3 ( customData = { dictionary omni = { dictionary graph = { string type = "colord[3]" color3d default = (0.01625, 0.14125, 0.26625) } } } ) custom rel omni:graph:input:a_colord_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "colord[3][]" color3d[] default = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] } } } ) custom rel omni:graph:input:a_colord_4 ( customData = { dictionary omni = { dictionary graph = { string type = "colord[4]" color4d default = (0.01625, 0.14125, 0.26625, 0.39125) } } } ) custom rel omni:graph:input:a_colord_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "colord[4][]" color4d[] default = [(0.01625, 0.14125, 0.26625, 0.39125), (0.39125, 0.26625, 0.14125, 0.01625)] } } } ) custom rel omni:graph:input:a_colorf_3 ( customData = { dictionary omni = { dictionary graph = { string type = "colorf[3]" color3f default = (0.125, 0.25, 0.375) } } } ) custom rel omni:graph:input:a_colorf_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "colorf[3][]" color3f[] default = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] } } } ) custom rel omni:graph:input:a_colorf_4 ( customData = { dictionary omni = { dictionary graph = { string type = "colorf[4]" color4f default = (0.125, 0.25, 0.375, 0.5) } } } ) custom rel omni:graph:input:a_colorf_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "colorf[4][]" color4f[] default = [(0.125, 0.25, 0.375, 0.5), (0.5, 0.375, 0.25, 0.125)] } } } ) custom rel omni:graph:input:a_colorh_3 ( customData = { dictionary omni = { dictionary graph = { string type = "colorh[3]" color3h default = (0.5, 0.625, 0.75) } } } ) custom rel omni:graph:input:a_colorh_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "colorh[3][]" color3h[] default = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] } } } ) custom rel omni:graph:input:a_colorh_4 ( customData = { dictionary omni = { dictionary graph = { string type = "colorh[4]" color4h default = (0.5, 0.625, 0.75, 0.875) } } } ) custom rel omni:graph:input:a_colorh_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "colorh[4][]" color4h[] default = [(0.5, 0.625, 0.75, 0.875), (0.875, 0.75, 0.625, 0.5)] } } } ) custom rel omni:graph:input:a_double ( customData = { dictionary omni = { dictionary graph = { string type = "double" double default = 4.125 } } } ) custom rel omni:graph:input:a_double_2 ( customData = { dictionary omni = { dictionary graph = { string type = "double[2]" double2 default = (4.125, 4.25) } } } ) custom rel omni:graph:input:a_double_2_array ( customData = { dictionary omni = { dictionary graph = { string type = "double[2][]" double2[] default = [(4.125, 4.25), (2.125, 2.25)] } } } ) custom rel omni:graph:input:a_double_3 ( customData = { dictionary omni = { dictionary graph = { string type = "double[3]" double3 default = (4.125, 4.25, 4.375) } } } ) custom rel omni:graph:input:a_double_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "double[3][]" double3[] default = [(4.125, 4.25, 4.375), (2.125, 2.25, 2.375)] } } } ) custom rel omni:graph:input:a_double_4 ( customData = { dictionary omni = { dictionary graph = { string type = "double[4]" double4 default = (4.125, 4.25, 4.375, 4.5) } } } ) custom rel omni:graph:input:a_double_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "double[4][]" double4[] default = [(4.125, 4.25, 4.375, 4.5), (2.125, 2.25, 2.375, 2.5)] } } } ) custom rel omni:graph:input:a_double_array ( customData = { dictionary omni = { dictionary graph = { string type = "double[]" double[] default = [4.125, 2.125] } } } ) custom rel omni:graph:input:a_execution ( customData = { dictionary omni = { dictionary graph = { string type = "execution" uint default = 0 } } } ) custom rel omni:graph:input:a_float ( customData = { dictionary omni = { dictionary graph = { string type = "float" float default = 4.5 } } } ) custom rel omni:graph:input:a_float_2 ( customData = { dictionary omni = { dictionary graph = { string type = "float[2]" float2 default = (4.5, 4.625) } } } ) custom rel omni:graph:input:a_float_2_array ( customData = { dictionary omni = { dictionary graph = { string type = "float[2][]" float2[] default = [(4.5, 4.625), (2.5, 2.625)] } } } ) custom rel omni:graph:input:a_float_3 ( customData = { dictionary omni = { dictionary graph = { string type = "float[3]" float3 default = (4.5, 4.625, 4.75) } } } ) custom rel omni:graph:input:a_float_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "float[3][]" float3[] default = [(4.5, 4.625, 4.75), (2.5, 2.625, 2.75)] } } } ) custom rel omni:graph:input:a_float_4 ( customData = { dictionary omni = { dictionary graph = { string type = "float[4]" float4 default = (4.5, 4.625, 4.75, 4.875) } } } ) custom rel omni:graph:input:a_float_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "float[4][]" float4[] default = [(4.5, 4.625, 4.75, 4.875), (2.5, 2.625, 2.75, 2.875)] } } } ) custom rel omni:graph:input:a_float_array ( customData = { dictionary omni = { dictionary graph = { string type = "float[]" float[] default = [4.5, 2.5] } } } ) custom rel omni:graph:input:a_frame_4 ( customData = { dictionary omni = { dictionary graph = { string type = "framed[4]" frame4d default = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ) } } } ) custom rel omni:graph:input:a_frame_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "framed[4][]" frame4d[] default = [( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ), ( (2, 3, 3, 3), (3, 2, 3, 3), (3, 3, 2, 3), (3, 3, 3, 2) )] } } } ) custom rel omni:graph:input:a_half ( customData = { dictionary omni = { dictionary graph = { string type = "half" half default = 2.5 } } } ) custom rel omni:graph:input:a_half_2 ( customData = { dictionary omni = { dictionary graph = { string type = "half[2]" half2 default = (2.5, 2.625) } } } ) custom rel omni:graph:input:a_half_2_array ( customData = { dictionary omni = { dictionary graph = { string type = "half[2][]" half2[] default = [(2.5, 2.625), (4.5, 4.625)] } } } ) custom rel omni:graph:input:a_half_3 ( customData = { dictionary omni = { dictionary graph = { string type = "half[3]" half3 default = (2.5, 2.625, 2.75) } } } ) custom rel omni:graph:input:a_half_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "half[3][]" half3[] default = [(2.5, 2.625, 2.75), (4.5, 4.625, 4.75)] } } } ) custom rel omni:graph:input:a_half_4 ( customData = { dictionary omni = { dictionary graph = { string type = "half[4]" half4 default = (2.5, 2.625, 2.75, 2.875) } } } ) custom rel omni:graph:input:a_half_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "half[4][]" half4[] default = [(2.5, 2.625, 2.75, 2.875), (4.5, 4.625, 4.75, 4.875)] } } } ) custom rel omni:graph:input:a_half_array ( customData = { dictionary omni = { dictionary graph = { string type = "half[]" half[] default = [2.5, 4.5] } } } ) custom rel omni:graph:input:a_int ( customData = { dictionary omni = { dictionary graph = { string type = "int" int default = -32 } } } ) custom rel omni:graph:input:a_int64 ( customData = { dictionary omni = { dictionary graph = { string type = "int64" int64 default = -46 } } } ) custom rel omni:graph:input:a_int64_array ( customData = { dictionary omni = { dictionary graph = { string type = "int64[]" int64[] default = [-46, -64] } } } ) custom rel omni:graph:input:a_int_2 ( customData = { dictionary omni = { dictionary graph = { string type = "int[2]" int2 default = (-32, -31) } } } ) custom rel omni:graph:input:a_int_2_array ( customData = { dictionary omni = { dictionary graph = { string type = "int[2][]" int2[] default = [(-32, -31), (-23, -22)] } } } ) custom rel omni:graph:input:a_int_3 ( customData = { dictionary omni = { dictionary graph = { string type = "int[3]" int3 default = (-32, -31, -30) } } } ) custom rel omni:graph:input:a_int_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "int[3][]" int3[] default = [(-32, -31, -30), (-23, -22, -21)] } } } ) custom rel omni:graph:input:a_int_4 ( customData = { dictionary omni = { dictionary graph = { string type = "int[4]" int4 default = (-32, -31, -30, -29) } } } ) custom rel omni:graph:input:a_int_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "int[4][]" int4[] default = [(-32, -31, -30, -29), (-23, -22, -21, -20)] } } } ) custom rel omni:graph:input:a_int_array ( customData = { dictionary omni = { dictionary graph = { string type = "int[]" int[] default = [-32, -23] } } } ) custom rel omni:graph:input:a_matrixd_2 ( customData = { dictionary omni = { dictionary graph = { string type = "matrixd[2]" matrix2d default = ( (1, 0), (0, 1) ) } } } ) custom rel omni:graph:input:a_matrixd_2_array ( customData = { dictionary omni = { dictionary graph = { string type = "matrixd[2][]" matrix2d[] default = [( (1, 0), (0, 1) ), ( (2, 3), (3, 2) )] } } } ) custom rel omni:graph:input:a_matrixd_3 ( customData = { dictionary omni = { dictionary graph = { string type = "matrixd[3]" matrix3d default = ( (1, 0, 0), (0, 1, 0), (0, 0, 1) ) } } } ) custom rel omni:graph:input:a_matrixd_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "matrixd[3][]" matrix3d[] default = [( (1, 0, 0), (0, 1, 0), (0, 0, 1) ), ( (2, 3, 3), (3, 2, 3), (3, 3, 2) )] } } } ) custom rel omni:graph:input:a_matrixd_4 ( customData = { dictionary omni = { dictionary graph = { string type = "matrixd[4]" matrix4d default = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ) } } } ) custom rel omni:graph:input:a_matrixd_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "matrixd[4][]" matrix4d[] default = [( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ), ( (2, 3, 3, 3), (3, 2, 3, 3), (3, 3, 2, 3), (3, 3, 3, 2) )] } } } ) custom rel omni:graph:input:a_normald_3 ( customData = { dictionary omni = { dictionary graph = { string type = "normald[3]" normal3d default = (0.01625, 0.14125, 0.26625) } } } ) custom rel omni:graph:input:a_normald_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "normald[3][]" normal3d[] default = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] } } } ) custom rel omni:graph:input:a_normalf_3 ( customData = { dictionary omni = { dictionary graph = { string type = "normalf[3]" normal3f default = (0.125, 0.25, 0.375) } } } ) custom rel omni:graph:input:a_normalf_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "normalf[3][]" normal3f[] default = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] } } } ) custom rel omni:graph:input:a_normalh_3 ( customData = { dictionary omni = { dictionary graph = { string type = "normalh[3]" normal3h default = (0.5, 0.625, 0.75) } } } ) custom rel omni:graph:input:a_normalh_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "normalh[3][]" normal3h[] default = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] } } } ) custom rel omni:graph:input:a_objectId ( customData = { dictionary omni = { dictionary graph = { string type = "objectId" uint64 default = 46 } } } ) custom rel omni:graph:input:a_objectId_array ( customData = { dictionary omni = { dictionary graph = { string type = "uint64[]" uint64[] default = [46, 64] } } } ) custom rel omni:graph:input:a_path ( customData = { dictionary omni = { dictionary graph = { string type = "path" string default = "/This/Is" } } } ) custom rel omni:graph:input:a_pointd_3 ( customData = { dictionary omni = { dictionary graph = { string type = "pointd[3]" point3d default = (0.01625, 0.14125, 0.26625) } } } ) custom rel omni:graph:input:a_pointd_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "pointd[3][]" point3d[] default = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] } } } ) custom rel omni:graph:input:a_pointf_3 ( customData = { dictionary omni = { dictionary graph = { string type = "pointf[3]" point3f default = (0.125, 0.25, 0.375) } } } ) custom rel omni:graph:input:a_pointf_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "pointf[3][]" point3f[] default = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] } } } ) custom rel omni:graph:input:a_pointh_3 ( customData = { dictionary omni = { dictionary graph = { string type = "pointh[3]" point3h default = (0.5, 0.625, 0.75) } } } ) custom rel omni:graph:input:a_pointh_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "pointh[3][]" point3h[] default = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] } } } ) custom rel omni:graph:input:a_quatd_4 ( customData = { dictionary omni = { dictionary graph = { string type = "quatd[4]" quatd default = (0.78, 0.01625, 0.14125, 0.26625) } } } ) custom rel omni:graph:input:a_quatd_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "quatd[4][]" quatd[] default = [(0.78, 0.01625, 0.14125, 0.26625), (0.51625, 0.14125, 0.26625, 0.39125)] } } } ) custom rel omni:graph:input:a_quatf_4 ( customData = { dictionary omni = { dictionary graph = { string type = "quatf[4]" quatf default = (0.5, 0.125, 0.25, 0.375) } } } ) custom rel omni:graph:input:a_quatf_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "quatf[4][]" quatf[] default = [(0.5, 0.125, 0.25, 0.375), (0.625, 0.25, 0.375, 0.5)] } } } ) custom rel omni:graph:input:a_quath_4 ( customData = { dictionary omni = { dictionary graph = { string type = "quath[4]" quath default = (0.75, 0, 0.25, 0.5) } } } ) custom rel omni:graph:input:a_quath_4_array ( customData = { dictionary omni = { dictionary graph = { string type = "quath[4][]" quath[] default = [(0.75, 0, 0.25, 0.5), (0.875, 0.125, 0.375, 0.625)] } } } ) custom rel omni:graph:input:a_string ( customData = { dictionary omni = { dictionary graph = { string type = "string" string default = "Anakin" } } } ) custom rel omni:graph:input:a_texcoordd_2 ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordd[2]" texCoord2d default = (0.01625, 0.14125) } } } ) custom rel omni:graph:input:a_texcoordd_2_array ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordd[2][]" texCoord2d[] default = [(0.01625, 0.14125), (0.14125, 0.01625)] } } } ) custom rel omni:graph:input:a_texcoordd_3 ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordd[3]" texCoord3d default = (0.01625, 0.14125, 0.26625) } } } ) custom rel omni:graph:input:a_texcoordd_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordd[3][]" texCoord3d[] default = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] } } } ) custom rel omni:graph:input:a_texcoordf_2 ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordf[2]" texCoord2f default = (0.125, 0.25) } } } ) custom rel omni:graph:input:a_texcoordf_2_array ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordf[2][]" texCoord2f[] default = [(0.125, 0.25), (0.25, 0.125)] } } } ) custom rel omni:graph:input:a_texcoordf_3 ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordf[3]" texCoord3f default = (0.125, 0.25, 0.375) } } } ) custom rel omni:graph:input:a_texcoordf_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordf[3][]" texCoord3f[] default = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] } } } ) custom rel omni:graph:input:a_texcoordh_2 ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordh[2]" texCoord2h default = (0.5, 0.625) } } } ) custom rel omni:graph:input:a_texcoordh_2_array ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordh[2][]" texCoord2h[] default = [(0.5, 0.625), (0.625, 0.5)] } } } ) custom rel omni:graph:input:a_texcoordh_3 ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordh[3]" texCoord3h default = (0.5, 0.625, 0.75) } } } ) custom rel omni:graph:input:a_texcoordh_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "texCoordh[3][]" texCoord3h[] default = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] } } } ) custom rel omni:graph:input:a_timecode ( customData = { dictionary omni = { dictionary graph = { string type = "timecode" timecode default = 5 } } } ) custom rel omni:graph:input:a_timecode_array ( customData = { dictionary omni = { dictionary graph = { string type = "timecode[]" timecode[] default = [5, 6] } } } ) custom rel omni:graph:input:a_token ( customData = { dictionary omni = { dictionary graph = { string type = "token" token default = "Ahsoka" } } } ) custom rel omni:graph:input:a_token_array ( customData = { dictionary omni = { dictionary graph = { string type = "token[]" token[] default = ["Ahsoka", "Tano"] } } } ) custom rel omni:graph:input:a_uchar ( customData = { dictionary omni = { dictionary graph = { string type = "uchar" uchar default = 12 } } } ) custom rel omni:graph:input:a_uchar_array ( customData = { dictionary omni = { dictionary graph = { string type = "uchar[]" uchar[] default = [12, 8] } } } ) custom rel omni:graph:input:a_uint ( customData = { dictionary omni = { dictionary graph = { string type = "uint" uint default = 32 } } } ) custom rel omni:graph:input:a_uint64 ( customData = { dictionary omni = { dictionary graph = { string type = "uint64" uint64 default = 46 } } } ) custom rel omni:graph:input:a_uint64_array ( customData = { dictionary omni = { dictionary graph = { string type = "uint64[]" uint64[] default = [46, 64] } } } ) custom rel omni:graph:input:a_uint_array ( customData = { dictionary omni = { dictionary graph = { string type = "uint[]" uint[] default = [32, 23] } } } ) custom rel omni:graph:input:a_vectord_3 ( customData = { dictionary omni = { dictionary graph = { string type = "vectord[3]" vector3d default = (0.01625, 0.14125, 0.26625) } } } ) custom rel omni:graph:input:a_vectord_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "vectord[3][]" vector3d[] default = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] } } } ) custom rel omni:graph:input:a_vectorf_3 ( customData = { dictionary omni = { dictionary graph = { string type = "vectorf[3]" vector3f default = (0.125, 0.25, 0.375) } } } ) custom rel omni:graph:input:a_vectorf_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "vectorf[3][]" vector3f[] default = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] } } } ) custom rel omni:graph:input:a_vectorh_3 ( customData = { dictionary omni = { dictionary graph = { string type = "vectorh[3]" vector3h default = (0.5, 0.625, 0.75) } } } ) custom rel omni:graph:input:a_vectorh_3_array ( customData = { dictionary omni = { dictionary graph = { string type = "vectorh[3][]" vector3h[] default = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] } } } ) token omni:graph:namespace = "local.nodes" def OmniGraph "Graph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 6) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "print_text" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execIn custom token inputs:logLevel = "Info" ( allowedTokens = ["Info", "Warning", "Error"] ) custom string inputs:text = "" custom bool inputs:toScreen = 0 custom token inputs:viewport = "" token node:type = "omni.graph.ui.PrintText" int node:typeVersion = 1 custom uint outputs:execOut ( customData = { bool isExecution = 1 } ) uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (382, 166) } } } } } def Xform "Environment" { 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"] 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"] } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestReferenceInstance.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (578.8124999999998, 578.8124999999999, 578.8125000000003) 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 = { } } dictionary renderSettings = { float3 "rtx:raytracing:inscattering:singleScatteringAlbedo" = (0.9, 0.9, 0.9) float3 "rtx:raytracing:inscattering:transmittanceColor" = (0.5, 0.5, 0.5) } } defaultPrim = "Root" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "Root" { def OmniGraph "ActionGraph" { token evaluator:type = "execution" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 3) token pipelineStage = "pipelineStageOnDemand" def OmniGraphNode "on_tick" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:framePeriod = 0 custom bool inputs:onlyPlayback = 1 custom token node:type = "omni.graph.action.OnTick" custom int node:typeVersion = 1 custom double outputs:absoluteSimTime = 0 custom double outputs:deltaSeconds = 0 custom double outputs:frame = 0 custom bool outputs:isPlaying = 0 custom uint outputs:tick = 0 ( customData = { bool isExecution = 1 } ) custom double outputs:time = 0 custom double outputs:timeSinceStart = 0 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (52.620888, 65.83809) } def OmniGraphNode "increment" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:increment = 1 custom token inputs:value = "" prepend token inputs:value.connect = </Root/ActionGraph/read_prim_attribute.outputs:value> custom token node:type = "omni.graph.nodes.Increment" custom int node:typeVersion = 1 custom token outputs:result uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (330.42627, 304.84106) } def OmniGraphNode "graph_target" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:targetPath custom token node:type = "omni.graph.nodes.GraphTarget" custom int node:typeVersion = 1 custom token outputs:primPath = "" uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-196.9863, 332.03223) } def OmniGraphNode "read_prim_attribute" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:name = "count" custom rel inputs:prim custom token inputs:primPath = "" prepend token inputs:primPath.connect = </Root/ActionGraph/graph_target.outputs:primPath> custom timecode inputs:usdTimecode = -1 custom bool inputs:usePath = 1 custom token node:type = "omni.graph.nodes.ReadPrimAttribute" custom int node:typeVersion = 1 custom token outputs:value custom uint64 state:target = 0 custom timecode state:usdTimecode = -1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (57.52121, 351.50977) } def OmniGraphNode "write_prim_attribute" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execIn = 0 prepend uint inputs:execIn.connect = </Root/ActionGraph/on_tick.outputs:tick> custom token inputs:name = "count" custom rel inputs:prim custom token inputs:primPath = "" prepend token inputs:primPath.connect = </Root/ActionGraph/graph_target.outputs:primPath> custom bool inputs:usePath = 1 custom token inputs:value = "" prepend token inputs:value.connect = </Root/ActionGraph/increment.outputs:result> custom token node:type = "omni.graph.nodes.WritePrimAttribute" custom int node:typeVersion = 1 custom uint outputs:execOut = 0 ( customData = { bool isExecution = 1 } ) uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (600.2972, 89.2115) } } def Xform "Instance" ( prepend apiSchemas = ["OmniGraphAPI"] ) { custom int count = 0 rel omniGraphs = </Root/ActionGraph> 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.graph.test/omni/graph/test/tests/data/TestInitWithController.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (0, 0, 0) } dictionary Right = { double3 position = (-50000, 0, -1.1102230246251565e-11) double3 target = (0, 0, 0) } dictionary Top = { double3 position = (-4.329780281177466e-12, 50000, 1.1102230246251565e-11) double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 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 ComputeNode "TestInitNode" { custom token node:type = "omnigraph.tests.testInitNode" custom int node:typeVersion = 1 custom float outputs:value } def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestNodeAttributeLookup.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 = { } } 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 GlobalComputeGraph "PushGraph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 2) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStageSimulation" } } def GlobalComputeGraph "PushGraph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 2) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStageSimulation" } def ComputeNode "read_prim" { custom rel inputs:prim prepend rel inputs:prim = </World/Cube> custom token node:type = "omni.graph.nodes.ReadPrim" custom int node:typeVersion = 1 custom float3[] outputs:extent custom double outputs:size custom double3 outputs:xformOp:rotateXYZ custom double3 outputs:xformOp:scale custom double3 outputs:xformOp:translate custom token[] outputs:xformOpOrder def Output "outputs_primBundle" { } def ComputeNodeMetaData "metaData" { custom token AttributeDownstreamConnection____outputs:xformOp:rotateXYZ = "/World/PushGraph/write_prim.inputs:xformOp:rotateXYZ,/World/PushGraph/add.inputs:a" } } def ComputeNode "write_prim" { custom uint inputs:execIn custom float3[] inputs:extent custom rel inputs:prim prepend rel inputs:prim = </World/Sphere> custom double inputs:radius custom bool inputs:refinementEnableOverride custom int inputs:refinementLevel custom double3 inputs:xformOp:rotateXYZ = (0, 0, 0) delete double3 inputs:xformOp:rotateXYZ.connect = </World/PushGraph/read_prim.outputs:xformOp:rotateXYZ> prepend double3 inputs:xformOp:rotateXYZ.connect = </World/PushGraph/read_prim.outputs:xformOp:rotateXYZ> custom double3 inputs:xformOp:scale custom double3 inputs:xformOp:translate custom token[] inputs:xformOpOrder custom token node:type = "omni.graph.nodes.WritePrim" custom int node:typeVersion = 1 custom uint outputs:execOut = 1 } def ComputeNode "add" { custom double3 __resolved_outputs:sum = (332.6912841796875, -0, 0) custom token inputs:a prepend token inputs:a.connect = </World/PushGraph/read_prim.outputs:xformOp:rotateXYZ> custom token inputs:b delete token inputs:b.connect = </World/PushGraph/read_prim.outputs:xformOp:rotateXYZ> prepend token inputs:b.connect = </World/PushGraph/constant_vec3d.inputs:value> custom token node:type = "omni.graph.nodes.Add" custom int node:typeVersion = 1 custom token outputs:sum def ComputeNodeMetaData "metaData" { custom token AttributeDownstreamConnection____outputs:sum = "/World/Cone.xformOp:rotateXYZ" } } def ComputeNode "copy_attributes_from_bundles" { custom rel inputs:fullData delete rel inputs:fullData = [ </World/PushGraph/read_prim/outputs_primBundle>, </World/Cube>, ] prepend rel inputs:fullData = </World/Capsule> custom token inputs:inputAttrNames = "" custom token inputs:outputAttrNames = "" custom rel inputs:partialData delete rel inputs:partialData = </World/PushGraph/read_prim/outputs_primBundle> custom token node:type = "omni.graph.nodes.CopyAttribute" custom int node:typeVersion = 1 def Output "outputs_data" { } def ComputeNodeMetaData "metaData" { custom token AttributeDownstreamConnection____outputs_data = "/World/PushGraph/remove_attributes_from_bundles.inputs:data" } } def ComputeNode "CylinderWrite" { custom token inputs:axis custom uint inputs:execIn custom float3[] inputs:extent custom double inputs:height custom rel inputs:prim prepend rel inputs:prim = </World/Cylinder> custom double inputs:radius custom bool inputs:refinementEnableOverride custom int inputs:refinementLevel custom double3 inputs:xformOp:rotateXYZ prepend double3 inputs:xformOp:rotateXYZ.connect = </World/PushGraph/extract_attribute.outputs:output> custom double3 inputs:xformOp:scale custom double3 inputs:xformOp:translate custom token[] inputs:xformOpOrder custom token node:type = "omni.graph.nodes.WritePrim" custom int node:typeVersion = 1 custom uint outputs:execOut = 1 } def ComputeNode "remove_attributes_from_bundles" { custom token inputs:attrNamesToRemove = "xformOp:translate xformOp:scale size xformOpOrder extent" custom rel inputs:data prepend rel inputs:data = </World/PushGraph/copy_attributes_from_bundles/outputs_data> custom token node:type = "omni.graph.nodes.RemoveAttribute" custom int node:typeVersion = 1 def Output "outputs_data" { } def ComputeNodeMetaData "metaData" { custom token AttributeDownstreamConnection____outputs_data = "/World/PushGraph/bundle_inspector.inputs:bundle" } } def ComputeNode "bundle_inspector" { custom rel inputs:bundle = </World/PushGraph/remove_attributes_from_bundles/outputs_data> custom bool inputs:print = 0 custom token node:type = "omni.graph.nodes.BundleInspector" custom int node:typeVersion = 1 custom int[] outputs:arrayDepths = [0] custom uint64 outputs:count = 1 custom token[] outputs:names = ["xformOp:rotateXYZ"] custom token[] outputs:roles = ["none"] custom int[] outputs:tupleCounts = [3] custom token[] outputs:types = ["double"] custom token[] outputs:values = ["(166.067825, -0.000000, 0.000000)"] def Output "outputs_bundle" { } def ComputeNodeMetaData "metaData" { custom token AttributeDownstreamConnection____outputs_bundle = "/World/PushGraph/extract_attribute.inputs:data" } } def ComputeNode "extract_attribute" { custom double3 __resolved_outputs:output = (166.0678253173828, -0, 0) custom token inputs:attrName = "xformOp:rotateXYZ" custom rel inputs:data prepend rel inputs:data = </World/PushGraph/bundle_inspector/outputs_bundle> custom token node:type = "omni.graph.nodes.ExtractAttribute" custom int node:typeVersion = 1 custom token outputs:output def ComputeNodeMetaData "metaData" { custom token AttributeDownstreamConnection____outputs:output = "/World/PushGraph/CylinderWrite.inputs:xformOp:rotateXYZ" } } def ComputeNode "constant_vec3d" { custom double3 inputs:value = (0, 0, 0) custom token node:type = "omni.graph.nodes.ConstantVec3d" custom int node:typeVersion = 1 def ComputeNodeMetaData "metaData" { custom token AttributeDownstreamConnection____inputs:value = "/World/PushGraph/add.inputs:b" } } } def Cube "Cube" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double size = 100 double3 xformOp:rotateXYZ = (0, -0, 0) double3 xformOp:scale = (1, 0.9999998211860657, 0.9999998211860657) double3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } 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 = (178.104, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Cone "Cone" { uniform token axis = "Y" float3[] extent = [(-50, -50, -50), (50, 50, 50)] double height = 100 double radius = 50 custom bool refinementEnableOverride = 1 custom int refinementLevel = 2 double3 xformOp:rotateXYZ = (0, 0, 0) delete double3 xformOp:rotateXYZ.connect = </World/PushGraph/read_prim.outputs:xformOp:rotateXYZ> prepend double3 xformOp:rotateXYZ.connect = </World/PushGraph/add.outputs:sum> double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (-251.908, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Cylinder "Cylinder" { uniform token axis = "Y" float3[] extent = [(-50, -50, -50), (50, 50, 50)] double height = 100 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, -276.967) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Capsule "Capsule" { uniform token axis = "Y" float3[] extent = [(-25, -25, -50), (25, 25, 50)] double height = 50 double radius = 25 custom bool refinementEnableOverride = 1 custom int refinementLevel = 2 double3 xformOp:rotateXYZ = (0, -0, 0) double3 xformOp:scale = (1, 1.0000003576278687, 1.0000003576278687) double3 xformOp:translate = (-19.7621, -1.09693e-13, 211.465) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestActionFanIn.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.00000397803842133726, 0.000007956076785831101, -0.00000397803842133726) } 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 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) bool "rtx:hashed:7351ffd78c5b3d6bf71f42e4d2dd2b35" = 0 bool "rtx:hashed:95b9b3a228047f919df3074b7014886f" = 0 float3 "rtx:lightspeed:material:overrideAlbedo" = (0.5, 0.5, 0.5) float3 "rtx:lightspeed:material:overrideEmissiveColor" = (0.5, 0.5, 0.5) bool "rtx:pathtracing:nrc:canRun" = 0 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) int "rtx:shaderDb:cachePermutationIndex" = -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, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "on_keyboard_input" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:altIn = 0 custom bool inputs:ctrlIn = 0 custom token inputs:keyIn = "A" ( allowedTokens = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Apostrophe", "Backslash", "Backspace", "CapsLock", "Comma", "Del", "Down", "End", "Enter", "Equal", "Escape", "F1", "F10", "F11", "F12", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "GraveAccent", "Home", "Insert", "Key0", "Key1", "Key2", "Key3", "Key4", "Key5", "Key6", "Key7", "Key8", "Key9", "Left", "LeftAlt", "LeftBracket", "LeftControl", "LeftShift", "LeftSuper", "Menu", "Minus", "NumLock", "Numpad0", "Numpad1", "Numpad2", "Numpad3", "Numpad4", "Numpad5", "Numpad6", "Numpad7", "Numpad8", "Numpad9", "NumpadAdd", "NumpadDel", "NumpadDivide", "NumpadEnter", "NumpadEqual", "NumpadMultiply", "NumpadSubtract", "PageDown", "PageUp", "Pause", "Period", "PrintScreen", "Right", "RightAlt", "RightBracket", "RightControl", "RightShift", "RightSuper", "ScrollLock", "Semicolon", "Slash", "Space", "Tab", "Up"] ) custom bool inputs:onlyPlayback = 0 custom bool inputs:shiftIn = 0 token node:type = "omni.graph.action.OnKeyboardInput" int node:typeVersion = 3 custom bool outputs:isPressed custom token outputs:keyOut custom uint outputs:pressed ( customData = { bool isExecution = 1 } ) custom uint outputs:released ( customData = { bool isExecution = 1 } ) uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-28.32303, 30.558456) } def OmniGraphNode "for_loop" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:breakLoop custom uint inputs:execIn prepend uint inputs:execIn.connect = [ </World/ActionGraph/on_keyboard_input.outputs:pressed>, </World/ActionGraph/on_impulse_event.outputs:execOut>, ] custom int inputs:start = 0 custom int inputs:step = 1 custom int inputs:stop = 2 token node:type = "omni.graph.action.ForLoop" int node:typeVersion = 1 custom uint outputs:finished ( customData = { bool isExecution = 1 } ) custom int outputs:index custom uint outputs:loopBody ( customData = { bool isExecution = 1 } ) custom int outputs:value custom int state:i = -1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (310, 94) } def OmniGraphNode "counter" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execIn prepend uint inputs:execIn.connect = </World/ActionGraph/for_loop.outputs:loopBody> custom token inputs:logLevel = "Info" ( allowedTokens = ["Info", "Warning", "Error"] ) custom uint inputs:reset token node:type = "omni.graph.action.Counter" int node:typeVersion = 1 custom int outputs:count custom uint outputs:execOut ( customData = { bool isExecution = 1 } ) custom int state:count uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (664.4135, -53.116158) } def OmniGraphNode "counter_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execIn prepend uint inputs:execIn.connect = </World/ActionGraph/for_loop.outputs:loopBody> custom token inputs:logLevel = "Info" ( allowedTokens = ["Info", "Warning", "Error"] ) custom uint inputs:reset token node:type = "omni.graph.action.Counter" int node:typeVersion = 1 custom int outputs:count custom uint outputs:execOut ( customData = { bool isExecution = 1 } ) custom int state:count uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (660.609, 374.31915) } def OmniGraphNode "counter_02" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execIn prepend uint inputs:execIn.connect = </World/ActionGraph/sync_gate.outputs:execOut> custom token inputs:logLevel = "Info" ( allowedTokens = ["Info", "Warning", "Error"] ) custom uint inputs:reset token node:type = "omni.graph.action.Counter" int node:typeVersion = 1 custom int outputs:count custom uint outputs:execOut ( customData = { bool isExecution = 1 } ) custom int state:count uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (1403.963, 203.39139) } def OmniGraphNode "on_impulse_event" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:onlyPlayback = 0 token node:type = "omni.graph.action.OnImpulseEvent" int node:typeVersion = 2 custom uint outputs:execOut ( customData = { bool isExecution = 1 } ) custom bool state:enableImpulse uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (10.181118, -137.32922) } def OmniGraphNode "sync_gate" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom uint inputs:execIn prepend uint inputs:execIn.connect = [ </World/ActionGraph/counter.outputs:execOut>, </World/ActionGraph/counter_01.outputs:execOut>, ] custom uint64 inputs:syncValue = 0 prepend uint64 inputs:syncValue.connect = </World/ActionGraph/to_uint64.outputs:converted> token node:type = "omni.graph.action.SyncGate" int node:typeVersion = 1 custom uint outputs:execOut ( customData = { bool isExecution = 1 } ) custom uint64 outputs:syncValue uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (1065.7456, 144.79875) } def OmniGraphNode "to_uint64" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:value prepend token inputs:value.connect = </World/ActionGraph/for_loop.outputs:index> token node:type = "omni.graph.nodes.ToUint64" int node:typeVersion = 1 custom token outputs:converted uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (734.48773, 203.07834) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestOM70414.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.00000397803842133726, 0.000007956076785831101, -0.000003978038307650422) } 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: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 = 1000 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestAllDataTypesPy.NonDefault.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.00000397803842133726, 0.000007956076785831101, -0.000003978038307650422) } 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 = { int "rtx:hydra:curves:splits" = 2 double "rtx:hydra:points:defaultWidth" = 1 float3 "rtx:iray:environment_dome_rotation_axis" = (0, 1, 0) } } metersPerUnit = 0.01 timeCodesPerSecond = 24 upAxis = "Y" ) def "World" { def OmniGraph "TestGraph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "TestAllDataTypesPy" { custom bool inputs:a_bool = 0 custom bool[] inputs:a_bool_array = [0, 1] custom rel inputs:a_bundle custom color3d inputs:a_colord_3 = (0.01625, 0.14125, 0.26625) custom color3d[] inputs:a_colord_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom color4d inputs:a_colord_4 = (0.01625, 0.14125, 0.26625, 0.39125) custom color4d[] inputs:a_colord_4_array = [(0.01625, 0.14125, 0.26625, 0.39125), (0.39125, 0.26625, 0.14125, 0.01625)] custom color3f inputs:a_colorf_3 = (0.125, 0.25, 0.375) custom color3f[] inputs:a_colorf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom color4f inputs:a_colorf_4 = (0.125, 0.25, 0.375, 0.5) custom color4f[] inputs:a_colorf_4_array = [(0.125, 0.25, 0.375, 0.5), (0.5, 0.375, 0.25, 0.125)] custom color3h inputs:a_colorh_3 = (0.5, 0.625, 0.75) custom color3h[] inputs:a_colorh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom color4h inputs:a_colorh_4 = (0.5, 0.625, 0.75, 0.875) custom color4h[] inputs:a_colorh_4_array = [(0.5, 0.625, 0.75, 0.875), (0.875, 0.75, 0.625, 0.5)] custom double inputs:a_double = 4.125 custom double2 inputs:a_double_2 = (4.125, 4.25) custom double2[] inputs:a_double_2_array = [(4.125, 4.25), (2.125, 2.25)] custom double3 inputs:a_double_3 = (4.125, 4.25, 4.375) custom double3[] inputs:a_double_3_array = [(4.125, 4.25, 4.375), (2.125, 2.25, 2.375)] custom double4 inputs:a_double_4 = (4.125, 4.25, 4.375, 4.5) custom double4[] inputs:a_double_4_array = [(4.125, 4.25, 4.375, 4.5), (2.125, 2.25, 2.375, 2.5)] custom double[] inputs:a_double_array = [4.125, 2.125] custom uint inputs:a_execution = 0 custom float inputs:a_float = 4.5 custom float2 inputs:a_float_2 = (4.5, 4.625) custom float2[] inputs:a_float_2_array = [(4.5, 4.625), (2.5, 2.625)] custom float3 inputs:a_float_3 = (4.5, 4.625, 4.75) custom float3[] inputs:a_float_3_array = [(4.5, 4.625, 4.75), (2.5, 2.625, 2.75)] custom float4 inputs:a_float_4 = (4.5, 4.625, 4.75, 4.875) custom float4[] inputs:a_float_4_array = [(4.5, 4.625, 4.75, 4.875), (2.5, 2.625, 2.75, 2.875)] custom float[] inputs:a_float_array = [4.5, 2.5] custom frame4d inputs:a_frame_4 = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ) custom frame4d[] inputs:a_frame_4_array = [( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ), ( (2, 3, 3, 3), (3, 2, 3, 3), (3, 3, 2, 3), (3, 3, 3, 2) )] custom half inputs:a_half = 2.5 custom half2 inputs:a_half_2 = (2.5, 2.625) custom half2[] inputs:a_half_2_array = [(2.5, 2.625), (4.5, 4.625)] custom half3 inputs:a_half_3 = (2.5, 2.625, 2.75) custom half3[] inputs:a_half_3_array = [(2.5, 2.625, 2.75), (4.5, 4.625, 4.75)] custom half4 inputs:a_half_4 = (2.5, 2.625, 2.75, 2.875) custom half4[] inputs:a_half_4_array = [(2.5, 2.625, 2.75, 2.875), (4.5, 4.625, 4.75, 4.875)] custom half[] inputs:a_half_array = [2.5, 4.5] custom int inputs:a_int = -32 custom int64 inputs:a_int64 = -46 custom int64[] inputs:a_int64_array = [-46, -64] custom int2 inputs:a_int_2 = (-32, -31) custom int2[] inputs:a_int_2_array = [(-32, -31), (-23, -22)] custom int3 inputs:a_int_3 = (-32, -31, -30) custom int3[] inputs:a_int_3_array = [(-32, -31, -30), (-23, -22, -21)] custom int4 inputs:a_int_4 = (-32, -31, -30, -29) custom int4[] inputs:a_int_4_array = [(-32, -31, -30, -29), (-23, -22, -21, -20)] custom int[] inputs:a_int_array = [-32, -23] custom matrix2d inputs:a_matrixd_2 = ( (1, 0), (0, 1) ) custom matrix2d[] inputs:a_matrixd_2_array = [( (1, 0), (0, 1) ), ( (2, 3), (3, 2) )] custom matrix3d inputs:a_matrixd_3 = ( (1, 0, 0), (0, 1, 0), (0, 0, 1) ) custom matrix3d[] inputs:a_matrixd_3_array = [( (1, 0, 0), (0, 1, 0), (0, 0, 1) ), ( (2, 3, 3), (3, 2, 3), (3, 3, 2) )] custom matrix4d inputs:a_matrixd_4 = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ) custom matrix4d[] inputs:a_matrixd_4_array = [( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ), ( (2, 3, 3, 3), (3, 2, 3, 3), (3, 3, 2, 3), (3, 3, 3, 2) )] custom normal3d inputs:a_normald_3 = (0.01625, 0.14125, 0.26625) custom normal3d[] inputs:a_normald_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom normal3f inputs:a_normalf_3 = (0.125, 0.25, 0.375) custom normal3f[] inputs:a_normalf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom normal3h inputs:a_normalh_3 = (0.5, 0.625, 0.75) custom normal3h[] inputs:a_normalh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom uint64 inputs:a_objectId = 46 custom uint64[] inputs:a_objectId_array = [46, 64] custom string inputs:a_path = "/This/Is" custom point3d inputs:a_pointd_3 = (0.01625, 0.14125, 0.26625) custom point3d[] inputs:a_pointd_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom point3f inputs:a_pointf_3 = (0.125, 0.25, 0.375) custom point3f[] inputs:a_pointf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom point3h inputs:a_pointh_3 = (0.5, 0.625, 0.75) custom point3h[] inputs:a_pointh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom quatd inputs:a_quatd_4 = (0.78, 0.01625, 0.14125, 0.26625) custom quatd[] inputs:a_quatd_4_array = [(0.78, 0.01625, 0.14125, 0.26625), (0.51625, 0.14125, 0.26625, 0.39125)] custom quatf inputs:a_quatf_4 = (0.5, 0.125, 0.25, 0.375) custom quatf[] inputs:a_quatf_4_array = [(0.5, 0.125, 0.25, 0.375), (0.625, 0.25, 0.375, 0.5)] custom quath inputs:a_quath_4 = (0.75, 0, 0.25, 0.5) custom quath[] inputs:a_quath_4_array = [(0.75, 0, 0.25, 0.5), (0.875, 0.125, 0.375, 0.625)] custom string inputs:a_string = "Anakin" custom texCoord2d inputs:a_texcoordd_2 = (0.01625, 0.14125) custom texCoord2d[] inputs:a_texcoordd_2_array = [(0.01625, 0.14125), (0.14125, 0.01625)] custom texCoord3d inputs:a_texcoordd_3 = (0.01625, 0.14125, 0.26625) custom texCoord3d[] inputs:a_texcoordd_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom texCoord2f inputs:a_texcoordf_2 = (0.125, 0.25) custom texCoord2f[] inputs:a_texcoordf_2_array = [(0.125, 0.25), (0.25, 0.125)] custom texCoord3f inputs:a_texcoordf_3 = (0.125, 0.25, 0.375) custom texCoord3f[] inputs:a_texcoordf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom texCoord2h inputs:a_texcoordh_2 = (0.5, 0.625) custom texCoord2h[] inputs:a_texcoordh_2_array = [(0.5, 0.625), (0.625, 0.5)] custom texCoord3h inputs:a_texcoordh_3 = (0.5, 0.625, 0.75) custom texCoord3h[] inputs:a_texcoordh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom timecode inputs:a_timecode = 5 custom timecode[] inputs:a_timecode_array = [5, 6] custom token inputs:a_token = "Ahsoka" custom token[] inputs:a_token_array = ["Ahsoka", "Tano"] custom uchar inputs:a_uchar = 12 custom uchar[] inputs:a_uchar_array = [12, 8] custom uint inputs:a_uint = 32 custom uint64 inputs:a_uint64 = 46 custom uint64[] inputs:a_uint64_array = [46, 64] custom uint[] inputs:a_uint_array = [32, 23] custom vector3d inputs:a_vectord_3 = (0.01625, 0.14125, 0.26625) custom vector3d[] inputs:a_vectord_3_array = [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] custom vector3f inputs:a_vectorf_3 = (0.125, 0.25, 0.375) custom vector3f[] inputs:a_vectorf_3_array = [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] custom vector3h inputs:a_vectorh_3 = (0.5, 0.625, 0.75) custom vector3h[] inputs:a_vectorh_3_array = [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] custom bool inputs:doNotCompute = 0 token node:type = "omni.graph.test.TestAllDataTypesPy" int node:typeVersion = 1 custom bool outputs:a_bool = 1 custom bool[] outputs:a_bool_array = [1, 0] custom color3d outputs:a_colord_3 = (1.5, 2.5, 3.5) custom color3d[] outputs:a_colord_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4d outputs:a_colord_4 = (1.5, 2.5, 3.5, 4.5) custom color4d[] outputs:a_colord_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom color3f outputs:a_colorf_3 = (1.5, 2.5, 3.5) custom color3f[] outputs:a_colorf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4f outputs:a_colorf_4 = (1.5, 2.5, 3.5, 4.5) custom color4f[] outputs:a_colorf_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom color3h outputs:a_colorh_3 = (1.5, 2.5, 3.5) custom color3h[] outputs:a_colorh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4h outputs:a_colorh_4 = (1.5, 2.5, 3.5, 4.5) custom color4h[] outputs:a_colorh_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom double outputs:a_double = 1.5 custom double2 outputs:a_double_2 = (1.5, 2.5) custom double2[] outputs:a_double_2_array = [(1.5, 2.5), (11.5, 12.5)] custom double3 outputs:a_double_3 = (1.5, 2.5, 3.5) custom double3[] outputs:a_double_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom double4 outputs:a_double_4 = (1.5, 2.5, 3.5, 4.5) custom double4[] outputs:a_double_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom double[] outputs:a_double_array = [1.5, 2.5] custom uint outputs:a_execution = 2 ( customData = { bool isExecution = 1 } ) custom float outputs:a_float = 1.5 custom float2 outputs:a_float_2 = (1.5, 2.5) custom float2[] outputs:a_float_2_array = [(1.5, 2.5), (11.5, 12.5)] custom float3 outputs:a_float_3 = (1.5, 2.5, 3.5) custom float3[] outputs:a_float_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom float4 outputs:a_float_4 = (1.5, 2.5, 3.5, 4.5) custom float4[] outputs:a_float_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom float[] outputs:a_float_array = [1.5, 2.5] custom frame4d outputs:a_frame_4 = ( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ) custom frame4d[] outputs:a_frame_4_array = [( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ), ( (11.5, 12.5, 13.5, 14.5), (15.5, 16.5, 17.5, 18.5), (19.5, 20.5, 21.5, 22.5), (23.5, 24.5, 25.5, 26.5) )] custom half outputs:a_half = 1.5 custom half2 outputs:a_half_2 = (1.5, 2.5) custom half2[] outputs:a_half_2_array = [(1.5, 2.5), (11.5, 12.5)] custom half3 outputs:a_half_3 = (1.5, 2.5, 3.5) custom half3[] outputs:a_half_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom half4 outputs:a_half_4 = (1.5, 2.5, 3.5, 4.5) custom half4[] outputs:a_half_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom half[] outputs:a_half_array = [1.5, 2.5] custom int outputs:a_int = 1 custom int64 outputs:a_int64 = 12345 custom int64[] outputs:a_int64_array = [12345, 23456] custom int2 outputs:a_int_2 = (1, 2) custom int2[] outputs:a_int_2_array = [(1, 2), (3, 4)] custom int3 outputs:a_int_3 = (1, 2, 3) custom int3[] outputs:a_int_3_array = [(1, 2, 3), (4, 5, 6)] custom int4 outputs:a_int_4 = (1, 2, 3, 4) custom int4[] outputs:a_int_4_array = [(1, 2, 3, 4), (5, 6, 7, 8)] custom int[] outputs:a_int_array = [1, 2] custom matrix2d outputs:a_matrixd_2 = ( (1.5, 2.5), (3.5, 4.5) ) custom matrix2d[] outputs:a_matrixd_2_array = [( (1.5, 2.5), (3.5, 4.5) ), ( (11.5, 12.5), (13.5, 14.5) )] custom matrix3d outputs:a_matrixd_3 = ( (1.5, 2.5, 3.5), (4.5, 5.5, 6.5), (7.5, 8.5, 9.5) ) custom matrix3d[] outputs:a_matrixd_3_array = [( (1.5, 2.5, 3.5), (4.5, 5.5, 6.5), (7.5, 8.5, 9.5) ), ( (11.5, 12.5, 13.5), (14.5, 15.5, 16.5), (17.5, 18.5, 19.5) )] custom matrix4d outputs:a_matrixd_4 = ( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ) custom matrix4d[] outputs:a_matrixd_4_array = [( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ), ( (11.5, 12.5, 13.5, 14.5), (15.5, 16.5, 17.5, 18.5), (19.5, 20.5, 21.5, 22.5), (23.5, 24.5, 25.5, 26.5) )] custom normal3d outputs:a_normald_3 = (1.5, 2.5, 3.5) custom normal3d[] outputs:a_normald_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom normal3f outputs:a_normalf_3 = (1.5, 2.5, 3.5) custom normal3f[] outputs:a_normalf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom normal3h outputs:a_normalh_3 = (1.5, 2.5, 3.5) custom normal3h[] outputs:a_normalh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom uint64 outputs:a_objectId = 2 custom uint64[] outputs:a_objectId_array = [2, 3] custom string outputs:a_path = "/Output" custom point3d outputs:a_pointd_3 = (1.5, 2.5, 3.5) custom point3d[] outputs:a_pointd_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom point3f outputs:a_pointf_3 = (1.5, 2.5, 3.5) custom point3f[] outputs:a_pointf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom point3h outputs:a_pointh_3 = (1.5, 2.5, 3.5) custom point3h[] outputs:a_pointh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom quatd outputs:a_quatd_4 = (4.5, 1.5, 2.5, 3.5) custom quatd[] outputs:a_quatd_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom quatf outputs:a_quatf_4 = (4.5, 1.5, 2.5, 3.5) custom quatf[] outputs:a_quatf_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom quath outputs:a_quath_4 = (4.5, 1.5, 2.5, 3.5) custom quath[] outputs:a_quath_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom string outputs:a_string = "Snoke" custom texCoord2d outputs:a_texcoordd_2 = (1.5, 2.5) custom texCoord2d[] outputs:a_texcoordd_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3d outputs:a_texcoordd_3 = (1.5, 2.5, 3.5) custom texCoord3d[] outputs:a_texcoordd_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom texCoord2f outputs:a_texcoordf_2 = (1.5, 2.5) custom texCoord2f[] outputs:a_texcoordf_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3f outputs:a_texcoordf_3 = (1.5, 2.5, 3.5) custom texCoord3f[] outputs:a_texcoordf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom texCoord2h outputs:a_texcoordh_2 = (1.5, 2.5) custom texCoord2h[] outputs:a_texcoordh_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3h outputs:a_texcoordh_3 = (1.5, 2.5, 3.5) custom texCoord3h[] outputs:a_texcoordh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom timecode outputs:a_timecode = 2.5 custom timecode[] outputs:a_timecode_array = [2.5, 3.5] custom token outputs:a_token = "Jedi" custom token[] outputs:a_token_array = ["Luke", "Skywalker"] custom uchar outputs:a_uchar = 2 custom uchar[] outputs:a_uchar_array = [2, 3] custom uint outputs:a_uint = 2 custom uint64 outputs:a_uint64 = 2 custom uint64[] outputs:a_uint64_array = [2, 3] custom uint[] outputs:a_uint_array = [2, 3] custom vector3d outputs:a_vectord_3 = (1.5, 2.5, 3.5) custom vector3d[] outputs:a_vectord_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom vector3f outputs:a_vectorf_3 = (1.5, 2.5, 3.5) custom vector3f[] outputs:a_vectorf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom vector3h outputs:a_vectorh_3 = (1.5, 2.5, 3.5) custom vector3h[] outputs:a_vectorh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom bool state:a_bool = 1 custom bool[] state:a_bool_array = [1, 0] custom color3d state:a_colord_3 = (1.5, 2.5, 3.5) custom color3d[] state:a_colord_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4d state:a_colord_4 = (1.5, 2.5, 3.5, 4.5) custom color4d[] state:a_colord_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom color3f state:a_colorf_3 = (1.5, 2.5, 3.5) custom color3f[] state:a_colorf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4f state:a_colorf_4 = (1.5, 2.5, 3.5, 4.5) custom color4f[] state:a_colorf_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom color3h state:a_colorh_3 = (1.5, 2.5, 3.5) custom color3h[] state:a_colorh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom color4h state:a_colorh_4 = (1.5, 2.5, 3.5, 4.5) custom color4h[] state:a_colorh_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom double state:a_double = 1.5 custom double2 state:a_double_2 = (1.5, 2.5) custom double2[] state:a_double_2_array = [(1.5, 2.5), (11.5, 12.5)] custom double3 state:a_double_3 = (1.5, 2.5, 3.5) custom double3[] state:a_double_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom double4 state:a_double_4 = (1.5, 2.5, 3.5, 4.5) custom double4[] state:a_double_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom double[] state:a_double_array = [1.5, 2.5] custom uint state:a_execution = 2 custom bool state:a_firstEvaluation = 1 custom float state:a_float = 1.5 custom float2 state:a_float_2 = (1.5, 2.5) custom float2[] state:a_float_2_array = [(1.5, 2.5), (11.5, 12.5)] custom float3 state:a_float_3 = (1.5, 2.5, 3.5) custom float3[] state:a_float_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom float4 state:a_float_4 = (1.5, 2.5, 3.5, 4.5) custom float4[] state:a_float_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom float[] state:a_float_array = [1.5, 2.5] custom frame4d state:a_frame_4 = ( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ) custom frame4d[] state:a_frame_4_array = [( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ), ( (11.5, 12.5, 13.5, 14.5), (15.5, 16.5, 17.5, 18.5), (19.5, 20.5, 21.5, 22.5), (23.5, 24.5, 25.5, 26.5) )] custom half state:a_half = 1.5 custom half2 state:a_half_2 = (1.5, 2.5) custom half2[] state:a_half_2_array = [(1.5, 2.5), (11.5, 12.5)] custom half3 state:a_half_3 = (1.5, 2.5, 3.5) custom half3[] state:a_half_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom half4 state:a_half_4 = (1.5, 2.5, 3.5, 4.5) custom half4[] state:a_half_4_array = [(1.5, 2.5, 3.5, 4.5), (11.5, 12.5, 13.5, 14.5)] custom half[] state:a_half_array = [1.5, 2.5] custom int state:a_int = 1 custom int64 state:a_int64 = 12345 custom int64[] state:a_int64_array = [12345, 23456] custom int2 state:a_int_2 = (1, 2) custom int2[] state:a_int_2_array = [(1, 2), (3, 4)] custom int3 state:a_int_3 = (1, 2, 3) custom int3[] state:a_int_3_array = [(1, 2, 3), (4, 5, 6)] custom int4 state:a_int_4 = (1, 2, 3, 4) custom int4[] state:a_int_4_array = [(1, 2, 3, 4), (5, 6, 7, 8)] custom int[] state:a_int_array = [1, 2] custom matrix2d state:a_matrixd_2 = ( (1.5, 2.5), (3.5, 4.5) ) custom matrix2d[] state:a_matrixd_2_array = [( (1.5, 2.5), (3.5, 4.5) ), ( (11.5, 12.5), (13.5, 14.5) )] custom matrix3d state:a_matrixd_3 = ( (1.5, 2.5, 3.5), (4.5, 5.5, 6.5), (7.5, 8.5, 9.5) ) custom matrix3d[] state:a_matrixd_3_array = [( (1.5, 2.5, 3.5), (4.5, 5.5, 6.5), (7.5, 8.5, 9.5) ), ( (11.5, 12.5, 13.5), (14.5, 15.5, 16.5), (17.5, 18.5, 19.5) )] custom matrix4d state:a_matrixd_4 = ( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ) custom matrix4d[] state:a_matrixd_4_array = [( (1.5, 2.5, 3.5, 4.5), (5.5, 6.5, 7.5, 8.5), (9.5, 10.5, 11.5, 12.5), (13.5, 14.5, 15.5, 16.5) ), ( (11.5, 12.5, 13.5, 14.5), (15.5, 16.5, 17.5, 18.5), (19.5, 20.5, 21.5, 22.5), (23.5, 24.5, 25.5, 26.5) )] custom normal3d state:a_normald_3 = (1.5, 2.5, 3.5) custom normal3d[] state:a_normald_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom normal3f state:a_normalf_3 = (1.5, 2.5, 3.5) custom normal3f[] state:a_normalf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom normal3h state:a_normalh_3 = (1.5, 2.5, 3.5) custom normal3h[] state:a_normalh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom uint64 state:a_objectId = 2 custom uint64[] state:a_objectId_array = [2, 3] custom string state:a_path = "/State" custom point3d state:a_pointd_3 = (1.5, 2.5, 3.5) custom point3d[] state:a_pointd_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom point3f state:a_pointf_3 = (1.5, 2.5, 3.5) custom point3f[] state:a_pointf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom point3h state:a_pointh_3 = (1.5, 2.5, 3.5) custom point3h[] state:a_pointh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom quatd state:a_quatd_4 = (4.5, 1.5, 2.5, 3.5) custom quatd[] state:a_quatd_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom quatf state:a_quatf_4 = (4.5, 1.5, 2.5, 3.5) custom quatf[] state:a_quatf_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom quath state:a_quath_4 = (4.5, 1.5, 2.5, 3.5) custom quath[] state:a_quath_4_array = [(4.5, 1.5, 2.5, 3.5), (14.5, 11.5, 12.5, 13.5)] custom string state:a_string = "Snoke" custom string state:a_stringEmpty custom texCoord2d state:a_texcoordd_2 = (1.5, 2.5) custom texCoord2d[] state:a_texcoordd_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3d state:a_texcoordd_3 = (1.5, 2.5, 3.5) custom texCoord3d[] state:a_texcoordd_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom texCoord2f state:a_texcoordf_2 = (1.5, 2.5) custom texCoord2f[] state:a_texcoordf_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3f state:a_texcoordf_3 = (1.5, 2.5, 3.5) custom texCoord3f[] state:a_texcoordf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom texCoord2h state:a_texcoordh_2 = (1.5, 2.5) custom texCoord2h[] state:a_texcoordh_2_array = [(1.5, 2.5), (11.5, 12.5)] custom texCoord3h state:a_texcoordh_3 = (1.5, 2.5, 3.5) custom texCoord3h[] state:a_texcoordh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom timecode state:a_timecode = 2.5 custom timecode[] state:a_timecode_array = [2.5, 3.5] custom token state:a_token = "Jedi" custom token[] state:a_token_array = ["Luke", "Skywalker"] custom uchar state:a_uchar = 2 custom uchar[] state:a_uchar_array = [2, 3] custom uint state:a_uint = 2 custom uint64 state:a_uint64 = 2 custom uint64[] state:a_uint64_array = [2, 3] custom uint[] state:a_uint_array = [2, 3] custom vector3d state:a_vectord_3 = (1.5, 2.5, 3.5) custom vector3d[] state:a_vectord_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom vector3f state:a_vectorf_3 = (1.5, 2.5, 3.5) custom vector3f[] state:a_vectorf_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] custom vector3h state:a_vectorh_3 = (1.5, 2.5, 3.5) custom vector3h[] state:a_vectorh_3_array = [(1.5, 2.5, 3.5), (11.5, 12.5, 13.5)] def Output "outputs_a_bundle" { } def Output "state_a_bundle" { } } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestRootGraphWithSettings.usda
#usda 1.0 ( ) def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 1) }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestTranslatingCube.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (0, 0, 0) } dictionary Right = { double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 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 Cube "Cube" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double size = 100 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"] } def OmniGraph "moveX" { token evaluator:type = "push" int2 fileFormatVersion = (1, 6) def OmniGraphNode "read_prim_attribute" { custom token inputs:name = "xformOp:translate" custom rel inputs:prim prepend rel inputs:prim = </World/Cube> custom token inputs:primPath = "" custom timecode inputs:usdTimecode = -1 custom bool inputs:usePath = 0 custom token node:type = "omni.graph.nodes.ReadPrimAttribute" custom int node:typeVersion = 1 custom token outputs:value custom uint64 state:target = 0 custom timecode state:usdTimecode = -1 } def OmniGraphNode "decompose" { custom double3 inputs:double3 = (0, 0, 0) prepend double3 inputs:double3.connect = </World/moveX/read_prim_attribute.outputs:value> custom token node:type = "omni.graph.test.DecomposeDouble3C" custom int node:typeVersion = 1 custom double outputs:x = 0 custom double outputs:y = 0 custom double outputs:z = 0 } def OmniGraphNode "subtract" { custom double inputs:a = 0 prepend double inputs:a.connect = </World/moveX/decompose.outputs:x> custom double inputs:b = 1 custom token node:type = "omni.graph.test.SubtractDoubleC" custom int node:typeVersion = 1 custom double outputs:out = 0 } def OmniGraphNode "compose" { custom double inputs:x = 0 prepend double inputs:x.connect = </World/moveX/subtract.outputs:out> custom double inputs:y = 0 prepend double inputs:y.connect = </World/moveX/decompose.outputs:y> custom double inputs:z = 0 prepend double inputs:z.connect = </World/moveX/decompose.outputs:z> custom token node:type = "omni.graph.test.ComposeDouble3C" custom int node:typeVersion = 1 custom double3 outputs:double3 = (0, 0, 0) } def OmniGraphNode "write_prim_attribute" { custom uint inputs:execIn = 0 custom token inputs:name = "xformOp:translate" custom rel inputs:prim prepend rel inputs:prim = </World/Cube> custom token inputs:primPath = "" custom bool inputs:usePath = 0 custom token inputs:value = "" prepend token inputs:value.connect = </World/moveX/compose.outputs:double3> custom token node:type = "omni.graph.nodes.WritePrimAttribute" custom int node:typeVersion = 1 custom uint outputs:execOut = 0 ( customData = { bool isExecution = 1 } ) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestSimCycleDependenciesTruePull.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 = { } } dictionary renderSettings = { float3 "rtx:iray:environment_dome_rotation_axis" = (0, 1, 0) } } 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 OmniGraph "PullGraph" { token evaluationMode = "Automatic" token evaluator:type = "pull" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "int_counter" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:increment = 1 prepend int inputs:increment.connect = </World/PullGraph/simple.outputs:a_int> custom bool inputs:reset = 0 token node:type = "omni.graph.examples.python.IntCounter" int node:typeVersion = 1 custom int outputs:count = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (231.5967, -109.70174) } def OmniGraphNode "int_counter_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom int inputs:increment = 1 prepend int inputs:increment.connect = </World/PullGraph/simple_01.outputs:a_int> custom bool inputs:reset = 0 token node:type = "omni.graph.examples.python.IntCounter" int node:typeVersion = 1 custom int outputs:count = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (698.32605, 178.53966) } def OmniGraphNode "simple" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:a_bool = 1 custom int inputs:a_constant_input = 0 custom double inputs:a_double = 0 prepend double inputs:a_double.connect = </World/PullGraph/read_time.outputs:deltaSeconds> custom float inputs:a_float = 0 custom half inputs:a_half = 0 custom int inputs:a_int = 0 custom int64 inputs:a_int64 = 0 custom uint64 inputs:a_objectId = 0 custom string inputs:a_path = "" custom string inputs:a_string = "helloString" custom token inputs:a_token = "helloToken" custom uchar inputs:unsigned:a_uchar = 0 custom uint inputs:unsigned:a_uint = 0 custom uint64 inputs:unsigned:a_uint64 = 0 token node:type = "omni.graph.tutorials.SimpleData" int node:typeVersion = 1 custom bool outputs:a_bool = 0 custom double outputs:a_double = 1 custom float outputs:a_float = 1 custom half outputs:a_half = 1 custom int outputs:a_int = 1 custom int64 outputs:a_int64 = 1 custom uint64 outputs:a_objectId = 1 custom string outputs:a_path = "/Child" custom string outputs:a_string = "worldString" custom token outputs:a_token = "worldToken" custom uchar outputs:unsigned:a_uchar = 1 custom uint outputs:unsigned:a_uint = 1 custom uint64 outputs:unsigned:a_uint64 = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-201.87401, -107.48449) } def OmniGraphNode "simple_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom bool inputs:a_bool = 1 custom int inputs:a_constant_input = 0 custom double inputs:a_double = 0 prepend double inputs:a_double.connect = </World/PullGraph/read_time_01.outputs:frame> custom float inputs:a_float = 0 custom half inputs:a_half = 0 custom int inputs:a_int = 0 custom int64 inputs:a_int64 = 0 custom uint64 inputs:a_objectId = 0 custom string inputs:a_path = "" custom string inputs:a_string = "helloString" custom token inputs:a_token = "helloToken" custom uchar inputs:unsigned:a_uchar = 0 custom uint inputs:unsigned:a_uint = 0 custom uint64 inputs:unsigned:a_uint64 = 0 token node:type = "omni.graph.tutorials.SimpleData" int node:typeVersion = 1 custom bool outputs:a_bool = 0 custom double outputs:a_double = 1 custom float outputs:a_float = 1 custom half outputs:a_half = 1 custom int outputs:a_int = 1 custom int64 outputs:a_int64 = 1 custom uint64 outputs:a_objectId = 1 custom string outputs:a_path = "/Child" custom string outputs:a_string = "worldString" custom token outputs:a_token = "worldToken" custom uchar outputs:unsigned:a_uchar = 1 custom uint outputs:unsigned:a_uint = 1 custom uint64 outputs:unsigned:a_uint64 = 1 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (236.03117, 23.332802) } def OmniGraphNode "read_time" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { token node:type = "omni.graph.nodes.ReadTime" int node:typeVersion = 1 custom double outputs:absoluteSimTime = 0 custom double outputs:deltaSeconds = 0 custom double outputs:frame = 0 custom bool outputs:isPlaying = 0 custom double outputs:time = 0 custom double outputs:timeSinceStart = 0 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-540.37634, -5.429764) } def OmniGraphNode "read_time_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { token node:type = "omni.graph.nodes.ReadTime" int node:typeVersion = 1 custom double outputs:absoluteSimTime = 0 custom double outputs:deltaSeconds = 0 custom double outputs:frame = 0 custom bool outputs:isPlaying = 0 custom double outputs:time = 0 custom double outputs:timeSinceStart = 0 uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-532.043, 301.23694) } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestGlobalGraphs.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (346.1130520546777, 730.8688792040283, 770.334523552793) double3 target = (116.6470760745791, -187.64754949669907, 99.09300175087196) } dictionary Right = { double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } int refinementOverrideImplVersion = 0 dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 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 float3 xformOp:rotateXYZ = (315, 0, 0) double3 xformOp:scale = (1, 1, 1) float3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Cylinder "Cylinder" { uniform token axis = "Y" float3[] extent = [(-50, -50, -50), (50, 50, 50)] double height = 100 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 = (-14.145638, 0, 89.546369) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def GlobalComputeGraph "globalGraph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" } def ComputeNode "DecomposeDouble3_b" { custom double3 inputs:double3 prepend double3 inputs:double3.connect = </World/Cylinder.xformOp:translate> custom token node:type = "omni.graph.examples.python.DecomposeDouble3" custom int node:typeVersion = 1 custom double outputs:x = 0 custom double outputs:y = 0 custom double outputs:z = 0 } def ComputeNode "SubtractDouble_b" { custom double inputs:a prepend double inputs:a.connect = </World/globalGraph/DecomposeDouble3_b.outputs:x> custom double inputs:b = 100 custom token node:type = "omni.graph.examples.python.SubtractDouble" custom int node:typeVersion = 1 custom double outputs:out = -1 } def ComputeNode "ComposeDouble3_b" { custom double inputs:x prepend double inputs:x.connect = </World/globalGraph/SubtractDouble_b.outputs:out> custom double inputs:y prepend double inputs:y.connect = </World/globalGraph/DecomposeDouble3_b.outputs:y> custom double inputs:z prepend double inputs:z.connect = </World/globalGraph/DecomposeDouble3_b.outputs:z> custom token node:type = "omni.graph.examples.python.ComposeDouble3" custom int node:typeVersion = 1 custom double3 outputs:double3 = (-1, 0, 0) } } def Capsule "Capsule" { uniform token axis = "Y" float3[] extent = [(-25, -25, -50), (25, 25, 50)] double height = 50 double radius = 25 custom bool refinementEnableOverride = 1 custom int refinementLevel = 2 double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (-109.380064, 0, 103.602351) prepend double3 xformOp:translate.connect = </World/globalGraph/ComposeDouble3_b.outputs:double3> uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Cube "Cube" { float3[] extent = [(-50, -50, -50), (50, 50, 50)] double size = 100 double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (-29.222733, 0, -51.330466) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" } def ComputeNode "DecomposeDouble3" { custom double3 inputs:double3 prepend double3 inputs:double3.connect = </World/Cube.xformOp:translate> custom token node:type = "omni.graph.examples.python.DecomposeDouble3" custom int node:typeVersion = 1 custom double outputs:x = 0 custom double outputs:y = 0 custom double outputs:z = 0 } def ComputeNode "SubtractDouble" { custom double inputs:a prepend double inputs:a.connect = </World/DecomposeDouble3.outputs:x> custom double inputs:b = 100 custom token node:type = "omni.graph.examples.python.SubtractDouble" custom int node:typeVersion = 1 custom double outputs:out = -1 } def ComputeNode "ComposeDouble3" { custom double inputs:x prepend double inputs:x.connect = </World/SubtractDouble.outputs:out> custom double inputs:y prepend double inputs:y.connect = </World/DecomposeDouble3.outputs:y> custom double inputs:z prepend double inputs:z.connect = </World/DecomposeDouble3.outputs:z> custom token node:type = "omni.graph.examples.python.ComposeDouble3" custom int node:typeVersion = 1 custom double3 outputs:double3 = (-1, 0, 0) } 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 = (-129.222733, 0, -51.330466) prepend double3 xformOp:translate.connect = </World/ComposeDouble3.outputs:double3> uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestGlobalGraphMultiplePipelineStages.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 = { } } dictionary renderSettings = { } } metersPerUnit = 0.01 timeCodesPerSecond = 24 upAxis = "Y" ) def "World" { def GlobalComputeGraph "my_simulation_push_graph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 1) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStageSimulation" } def ComputeNode "subtractSize" { custom double inputs:a = 0 prepend double inputs:a.connect = </cube1.size> custom double inputs:b = -1 custom int inputs:test_create1 custom int3 inputs:test_create2 custom int3[] inputs:test_create3 custom uint inputs:test_create4 custom token node:type = "omni.graph.test.SubtractDoubleC" custom int node:typeVersion = 1 custom double outputs:out = 118.7000000000794 } } # note this graph here is just a duplicated version of the above push graph, changed slightly to # be in a different pipeline stage. It's setup this way just to test the parsing of the graphs. # It's not meant to be ticked. Please change the graph appropriately if ever that aspect is to # be tested def GlobalComputeGraph "my_postrender_push_graph" { def ComputeGraphSettings "computegraphSettings" { custom token evaluator:type = "push" custom int2 fileFormatVersion = (1, 1) custom token flatCacheBacking = "Shared" custom token pipelineStage = "pipelineStagePostRender" } def ComputeNode "subtractSize" { custom double inputs:a = 0 prepend double inputs:a.connect = </cube1.size> custom double inputs:b = -1 custom int inputs:test_create1 custom int3 inputs:test_create2 custom int3[] inputs:test_create3 custom uint inputs:test_create4 custom token node:type = "omni.graph.test.SubtractDoubleC" custom int node:typeVersion = 1 custom double outputs:out = 118.7000000000794 } } } def Cube "cube1" { color3f[] primvars:displayColor = [(1, 0, 1)] double size = 118.7000000000794 prepend double size.connect = </World/my_simulation_push_graph/subtractSize.outputs:out> }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestCompoundGraph.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.0000039780381939635845, 0.000007956076956361358, -0.000003978038478180679) } 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 = { } } } 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 OmniGraph "ActionGraph" { token evaluationMode = "Automatic" token evaluator:type = "execution" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "compound" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:A custom token inputs:a custom token inputs:B custom token inputs:b token node:type = "/World/Compounds/Compound" int node:typeVersion = 1 custom token outputs:sum custom token outputs:Value uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (361, 83) def OmniGraph "ActionGraph_01" ( references = </World/Compounds/Compound/Graph> ) { token evaluationMode = "Instanced" token evaluator:type = "execution" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" } } } def Scope "Compounds" { def OmniGraphCompoundNodeType "Compound" { prepend rel omni:graph:asset = </World/Compounds/Compound/Graph> custom rel omni:graph:input:A prepend rel omni:graph:input:A = </World/Compounds/Compound/Graph/Add_Node.inputs:a> custom rel omni:graph:input:B prepend rel omni:graph:input:B = </World/Compounds/Compound/Graph/Add_Node.inputs:b> custom rel omni:graph:output:Value prepend rel omni:graph:output:Value = </World/Compounds/Compound/Graph/Add_Node.outputs:sum> def OmniGraph "Graph" ( instanceable = false ) { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 4) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Add_Node" { custom token inputs:a custom token inputs:b token node:type = "omni.graph.nodes.Add" int node:typeVersion = 1 custom token outputs:sum } } } } }
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/data/TestBundleToTargetConnection.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.00000397803842133726, 0.000007956076785831101, -0.000003978038307650422) } 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:fog:fogColor" = (0.75, 0.75, 0.75) float3 "rtx:index:regionOfInterestMax" = (0, 0, 0) float3 "rtx:index:regionOfInterestMin" = (0, 0, 0) 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" = (3.4028235e38, 3.4028235e38, 3.4028235e38) 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 = 30 upAxis = "Y" ) def Xform "World" { def OmniGraph "PushGraph" { token evaluationMode = "Automatic" token evaluator:type = "push" token fabricCacheBacking = "Shared" int2 fileFormatVersion = (1, 7) token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "test_node_bundle_to_target_connection" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom rel inputs:bundle custom rel inputs:target ( customData = { dictionary omni = { dictionary graph = { string relType = "target" } } } ) token node:type = "omni.graph.test.BundleToTarget" int node:typeVersion = 1 custom rel outputs:target ( customData = { dictionary omni = { dictionary graph = { string relType = "target" } } } ) uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (-59, 72) def Output "outputs_bundle" { } } def OmniGraphNode "test_node_bundle_to_target_connection_01" ( prepend apiSchemas = ["NodeGraphNodeAPI"] ) { custom rel inputs:bundle custom rel inputs:target ( customData = { dictionary omni = { dictionary graph = { string relType = "target" } } } ) prepend rel inputs:target = </World/PushGraph/test_node_bundle_to_target_connection/outputs_bundle> token node:type = "omni.graph.test.BundleToTarget" int node:typeVersion = 1 custom rel outputs:target ( customData = { dictionary omni = { dictionary graph = { string relType = "target" } } } ) uniform token ui:nodegraph:node:expansionState = "open" uniform float2 ui:nodegraph:node:pos = (331, 79) def Output "outputs_bundle" { } } } } def Xform "Environment" { 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"] def DistantLight "defaultLight" ( prepend apiSchemas = ["ShapingAPI"] ) { float inputs:angle = 1 float inputs:intensity = 3000 float inputs:shaping:cone:angle = 180 float inputs:shaping:cone:softness float inputs:shaping:focus color3f inputs:shaping:focusTint asset inputs: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"] } }
omniverse-code/kit/exts/omni.graph.test/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). ## [Unreleased] ## [0.18.0] - 2022-11-15 ### Added - Additional test to exercise simple dynamic attribute values ## [0.17.0] - 2022-11-09 ### Added - Test node and script for verifying location of dynamic attribute memory ## [0.16.1] - 2022-10-18 ### Added - Test against crashing when new UsdContext is created. ## [0.16.0] - 2022-09-28 ### Added - Test for argument flattening utility ### Fixed - Obsolete branding - Obsolete test configurations ## [0.15.1] - 2022-09-27 ### Fixed - Lint errors that crept in ## [0.15.0] - 2022-09-06 ### Removed - Tests and dependencies related to UI and RTX ### Changed - Test node type that used the omni.graph.ui extension to one that does not ## [0.14.1] - 2022-08-31 ### Fixed - Refactored out use of a deprecated class ## [0.14.0] - 2022-08-30 ### Added - Test for reading nodes with all data types, and sample test files with such nodes ### Fixed - Linting errors ## [0.13.9] - 2022-08-17 ### Changed - Restored the fixed failing test to the test suite ## [0.13.8] - 2022-08-16 ### Removed - References to obsolete ABI methods ## [0.13.7] - 2022-08-09 ### Fixed - Applied formatting to all of the Python files ## [0.13.6] - 2022-08-03 ### Fixed - Compilation errors related to deprecation of methods in ogn bundle. ## [0.13.5] - 2022-07-27 ### Fixed - All of the lint errors reported on the Python files in this extension ## [0.13.4] - 2022-07-21 ### Changed - Undo revert ## [0.13.3] - 2022-07-18 ### Changed - Reverted the changes in 0.13.2 ## [0.13.2] - 2022-07-15 ### Changed - Removed LatentTest node, modified tests ## [0.13.1] - 2022-07-11 ### Fixed - OgnComputeErrorPy node was importing the _internal class directly, which some of our linux build systems do not like. ## [0.13.0] - 2022-07-08 ### Added - Test of attribute deprecation API. ## [0.12.0] - 2022-07-07 ### Changed - Refactored imports from omni.graph.tools to get the new locations ### Added - Test for public API consistency ## [0.11.0] - 2022-06-28 ### Added - Test to verify that CHANGELOG and extension.toml versions match ## [0.10.0] - 2022-06-17 ### Added - Tests for changing graph settings from USD ## [0.9.0] - 2022-06-13 ### Added - Tests for evaluation mode setting ### Changed - Evaluation mode added to settings tests ## [0.8.0] - 2022-06-13 ### Added - New test to verify that C++ and Python node duplication propagate attribute values ## [0.7.0] - 2022-06-08 ### Added - Added gpuinterop vertex deformation test ## [0.6.0] - 2022-06-07 ### Added - Test for CPU-GPU pointer access in the controller interface ## [0.5.1] - 2022-06-06 ### Fixed - Fixed extension dependencies and restored flaky test ## [0.5.0] - 2022-05-27 ### Added - Added a new test for accessing multiple schema-based graphs in a single scene ## [0.4.1] - 2022-05-26 ### Changed - Re-enabled test_graphs_in_sublayer_load, test_variable_commands and test_variables_create_remove_stress_test ## [0.4.0] - 2022-04-29 ### Removed - Removed obsolete tests and test files ### Changed - Made tests derive from OmniGraphTestCase and use the new og.Settings ## [0.3.0] - 2022-04-25 ### Changed - Stopped generating the pointless USD and docs for the test nodes ### Fixed - Fixed reference to extension.toml in the docs to point to the correct line and use an explicit language ## [0.2.4] - 2022-04-20 ### Added - Test for undoing prim deletions. ## [0.2.3] - 2022-04-11 ### Added - Test for connection callbacks ### Changed - Consolidated various callback tests into test_callbacks.py ## [0.2.2] - 2022-03-16 ### Changed - Previously disabled tests have been re-enabled with new _enabledLegacyPrimConnections_ setting. ## [0.2.1] - 2022-03-08 ### Changed - Modified registration test to match the new style used as of *omni.graph.core 2.23.3* ## [0.2.0] - 2022-03-01 ### Changed - Moved *expected_errors.py* to omni.graph so that it can be more generally accessible ## [0.1.0] - 2021-03-01 ### Changed - Renamed from omni.graph.tests to avoid conflict with automatic test detection
omniverse-code/kit/exts/omni.graph.test/docs/README.md
# OmniGraph Integration Testing [omni.graph.test] This extension contains support for tests that span multiple OmniGraph extensions. ## Published Documentation The automatically-published user guide from this repo can be viewed :ref:`here<index.rst>`
omniverse-code/kit/exts/omni.graph.test/docs/index.rst
.. _omni.graph.test: OmniGraph Integration Testing ############################# .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension**: omni.graph.test,**Documentation Generated**: |today| In order to effectively test the OmniGraph access to nodes and scripts that are not necessary for the graph to operate correctly. In order to minimize the unnecessary files, yet still have nodes and files explicitly for testing, all of that functionality has been broken out into this extension. Dependencies ============ As the purpose of this extension is to provide testing facilities for all of OmniGraph it will have load dependencies on all of the `omni.graph.*` extensions. If any new ones are added they should be added to the dependencies in the file ``config/extension.toml``. Data Files ========== Three types of data files are accessed in this extension: 1. Generic data files, created in other extensions for use by the user (e.g. compound node definitions) 2. Example files, created to illustrate how to use certain nodes but not intended for general use 3. Test files, used only for the purpose of loading to test certain features The ``data/`` subdirectories in this extension contains the latter of those three. The other files live in the lowest level extension in which they are legal (e.g. if they contain a node from `omni.graph.nodes` then they will live in that extension). As this extension has dependencies on all of the OmniGraph extensions it will have access to all of their data files as well. Node Files ========== Most nodes will come from other extensions. Some nodes are created explicitly for testing purposes. These will appear in this extension and should not be used for any other purpose. Import Example -------------- This simple example shows how the test files from the `omni.graph.examples.python` extension were imported and enabled in this extension. The first step was to move the required files into the directory tree: .. code-block:: text omni.graph.test/ β”œβ”€β”€ python/ └── tests/ β”œβ”€β”€β”€β”€ test_omnigraph_simple.py └── data/ β”œβ”€β”€β”€β”€ TestEventTrigger.usda └──── TestExecutionConnections.usda .. note:: The two .usda files contain only nodes from the `omni.graph.examples.python` extension and are solely used for test purposes. That is why they could be moved into the extension's test directory. Next the standard automatic test detection file was added to ``omni.graph.test/python/tests/__init__.py`` .. literalinclude:: ../python/tests/__init__.py :linenos: :language: python Finally, the `config/extension.toml` had additions made to inform it of the dependency on the new extension: .. literalinclude:: ../config/extension.toml :language: toml :linenos: :emphasize-lines: 34 .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.graph.test/docs/Overview.md
# OmniGraph Integration Testing ```{csv-table} **Extension**: omni.graph.test,**Documentation Generated**: {sub-ref}`today` ``` In order to effectively test the OmniGraph access to nodes and scripts that are not necessary for the graph to operate correctly. In order to minimize the unnecessary files, yet still have nodes and files explicitly for testing, all of that functionality has been broken out into this extension. ## Dependencies As the purpose of this extension is to provide testing facilities for all of OmniGraph it will have load dependencies on all of the `omni.graph.*` extensions. If any new ones are added they should be added to the dependencies in the file ``config/extension.toml``. ## Data Files Three types of data files are accessed in this extension: 1. Generic data files, created in other extensions for use by the user (e.g. compound node definitions) 2. Example files, created to illustrate how to use certain nodes but not intended for general use 3. Test files, used only for the purpose of loading to test certain features The ``data/`` subdirectories in this extension contains the latter of those three. The other files live in the lowest level extension in which they are legal (e.g. if they contain a node from `omni.graph.nodes` then they will live in that extension). As this extension has dependencies on all of the OmniGraph extensions it will have access to all of their data files as well. ## Node Files Most nodes will come from other extensions. Some nodes are created explicitly for testing purposes. These will appear in this extension and should not be used for any other purpose. ### Import Example This simple example shows how the test files from the `omni.graph.examples.python` extension were imported and enabled in this extension. The first step was to move the required files into the directory tree: ```text omni.graph.test/ β”œβ”€β”€ python/ └── tests/ β”œβ”€β”€β”€β”€ test_omnigraph_simple.py └── data/ β”œβ”€β”€β”€β”€ TestEventTrigger.usda └──── TestExecutionConnections.usda ``` ```{note} The two .usda files contain only nodes from the `omni.graph.examples.python` extension and are solely used for test purposes. That is why they could be moved into the extension's test directory. ``` Next the standard automatic test detection file was added to ``omni.graph.test/python/tests/__init__.py`` ```{literalinclude} ../../../../source/extensions/omni.graph.test/python/tests/__init__.py --- linenos: language: python --- ``` Finally, the `config/extension.toml` had additions made to inform it of the dependency on the new extension: ```{literalinclude} ../../../../source/extensions/omni.graph.test/config/extension.toml --- language: toml linenos: emphasize-lines: 34 --- ```
omniverse-code/kit/exts/omni.kit.renderer.core/omni/kit/renderer_test/__init__.py
from ._renderer_test import * # Cached interface instance pointer def get_renderer_test_interface() -> IRendererTest: if not hasattr(get_renderer_test_interface, "renderer_test"): get_renderer_test_interface.renderer_test = acquire_renderer_test_interface() return get_renderer_test_interface.renderer_test
omniverse-code/kit/exts/omni.kit.widget.path_field/PACKAGE-LICENSES/omni.kit.widget.path_field-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.widget.path_field/config/extension.toml
[package] title = "Kit Path Field Widget v2.0.4" version = "2.0.4" category = "Internal" description = "String field widget with tooltips for branching" authors = ["NVIDIA"] slackids = ["UQY4RMR3N"] repository = "" keywords = ["kit", "ui"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} [[python.module]] name = "omni.kit.widget.path_field" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ]
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/style.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui UI_STYLES = {} UI_STYLES["NvidiaLight"] = { "ScrollingFrame": {"background_color": 0xFF535354, "margin": 0, "padding": 0}, "Rectangle": {"background_color": 0xFF535354}, "InputField": {"background_color": 0xFF535354, "color": 0xFFD6D6D6, "padding": 0}, "BreadCrumb": {"background_color": 0x0, "padding": 0}, "BreadCrumb.Label": {"color": 0xFFD6D6D6}, "BreadCrumb:hovered": {"background_color": 0xFFCFCCBF}, "BreadCrumb.Label:hovered": {"color": 0xFF2A2825}, "BreadCrumb:selected": {"background_color": 0xFF535354}, "Tooltips.Menu": {"background_color": 0xFFE0E0E0, "border_color": 0xFFE0E0E0, "border_width": 0.5}, "Tooltips.Item": {"background_color": 0xFF535354, "padding": 4}, "Tooltips.Item:hovered": {"background_color": 0xFF6E6E6E}, "Tooltips.Item:checked": {"background_color": 0xFF6E6E6E}, "Tooltips.Item.Label": {"color": 0xFFD6D6D6, "alignment": ui.Alignment.LEFT}, "Tooltips.Spacer": {"background_color": 0x0, "color": 0x0, "alignment": ui.Alignment.LEFT, "padding": 0}, } UI_STYLES["NvidiaDark"] = { "ScrollingFrame": {"background_color": 0xFF23211F, "margin": 0, "padding": 0}, "InputField": {"background_color": 0x0, "color": 0xFF9E9E9E, "padding": 0, "margin": 0}, "BreadCrumb": {"background_color": 0x0, "padding": 0}, "BreadCrumb:hovered": {"background_color": 0xFF8A8777}, "BreadCrumb:selected": {"background_color": 0xFF8A8777}, "BreadCrumb.Label": {"color": 0xFF9E9E9E}, "BreadCrumb.Label:hovered": {"color": 0xFF2A2825}, "Tooltips.Menu": {"background_color": 0xDD23211F, "border_color": 0xAA8A8777, "border_width": 0.5}, "Tooltips.Item": {"background_color": 0x0, "padding": 4}, "Tooltips.Item:hovered": {"background_color": 0xFF8A8777}, "Tooltips.Item:checked": {"background_color": 0xFF8A8777}, "Tooltips.Item.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT}, "Tooltips.Item.Label:hovered": {"color": 0xFF2A2825}, "Tooltips.Item.Label:checked": {"color": 0xFF2A2825}, "Tooltips.Spacer": { "background_color": 0x0, "color": 0x0, "alignment": ui.Alignment.LEFT, "padding": 0, "margin": 0, }, }
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/__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. # """ A UI alternative to omni.ui.StringField for navigating tree views with the keyboard. As the user navigates the tree using TAB, Backspace, and Arrow keys, they are constantly provided branching options via auto-filtered tooltips. Example: .. code-block:: python path_field = PathField( apply_path_handler=self._apply_path_handler, branching_options_provider=self._branching_options_provider, ) """ from .widget import PathField
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/model.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import omni.kit.app import omni.ui as ui from typing import List from .style import UI_STYLES from carb.input import KeyboardInput as Key from functools import partial class DelayedFocus: """A helper to run focus_keyboard the next frame""" def __init__(self, field: ui.StringField): self.__task = None self.__field = field def destroy(self): if self.__task and not self.__task.done(): self.__task.cancel() self.__task = None self.__field = None def focus_keyboard(self): """Execute frame.focus_keyboard in the next frame""" # Update in the next frame. if self.__task is None or self.__task.done(): self.__task = asyncio.ensure_future(self.__delayed_do()) async def __delayed_do(self): # Wait one frame await omni.kit.app.get_app().next_update_async() self.__field.focus_keyboard() class PathFieldModel(ui.AbstractValueModel): def __init__(self, parent: ui.Widget, theme: str, **kwargs): super().__init__() self._parent = parent self._window = None self._field = None self._tooltips_frame = None self._tooltips = None self._tooltip_items = [] self._num_tooltips = 0 self._path = None # Always ends with separator character! self._branches = [] self._focus = None self._style = UI_STYLES[theme] self._apply_path_handler = kwargs.get("apply_path_handler", None) self._apply_path_on_branch_changed = False self._current_path_provider = kwargs.get("current_path_provider", None) self._branching_options_provider = kwargs.get("branching_options_provider", None) # OBSOLETE self._branching_options_handler = kwargs.get("branching_options_handler", None) self._tooltips_max_visible = kwargs.get("tooltips_max_visible", 10) self._separator = kwargs.get("separator", "/") self._is_paste = False def set_value(self, value: str): print("Warning: Method 'set_value' is provided for compatibility only and should not be used.") def get_value_as_string(self) -> str: # Return empty string to parent widget return "" def set_path(self, path: str): self._path = path def set_branches(self, branches: [str]): if branches: self._branches = branches else: self._branches = [] def begin_edit(self): if not (self._window and self._window.visible): self._build_ui() # Reset path in case we inadvertently deleted it if self._current_path_provider: input_str = self._current_path_provider() else: input_str = "" self._field.model.set_value(input_str) def _build_ui(self): # Create and show the window with field and list of tips window_args = { "flags": ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_BACKGROUND | ui.WINDOW_FLAGS_NO_MOVE, "auto_resize": True, "padding_x": 0, "padding_y": 0, "spacing": 0, } self._window = ui.Window("0", **window_args) with self._window.frame: width = self._parent.computed_content_width with ui.VStack(height=0, style=self._style): with ui.ZStack(): ui.Rectangle() # Use scrolling frame to confine width in case of long inputs with ui.ScrollingFrame( width=width, height=20, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"background_color": 0x0}, ): with ui.HStack(spacing=0): ui.Spacer(width=3) input = ui.SimpleStringModel() input.add_value_changed_fn(lambda m: self._update_tooltips()) with ui.Placer(stable_size=True, offset_x=6, offset_y=3): self._field = ui.StringField(input, style_type_name_override="InputField") # TODO: It's a workaround. We need to find out # why we need delayed focus here and why # self._field.focus_keyboard doesn't work. self._focus = DelayedFocus(self._field) self._focus.focus_keyboard() # Reserve for tooltips self._tooltips_frame = ui.Frame() # Process pre-defined set of key presses self._window.set_key_pressed_fn(self._on_key_pressed) self._place_window() def _on_key_pressed(self, key: int, key_mod: int, key_down: bool): """ Process keys on release. """ key = Key(key) # Convert to enumerated type if key_down: if key == Key.V and key_mod == 2: # We need it to avoid the connection to the server if the # string is pasted self._is_paste = True return if self._is_paste: self._is_paste = False do_apply_path = False if key == Key.ESCAPE: do_apply_path = True self._hide_window() elif key in [Key.TAB, Key.RIGHT, Key.ENTER]: if self._tooltips and self._tooltip_items: index = self._tooltips.model.get_value_as_int() self._extend_path_by_selected_branch(index) if key == Key.ENTER: do_apply_path = True self._hide_window() elif self._apply_path_on_branch_changed: do_apply_path = True elif key == Key.LEFT: self._shrink_path_by_tail_branch() if self._apply_path_on_branch_changed: do_appy_path = True elif key == Key.DOWN: if self._tooltips and self._num_tooltips > 0: value = self._tooltips.model.get_value_as_int() self._tooltips.model.set_value((value + 1) % self._num_tooltips) elif key == Key.UP: if self._tooltips and self._num_tooltips > 0: value = self._tooltips.model.get_value_as_int() self._tooltips.model.set_value(value - 1 if value >= 1 else self._num_tooltips - 1) else: # Skip all other keys pass if do_apply_path and self._apply_path_handler: try: self._apply_path_handler(self._field.model.get_value_as_string()) except Exception: pass def _update_tooltips(self): """Generates list of tips""" if not self._field: return cur_path = self._path or "" input_str = self._field.model.get_value_as_string() # TODO: This is a hack to avoid the connection to the server if the # string is pasted. When we paste full path, we don't want to wait for # the server connection. if self._is_paste: self.set_path(input_str) return splits = input_str.rsplit(self._separator, 1) match_str = splits[1] if len(splits) > 1 else splits[0] # Alternatively: match_str = input_str.replace(cur_path, "").lower().rstrip(self._separator) if not input_str.startswith(cur_path) or self._separator in input_str[len(cur_path) :]: # Off the current path, need to update both path and branches before continuing. if self._branching_options_handler: new_path = splits[0] new_path += self._separator if new_path else "" self.set_path(new_path) return self._branching_options_handler(new_path, partial(self._update_tooltips_menu, match_str, True)) else: self._update_tooltips_menu(match_str, False, None) def _update_tooltips_menu(self, match_str: str, update_branches: bool, branches: List[str]): if update_branches: self.set_branches(branches) self._num_tooltips = 0 self._tooltip_items.clear() with self._tooltips_frame: with ui.HStack(): with ui.HStack(mouse_pressed_fn=lambda x, y, b, _: self._hide_window()): ui.Spacer(width=6) ui.Label(self._path or "", width=0, style_type_name_override="Tooltips.Spacer") with ui.ZStack(): ui.Rectangle(style_type_name_override="Tooltips.Menu") with ui.VStack(): self._tooltips = ui.RadioCollection() self._tooltip_items.clear() # Pre-pend an empty branch to pick none for branch in [" "] + self._branches: if self._num_tooltips >= self._tooltips_max_visible: break if not match_str or (branch and branch.lower().startswith(match_str.lower())): item = ui.RadioButton( text=branch, height=20, radio_collection=self._tooltips, style_type_name_override="Tooltips.Item", ) item.set_clicked_fn(partial(self._extend_path_by_selected_branch, self._num_tooltips)) self._tooltip_items.append(item) self._num_tooltips += 1 self._tooltips.model.set_value(0) with ui.HStack(mouse_pressed_fn=lambda x, y, b, _: self._hide_window()): ui.Spacer(style_type_name_override="Tooltips.Spacer") self._place_window() def _extend_path_by_selected_branch(self, index: int): index = min(index, len(self._tooltip_items) - 1) if not self._tooltip_items[index].visible: return branch = self._tooltip_items[index].text.strip() if branch: # Skip empty strings, incl. one we introduced. Don't allow ending with 2 copies of separator. new_path = self._path + (branch + self._separator if not branch.endswith(self._separator) else branch) else: new_path = self._path if self._field: self._field.model.set_value(new_path) def _shrink_path_by_tail_branch(self): input_str = self._field.model.get_value_as_string() splits = input_str.rstrip(self._separator).rsplit(self._separator, 1) if len(splits) > 1 and splits[1]: new_path = splits[0] + self._separator else: new_path = "" if self._field: self._field.model.set_value(new_path) def _place_window(self): if self._parent: self._window.position_x = self._parent.screen_position_x - 1 self._window.position_y = self._parent.screen_position_y + 1 def _hide_window(self): if self._window: self._window.visible = False def destroy(self): self._field = None self._tootip_items = None self._tooltips = None self._tooltips_frame = None self._parent = None self._window = None if self._focus: self._focus.destroy() self._focus = None
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/widget.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import platform import sys, os import omni.ui as ui from .model import PathFieldModel from .style import UI_STYLES class PathField: """ Main class for the PathField widget. This widget is a UI alternative to omni.ui.StringField for navigating tree views with the keyboard. As the user navigates the tree using TAB, Backspace, and Arrow keys, they are constantly provided branching options via auto-filtered tooltips. Args: None Keyword Args: apply_path_handler (Callable): This function is called when the user hits Enter on the input field, signaling that they want to apply the path. This handler is expected to update the caller's app accordingly. Function signature: void apply_path_handler(path: str) branching_options_handler (Callable): This function is required to provide a list of possible branches whenever prompted with a path. For example, if path = "C:", then the list of values produced might be ["Program Files", "temp", ..., "Users"]. Function signature: list(str) branching_options_provider(path: str, callback: func) separator (str): Character used to split a path into list of branches. Default '/'. """ def __init__(self, **kwargs): import carb.settings self._scrolling_frame = None self._input_frame = None self._path = None self._path_model = None self._breadcrumbs = [] self._theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" self._style = UI_STYLES[self._theme] self._apply_path_handler = kwargs.get("apply_path_handler", None) self._branching_options_handler = kwargs.get("branching_options_handler", None) self._branching_options_provider = kwargs.get("branching_options_provider", None) # OBSOLETE self._separator = kwargs.get("separator", "/") self._prefix_separator = kwargs.get("prefix_separator", None) self._build_ui() @property def path(self) -> str: """str: Returns the current path as entered in the field box.""" return self._path def _parse_path(self, full_path: str): if not full_path: return None, None prefix, path = "", full_path if self._prefix_separator: splits = full_path.split(self._prefix_separator, 1) if len(splits) == 2: prefix = f"{splits[0]}{self._prefix_separator}" path = splits[1] return prefix, path def set_path(self, full_path: str): """ Sets the path. Args: path (str): The full path name. """ if not full_path: return prefix, path = self._parse_path(full_path) # Make sure path string is properly formatted - it should end with # exactly 1 copy of the separator character. if path: path = f"{path.rstrip(self._separator)}{self._separator}" self._path = f"{prefix}{path}" self._update_breadcrumbs(self._path) def _build_ui(self): # Use a scrolling frame to prevent long paths from exploding width inut box self._scrolling_frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style=self._style, style_type_name_override="ScrollingFrame", ) with self._scrolling_frame: self._build_input_field() def _build_input_field(self): self._path_model = PathFieldModel( self._scrolling_frame, self._theme, show_max_suggestions=10, apply_path_handler=self._apply_path_handler, branching_options_handler=self._branching_options_handler, current_path_provider=lambda: self._path or "", ) with ui.ZStack(style=self._style): ui.Rectangle() with ui.HStack(height=20): ui.Spacer(width=3) self._input_frame = ui.Frame() field = ui.StringField(self._path_model, style_type_name_override="InputField", identifier="filepicker_directory_path") self._update_breadcrumbs(self._path) def _update_breadcrumbs(self, path: str): def on_breadcrumb_clicked(button: ui.RadioButton): if button and self._apply_path_handler: self._apply_path_handler(button.name) def create_breadcrumb(label: str, path: str): breadcrumb = ui.Button(text="", style_type_name_override="BreadCrumb") # HACK Alert: We're hijacking the name attr to store the fullpath. # Alternatively subclass from ui.Button and add a fullpath attr. breadcrumb.text = label breadcrumb.name = path breadcrumb.set_clicked_fn(lambda b=breadcrumb: on_breadcrumb_clicked(b)), separator = ui.Label(self._separator, style_type_name_override="BreadCrumb.Label") return (breadcrumb, separator) self._breadcrumbs.clear() prefix, path = self._parse_path(path) accum_path = "" with self._input_frame: with ui.HStack(width=0, spacing=0, style=self._style): ui.Spacer(width=5) if prefix: accum_path += prefix self._breadcrumbs.append(create_breadcrumb(accum_path, accum_path)) _, separator = self._breadcrumbs[-1] separator.visible = False if path: for token in path.rstrip(self._separator).split(self._separator): accum_path += token self._breadcrumbs.append(create_breadcrumb(token, accum_path)) accum_path += self._separator # For extremely long paths, scroll to the last breadcrumb if self._breadcrumbs: breadcrumb, _ = self._breadcrumbs[-1] breadcrumb.scroll_here_x(0) def destroy(self): """Destructor.""" self._path_model = None self._breadcrumbs = None self._input_frame = None self._scrolling_frame = None
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/tests/__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 .test_breadcrumbs import TestBreadCrumbs
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/tests/test_breadcrumbs.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from unittest.mock import Mock, patch from ..widget import PathField class TestBreadCrumbs(omni.kit.test.AsyncTestCase): """Testing PathField.set_path""" async def setUp(self): self.test_paths = { "omniverse://ov-test/NVIDIA/Samples": ["omniverse://", "ov-test", "NVIDIA", "Samples"], "my-computer://C:/Users/jack": ["my-computer://", "C:", "Users", "jack"], "my-computer:///home/jack": ["my-computer://", "", "home", "jack"], "C:/Users/jack": ["C:", "Users", "jack"], "/": [""], "/home/jack": ["", "home", "jack"], } async def tearDown(self): pass async def test_breadcrumbs_succeeds(self): """Testing PathField.set_path correctly initializes breacrumbs""" mock_path_handler = Mock() under_test = PathField(separator="/", prefix_separator="://", apply_path_handler=mock_path_handler) for path, expected in self.test_paths.items(): under_test.set_path(path) expected_path = "" for breadcrumb, _ in under_test._breadcrumbs: expected_step = expected.pop(0) expected_path += expected_step # Confirm when breadcrumb clicked, it triggers callback with expected path breadcrumb.call_clicked_fn() mock_path_handler.assert_called_with(expected_path) expected_path += "/" if not expected_step.endswith("://") else ""
omniverse-code/kit/exts/omni.kit.widget.path_field/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [2.0.4] - 2022-11-09 ### Changes - Fix to toml file ## [2.0.3] - 2021-06-16 ### Changes - Fixes double "//" at the end of the path string. ## [2.0.2] - 2021-04-23 ### Changes - Fix to breadcrumbs on Linux returning incorrect paths resulting in Connection Errors. ## [2.0.1] - 2021-02-10 ### Changes - Updated StyleUI handling ## [2.0.0] - 2020-01-03 ### Updated - Refactored for async directory listing to improve overall stability in case of network delays. ### Added - Keyword Arg: 'branching_options_handler' ### Deleted - Keyword Arg: 'branching_options_provider' ## [0.1.6] - 2020-11-20 ### Added - Don't Execute "apply path" on directory changes, only when user hits Esc or Enter key. ## [0.1.5] - 2020-11-20 ### Added - Fixes occasionally jumbled-up breadcrumbs. ## [0.1.4] - 2020-09-18 ### Added - Initial commit to master.
omniverse-code/kit/exts/omni.kit.widget.path_field/docs/index.rst
omni.kit.widget.path_field ########################## A UI alternative to omni.ui.StringField for smarter path traversal (think filesystem paths). .. toctree:: :maxdepth: 1 CHANGELOG .. automodule:: omni.kit.widget.path_field :platform: Windows-x86_64, Linux-x86_64 :members: :show-inheritance: :undoc-members: .. autoclass:: PathField :members:
omniverse-code/kit/exts/omni.kit.window.stageviewer/PACKAGE-LICENSES/omni.kit.window.stageviewer-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.window.stageviewer/config/extension.toml
[package] version = "1.0.5" category = "Internal" feature = true title = "Stage Viewer" description="Adds context menu in the Content Browser that allows to inspect stages." changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.widget.stage" = {} [[python.module]] name = "omni.kit.window.stageviewer" # Additional python module with tests, to make them discoverable by test system. [[python.module]] name = "omni.kit.window.stageviewer.tests" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", "omni.kit.window.content_browser", ] stdoutFailPatterns.exclude = [ "*Failed to acquire interface*while unloading all plugins*" ]
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/stageviewer_extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ext from .content_menu import content_available from .content_menu import ContentMenu class StageViewerExtension(omni.ext.IExt): def on_startup(self, ext_id): # Setup a callback when any extension is loaded/unloaded 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.window.stageviewer" ) self.__context_menu = None self._on_event(None) def _on_event(self, event): """Called when any extension is loaded/unloaded""" if self.__context_menu: if not content_available(): self.__context_menu.destroy() self.__context_menu = None else: if content_available(): self.__context_menu = ContentMenu() def on_shutdown(self): self.__extensions_subscription = None if self.__context_menu: self.__context_menu.destroy() self.__context_menu = None
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/stageviewer_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.window.stageviewer/omni/kit/window/stageviewer/__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 .stageviewer import StageViewer from .stageviewer_extension import StageViewerExtension
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/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 .stageviewer import ViewerWindows from .stageviewer_utils import is_extension_loaded from omni.kit.ui import get_custom_glyph_code def content_available(): """ Returns True if the extension "omni.kit.window.content_browser" is loaded. """ return is_extension_loaded("omni.kit.window.content_browser") class ContentMenu: """ When this object is alive, Content Browser has the additional context menu with the items that allow to view usd files. """ def __init__(self): self._content_window = None self.__view_menu_subscription = None if content_available(): import omni.kit.window.content_browser as content self._content_window = content.get_content_window() if self._content_window: self.__view_menu_subscription = self._content_window.add_context_menu( "Inspect", "show.svg", self._on_show_triggered, self._is_show_visible ) def _is_show_visible(self, content_url): '''True if we can show the menu item "View Image"''' for ext in ["usd", "usda"]: if content_url.endswith(f".{ext}"): return True return False def _on_show_triggered(self, menu, value): """Start watching for the layer and run the editor""" ViewerWindows().open_window(value) def destroy(self): """Stop all watchers and remove the menu from the content browser""" if self.__view_menu_subscription: self._content_window.delete_context_menu(self.__view_menu_subscription) self.__view_menu_subscription = None self._content_window = None ViewerWindows().close_all()
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/stageviewer.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from omni.kit.widget.stage import StageWidget from pxr import Usd from .singleton import Singleton @Singleton class ViewerWindows: """This object keeps all the Stage Viewer windows""" def __init__(self): self.__windows = {} def open_window(self, filepath): """Open StageViewer window with the stage file opened in it""" if filepath in self.__windows: self.__windows[filepath].visible = True else: stage = Usd.Stage.Open(filepath, Usd.Stage.LoadNone) if not stage: return window = StageViewer(stage) # When window is closed, remove it from the list window.set_visibility_changed_fn(lambda _, f=filepath: self.close(f)) self.__windows[filepath] = window def close(self, filepath): """Close and remove specific window""" self.__windows[filepath].destroy() self.__windows[filepath] = None del self.__windows[filepath] def close_all(self): """Close and remove all windows""" self.__windows = {} class StageViewer(ui.Window): """The Stage window that displays a custom stage""" def __init__(self, stage: Usd.Stage, **kwargs): if stage: name = stage.GetRootLayer().identifier else: name = "None" kwargs["flags"] = ui.WINDOW_FLAGS_NO_SCROLLBAR kwargs["width"] = 600 kwargs["height"] = 800 super().__init__(f"Stage {name}", **kwargs) with self.frame: # We only show the Type column self.__stage_widget = StageWidget(stage, columns_accepted=["Type"], lazy_payloads=True) def destroy(self): """ Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ self.__stage_widget.destroy() self.__stage_widget = None super().destroy()
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/singleton.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. # def Singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/tests/__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 .stageviewer_test import TestStageviewer
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/tests/stageviewer_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. ## import omni.kit.test from ..stageviewer import StageViewer from ..content_menu import ContentMenu from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from pxr import Usd from pxr import UsdGeom import omni.kit.app import omni.kit.commands import omni.ui as ui import omni.usd CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data") class TestStageviewer(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): # New stage with a sphere stage = Usd.Stage.CreateInMemory("test.usda") UsdGeom.Sphere.Define(stage, "/Sphere") window = await self.create_test_window() stageviewer = StageViewer(stage) stageviewer.flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE stageviewer.position_x = 0 stageviewer.position_y = 0 stageviewer.width = 256 stageviewer.height = 256 for _ in range(2): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir) stageviewer.destroy() async def test_context_menu(self): """This is to test that the content menu is shown when it is a usd file""" context_menu = ContentMenu() for _ in range(2): await omni.kit.app.get_app().next_update_async() file_name = f"{self._golden_img_dir}/empty.usd".replace("\\", "/") result = context_menu._is_show_visible(file_name) self.assertTrue(result, True) context_menu.destroy()
omniverse-code/kit/exts/omni.kit.window.stageviewer/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.5] - 2022-11-18 ### Fixed - Fix test on Linux ## [1.0.4] - 2022-07-05 ### Changed - Added more test to increase the test coverage ## [1.0.3] - 2022-04-06 ### Fixed - Message "Failed to acquire interface while unloading all plugins" ## [1.0.2] - 2021-06-16 ### Changed - Load payloads when the user expands the tree ## [1.0.1] - 2020-11-12 ### Changed - Fixed exception in Create ## [1.0.0] - 2020-09-16 ### Added - Adds context menu in the Content Browser
omniverse-code/kit/exts/omni.kit.multinode/PACKAGE-LICENSES/omni.kit.multinode-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.multinode/config/extension.toml
[package] title = "Kit Multi-Node Setup" version = "0.1.0" authors = ["NVIDIA"] [dependencies] "omni.kit.renderer.core" = {} [[native.plugin]] path = "bin/omni.kit.multinode.plugin" [[test]] waiver = "Extension is tested externally"
omniverse-code/kit/exts/omni.kit.widget.settings/PACKAGE-LICENSES/omni.kit.widget.settings-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.