file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial6/OgnTutorialTupleArrays.cpp
// 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. // #include <OgnTutorialTupleArraysDatabase.h> #include <algorithm> class OgnTutorialTupleArrays { public: static bool compute(OgnTutorialTupleArraysDatabase& db) { // Use the "auto&" declarations to avoid long type names, prone to error const auto& a = db.inputs.a(); const auto& b = db.inputs.b(); auto& result = db.outputs.result(); // Some simple error checking never hurts if (a.size() != b.size()) { db.logWarning("Input sizes did not match (%zu versus %zu)", a.size(), b.size()); return false; } // The output contents are unrelated to the input contents so resize rather than copying result.resize(a.size()); // Illustrating how simple these operations are thanks to iterators and the built-in operator* std::transform(a.begin(), a.end(), b.begin(), result.begin(), [](const GfVec3f& valueA, const GfVec3f& valueB) -> float { return valueA * valueB; }); return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial5/OgnTutorialArrayData.cpp
// 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. // #include <OgnTutorialArrayDataDatabase.h> #include <algorithm> class OgnTutorialArrayData { public: static bool compute(OgnTutorialArrayDataDatabase& db) { // For clarity get the attribute values into separate variables. The type definitions are included to // show exactly what data types are returned, though you should know that from your .ogn declaration. // It's sufficient to use "const auto" for inputs or "auto" for outputs. const float multiplier = db.inputs.multiplier(); const ::ogn::const_array<float>& inputArray = db.inputs.original(); const ::ogn::const_array<bool>& gateArray = db.inputs.gates(); ::ogn::array<float>& outputArray = db.outputs.result(); ::ogn::array<bool>& negativeValues = db.outputs.negativeValues(); if (gateArray.size() != inputArray.size()) { db.logWarning("Gate array size %zu should equal input array size %zu", gateArray.size(), inputArray.size()); return false; } // Output array data has to be properly sized before filling as it will contain the same number // of elements as the input the size is already known. You could also do an assignment and modify the // output in place if that makes your algorithm more efficient: // outputArray = inputArray; outputArray.resize(inputArray.size()); negativeValues.resize(inputArray.size()); // The attribute array data wrapper is compatible with the STL algorithms so computations can be // performed in a single std::algorithm call. std::transform(inputArray.begin(), inputArray.end(), gateArray.begin(), outputArray.begin(), [multiplier](const float& value, const bool& gate) -> float { return gate ? value * multiplier : value; }); std::transform(outputArray.begin(), outputArray.end(), negativeValues.begin(), [](const float& value) -> bool { return value < 0.0f; }); // Regular iterators can also be applied int totalCharacters{ 0 }; for (const auto& stringInput : db.inputs.info()) { totalCharacters += int(std::strlen(db.tokenToString(stringInput))); } db.outputs.infoSize() = totalCharacters; return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial5/OgnTutorialArrayData.ogn
{ "ArrayData": { "version": 1, "categories": "tutorials", "scheduling": ["threadsafe"], "description": ["This is a tutorial node. It will compute the array 'result' as the input array 'original' ", "with every element multiplied by the constant 'multiplier'." ], "$todo": "Enable the string attributes when fabric fully supports them", "metadata": { "uiName": "Tutorial Node: Array Attributes" }, "inputs": { "original": { "description": "Array to be multiplied", "type": "float[]", "default": [] }, "gates": { "description": "Boolean mask telling which elements of the array should be multiplied", "type": "bool[]", "default": [] }, "multiplier": { "description": "Multiplier of the array elements", "type": "float", "default": 1.0 }, "info": { "description": "List of strings providing commentary", "type": "token[]", "default": ["There", "is", "no", "data"] } }, "outputs": { "result": { "description": "Multiplied array", "type": "float[]" }, "negativeValues": { "description": "Array of booleans set to true if the corresponding 'result' is negative", "type": "bool[]" }, "infoSize": { "description": "Number of letters in all strings in the info input", "type": "int" } }, "tests": [ { "inputs:original": [1.0, 2.0, 3.0], "inputs:gates": [true, false, true], "inputs:multiplier": 2.0, "outputs:result": [2.0, 2.0, 6.0], "outputs:negativeValues": [false, false, false], "outputs:infoSize": 13 }, { "inputs:original": [10.0, -20.0, 30.0], "inputs:gates": [true, false, true], "outputs:result": [10.0, -20.0, 30.0], "outputs:negativeValues": [false, true, false] }, { "inputs:info": ["Hello", "lamp\"post", "what'cha", "knowing"], "outputs:infoSize": 29 } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial5/tutorial5.rst
.. _ogn_tutorial_arrayData: Tutorial 5 - Array Data Node ============================ Array data consists of multiple elements of a simple type whose count is only known at runtime. For example *float[]* or *double[]*. This node takes an array of floats and a multiplier and generates an output array consisting of the product of the two. OgnTutorialArrayData.ogn ------------------------ The *ogn* file shows the implementation of a node named "omni.graph.tutorials.ArrayData", which has a float value and float array input with one float array output. .. literalinclude:: OgnTutorialArrayData.ogn :linenos: :language: json OgnTutorialArrayData.cpp ------------------------ The *cpp* file contains the implementation of the compute method, which multiplies the float value by each member of the float array. Note how the attribute Array values can be accessed as though they were a simple *std::vector* type. .. literalinclude:: OgnTutorialArrayData.cpp :linenos: :language: c++ Array Attribute Access ---------------------- The attribute access is as described in :ref:`ogn_tutorial_simpleData` except that the exact return types of the attributes are different in order to support array member access. Full definition of the array wrapper classes can be found in the interface file *omni/graph/core/ogn/array.h*, though they do behave in a manner consistent with *std::array*, supporting iterators, standard algorithms, random access through either ``operator[]`` or the ``at(index)`` function, the ``empty()`` and ``size()`` functions, and access to the raw underlying data using the function ``data()``. The non-const version also supports assignment and the ``resize()`` function for modifying its contents. +---------------------+--------------------------------+ | Database Function | Returned Type | +=====================+================================+ | inputs.original() | const ogn::const_array<float>& | +---------------------+--------------------------------+ | inputs.multiplier() | const float& | +---------------------+--------------------------------+ | outputs.result() | ogn::array<float>& | +---------------------+--------------------------------+ These wrapper classes are similar in concept to ``std::span``, which handles unmanaged pointer+size data. In this case the data is being managed by the FlatCache. Modifications to the wrapper class data will directly modify the underlying data in the FlatCache. You can still use the *auto* declarations on these types, and the array attributes have an additional ``size()`` method added for convenience. .. code-block:: c++ bool compute(OgnTutorialArrayDataDatabase& db) { const auto& multiplier = db.inputs.multiplier(); const auto& original = db.inputs.original(); size_t originalSize = db.inputs.original.size(); auto& result = db.outputs.result(); };
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial25/OgnTutorialDynamicAttributes.cpp
// 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. // #include <OgnTutorialDynamicAttributesDatabase.h> #include <omni/graph/core/CppWrappers.h> namespace omni { namespace graph { using core::AttributeRole; namespace tutorials { class OgnTutorialDynamicAttributes { public: static bool compute(OgnTutorialDynamicAttributesDatabase& db) { auto iNode = db.abi_node().iNode; // Get a copy of the input so that it can be modified in place uint32_t rawOutput = db.inputs.value(); // Only run this section of code if the dynamic attribute is present if (iNode->getAttributeExists(db.abi_node(), db.tokenToString(db.tokens.firstBit))) { AttributeObj firstBit = iNode->getAttributeByToken(db.abi_node(), db.tokens.firstBit); // firstBit will invert the bit with its number, if present. const auto firstBitPtr = getDataR<uint32_t>( db.abi_context(), firstBit.iAttribute->getConstAttributeDataHandle(firstBit, db.getInstanceIndex())); if (firstBitPtr) { if( 0 <= *firstBitPtr && *firstBitPtr <= 31) { rawOutput ^= 1 << *firstBitPtr; } else { db.logWarning("Could not xor bit %ud. Must be in [0, 31]", *firstBitPtr); } } else { db.logError("Could not retrieve the data for firstBit"); } } if (iNode->getAttributeExists(db.abi_node(), db.tokenToString(db.tokens.secondBit))) { AttributeObj secondBit = iNode->getAttributeByToken(db.abi_node(), db.tokens.secondBit); // secondBit will invert the bit with its number, if present const auto secondBitPtr = getDataR<uint32_t>( db.abi_context(), secondBit.iAttribute->getConstAttributeDataHandle(secondBit, db.getInstanceIndex())); if (secondBitPtr) { if( 0 <= *secondBitPtr && *secondBitPtr <= 31) { rawOutput ^= 1 << *secondBitPtr; } else { db.logWarning("Could not xor bit %ud. Must be in [0, 31]", *secondBitPtr); } } else { db.logError("Could not retrieve the data for secondBit"); } } if (iNode->getAttributeExists(db.abi_node(), db.tokenToString(db.tokens.invert))) { AttributeObj invert = iNode->getAttributeByToken(db.abi_node(), db.tokens.invert); // invert will invert the bits, if the role is set and the attribute access is correct const auto invertPtr = getDataR<double>( db.abi_context(), invert.iAttribute->getConstAttributeDataHandle(invert, db.getInstanceIndex())); if (invertPtr) { // Verify that the invert attribute has the (random) correct role before applying it if (invert.iAttribute->getResolvedType(invert).role == AttributeRole::eTimeCode) { rawOutput ^= 0xffffffff; } } else { db.logError("Could not retrieve the data for invert"); } } // Set the modified result onto the output as usual db.outputs.result() = rawOutput; return true; } }; REGISTER_OGN_NODE() } // namespace tutorials } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial25/OgnTutorialDynamicAttributes.ogn
{ "DynamicAttributes": { "version": 1, "categories": "tutorials", "scheduling": ["threadsafe"], "description": [ "This is a C++ node that exercises the ability to add and remove database attribute", "accessors for dynamic attributes. When the dynamic attribute is added the property will exist", "and be able to get/set the attribute values. When it does not the property will not exist.", "The dynamic attribute names are found in the tokens below. If neither exist then the input", "value is copied to the output directly. If 'firstBit' exists then the 'firstBit'th bit of the input", "is x-ored for the copy. If 'secondBit' exists then the 'secondBit'th bit of the input is x-ored", "for the copy. (Recall bitwise match xor(0,0)=0, xor(0,1)=1, xor(1,0)=1, and xor(1,1)=0.)", "For example, if 'firstBit' is present and set to 1 then the bitmask will be b0010, where bit 1 is set.", "If the input is 7, or b0111, then the xor operation will flip bit 1, yielding b0101, or 5 as the result.", "If on the next run 'secondBit' is also present and set to 2 then its bitmask will be b0100, where bit", "2 is set. The input of 7 (b0111) flips bit 1 because firstBit=1 and flips bit 2 because", "secondBit=2, yielding a final result of 1 (b0001)." ], "uiName": "Tutorial Node: Dynamic Attributes", "tokens": {"firstBit": "inputs:firstBit", "secondBit": "inputs:secondBit", "invert": "inputs:invert"}, "inputs": { "value": { "type": "uint", "description": "Original value to be modified." } }, "outputs": { "result": { "type": "uint", "description": "Modified value" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial25/OgnTutorialDynamicAttributesPy.ogn
{ "DynamicAttributesPy": { "version": 1, "categories": "tutorials", "description": [ "This is a Python node that exercises the ability to add and remove database attribute", "accessors for dynamic attributes. When the dynamic attribute is added the property will exist", "and be able to get/set the attribute values. When it does not the property will not exist.", "The dynamic attribute names are found in the tokens below. If neither exist then the input", "value is copied to the output directly. If 'firstBit' exists then the 'firstBit'th bit of the input", "is x-ored for the copy. If 'secondBit' exists then the 'secondBit'th bit of the input is x-ored", "for the copy. (Recall bitwise match xor(0,0)=0, xor(0,1)=1, xor(1,0)=1, and xor(1,1)=0.)", "For example, if 'firstBit' is present and set to 1 then the bitmask will be b0010, where bit 1 is set.", "If the input is 7, or b0111, then the xor operation will flip bit 1, yielding b0101, or 5 as the result.", "If on the next run 'secondBit' is also present and set to 2 then its bitmask will be b0100, where bit", "2 is set. The input of 7 (b0111) flips bit 1 because firstBit=1 and flips bit 2 because", "secondBit=2, yielding a final result of 1 (b0001)." ], "uiName": "Tutorial Python Node: Dynamic Attributes", "language": "python", "tokens": {"firstBit": "inputs:firstBit", "secondBit": "inputs:secondBit", "invert": "inputs:invert"}, "inputs": { "value": { "type": "uint", "description": "Original value to be modified." } }, "outputs": { "result": { "type": "uint", "description": "Modified value" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial25/OgnTutorialDynamicAttributesPy.py
"""Implementation of the node OgnTutorialDynamicAttributesPy.ogn""" from contextlib import suppress from operator import xor import omni.graph.core as og class OgnTutorialDynamicAttributesPy: @staticmethod def compute(db) -> bool: """Compute the output based on the input and the presence or absence of dynamic attributes""" raw_output = db.inputs.value # The suppression of the AttributeError will just skip this section of code if the dynamic attribute # is not present with suppress(AttributeError): # firstBit will invert the bit with its number, if present. if 0 <= db.inputs.firstBit <= 31: raw_output = xor(raw_output, 2**db.inputs.firstBit) else: db.log_error(f"Could not xor bit {db.inputs.firstBit}. Must be in [0, 31]") with suppress(AttributeError): # secondBit will invert the bit with its number, if present if 0 <= db.inputs.secondBit <= 31: raw_output = xor(raw_output, 2**db.inputs.secondBit) else: db.log_error(f"Could not xor bit {db.inputs.secondBit}. Must be in [0, 31]") with suppress(AttributeError): # invert will invert the bits, if the role is set and the attribute access is correct _ = db.inputs.invert if ( db.role.inputs.invert == og.AttributeRole.TIMECODE and db.attributes.inputs.invert == db.abi_node.get_attribute(db.tokens.invert) ): raw_output = xor(raw_output, 0xFFFFFFFF) db.outputs.result = raw_output
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial25/tutorial25.rst
.. _ogn_tutorial_dynamic_attributes: Tutorial 25 - Dynamic Attributes ================================ A dynamic attribute is like any other attribute on a node, except that it is added at runtime rather than being part of the .ogn specification. These are added through the ABI function ``INode::createAttribute`` and removed from the node through the ABI function ``INode::removeAttribute``. Once a dynamic attribute is added it can be accessed through the same ABI and script functions as regular attributes. .. warning:: While the Python node database is able to handle the dynamic attributes through the same interface as regular attributes (e.g. ``db.inputs.dynAttr``), the C++ node database is not yet similarly flexible and access to dynamic attribute values must be done directly through the ABI calls. OgnTutorialDynamicAttributes.ogn -------------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.DynamicAttributes", which has a simple float input and output. .. literalinclude:: OgnTutorialDynamicAttributes.ogn :linenos: :language: json OgnTutorialDynamicAttributes.cpp -------------------------------- The *cpp* file contains the implementation of the compute method. It passes the input directly to the output unless it finds a dynamic attribute named "multiplier", in which case it multiplies by that amount instead. .. literalinclude:: OgnTutorialDynamicAttributes.cpp :linenos: :language: c++ OgnTutorialDynamicAttributesPy.py --------------------------------- The *py* file contains the same algorithm as the C++ node, with only the implementation language being different. .. literalinclude:: OgnTutorialDynamicAttributesPy.py :linenos: :language: python Adding And Removing Dynamic Attributes -------------------------------------- In addition to the above ABI functions the Python ``og.Controller`` class provides the ability to add and remove dynamic attributes from a script. To create a dynamic attribute you would use this function: .. literalinclude:: ../../../omni.graph/python/_impl/node_controller.py :language: python :start-after: begin-create-attribute-function :end-before: end-create-attribute-function For example this is the code to create a `float[3]` input and a bundle output on an existing node: .. code-block:: py import omni.graph.core as og new_input = og.Controller.create_attribute("/World/MyNode", "newInput", "float[3]") new_output = og.Controller.create_attribute("/World/MyNode", "newOutput", "bundle", og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) # The proper namespace will be added to the attribute, though you can also be explicit about it other_input = og.Controller.create_attribute("/World/MyNode", "inputs:otherInput", "float[3]") When the node is deleted the dynamic attribute will also be deleted, and the attribute will be stored in the USD file. If you want to remove the attribute from the node at any time you would use this function: .. literalinclude:: ../../../omni.graph/python/_impl/node_controller.py :language: python :start-after: begin-remove-attribute-function :end-before: end-remove-attribute-function The second optional parameter is only needed when the attribute is passed as a string. When passing an `og.Attribute` the node is already known, being part of the attribute. .. code-block:: py import omni.graph.core as og new_attr = og.Controller.create_attribute("/World/MyNode", "newInput", "float[3]") # When passing the attribute the node is not necessary og.Controller.remove_attribute(new_attr) # However if you don't have the attribute available you can still use the name, noting that the # namespace must be present. # og.Controller.remove_attribute("inputs:newInput", "/World/MyNode") Adding More Information +++++++++++++++++++++++ While the attribute name and type are sufficient to unambiguously create it there is other information you can add that would normally be present in the .ogn file. It's a good idea to add some of the basic metadata for the UI. .. code-block:: py import omni.graph.core as og new_attr = og.Controller.create_attribute("/World/MyNode", "newInput", "vectorf[3]") new_attr.set_metadata(og.MetadataKeys.DESCRIPTION, "This is a new input with a vector in it") new_attr.set_metadata(og.MetadataKeys.UI_NAME, "Input Vector") While dynamic attributes don't have default values you can do the equivalent by setting a value as soon as you create the attribute: .. code-block:: py import omni.graph.core as og new_attr = og.Controller.create_attribute("/World/MyNode", "newInput", "vectorf[3]") og.Controller.set(new_attr, [1.0, 2.0, 3.0]) This default value can also be changed at any time (even when the attribute is already connected): .. code-block:: py new_attr.set_default([1.0, 0.0, 0.0])
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial18/tutorial18.rst
.. _ogn_tutorial_state: Tutorial 18 - Node With Internal State ====================================== This node illustrates how you can use internal state information, so long as you inform OmniGraph that you are doing so in order for it to make more intelligent execution scheduling decisions. The advantage of using internal state data rather than state attributes is that the data can be in any structure you choose, not just those supported by OmniGraph. The disadvantage is that being opaque, none of the generic UI will be able to show information about that data. OgnTutorialState.ogn -------------------- The *.ogn* file containing the implementation of a node named "omni.graph.tutorials.State". Unlike Python nodes with internal state the C++ nodes do not require and empty `"state"` section as the presence of state information is inferred from the data members in the node implementation class (i.e. `mIncrementValue` in this node). .. literalinclude:: OgnTutorialState.ogn :linenos: :language: json OgnTutorialState.cpp -------------------- The *.cpp* file contains the compute method and the internal state information used to run the algorithm. By adding non-static class members to your node OmniGraph will know to instantiate a unique instance of your node for every evaluation context, letting you use those members as state data. The data in the node will be invisible to OmniGraph as a whole and will be persistent between evaluations of the node. .. literalinclude:: OgnTutorialState.cpp :linenos: :language: cpp
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial18/OgnTutorialState.cpp
// Copyright (c) 2020-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. // #include <OgnTutorialStateDatabase.h> #include <atomic> // Implementation of a C++ OmniGraph node that uses internal state information to compute outputs. class OgnTutorialState { // ------------------------------------------------------------ // The presence of these members will be detected when a node of this type is being instantiated, at which // time an instance of this node will be attached to the OmniGraph node and be made available in the // database class as the member "db.internalState<OgnTutorialState>()". // // Start all nodes with a monotinic increment value of 0 size_t mIncrementValue{ 0 }; // ------------------------------------------------------------ // You can also define node-type static data, although you are responsible for dealing with any // thread-safety issues that may arise from accessing it from multiple threads (or multiple hardware) // at the same time. In this case it is a single value that is read and incremented so an atomic // variable is sufficient. In real applications this would be a complex structure, potentially keyed off // of combinations of inputs or real time information, requiring more stringent locking. // // This value increases for each node and indicates the value from which a node's own internal state value // increments. e.g. the first instance of this node type will start its state value at 1, the second instance at 2, // and so on... static std::atomic<size_t> sStartingValue; public: // Operation of the state mechanism relies on the presence of a default constructor. If you don't have to do // any initialization you can let the compiler provide the default implementation. OgnTutorialState() { mIncrementValue = sStartingValue; // Update the per-class state information for the next node. The values go up by 100 to make it easier for // tests to compare the state information on different nodes. sStartingValue += 100; } // Helper function to update the node's internal state based on the previous values and the per-class state. // You could also do this in-place in the compute() function; pulling it out here makes the state manipulation // more explicit. void updateState() { mIncrementValue += 1; } public: // Compute the output based on inputs and internal state static bool compute(OgnTutorialStateDatabase& db) { // This illustrates how internal state and inputs can be used in conjunction. The inputs can be used // to divert to a different computation path. if (db.inputs.override()) { db.outputs.monotonic() = db.inputs.overrideValue(); } else { // OmniGraph ensures that the database contains the correct internal state information for the node // being evaluated. Beyond that it has no knowledge of the data within that state. auto& state = db.internalState<OgnTutorialState>(); db.outputs.monotonic() = state.mIncrementValue; // Update the node's internal state data for the next evaluation. state.updateState(); } return true; } }; std::atomic<size_t> OgnTutorialState::sStartingValue{ 0 }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial18/OgnTutorialState.ogn
{ "State" : { "version": 1, "categories": "tutorials", "scheduling": ["threadsafe"], "description": [ "This is a tutorial node. It makes use of internal state information", "to continuously increment an output." ], "metadata": { "uiName": "Tutorial Node: Internal States" }, "inputs": { "overrideValue": { "type": "int64", "description": "Value to use instead of the monotonically increasing internal one when 'override' is true", "default": 0, "metadata": { "uiName": "Override Value" } }, "override": { "type": "bool", "description": "When true get the output from the overrideValue, otherwise use the internal value", "default": false, "metadata": { "uiName": "Enable Override" } } }, "outputs": { "monotonic": { "type": "int64", "description": "Monotonically increasing output, set by internal state information", "default": 0, "metadata": { "uiName": "State-Based Output" } } }, "tests": [ { "inputs:overrideValue": 555, "inputs:override": true, "outputs:monotonic": 555 } ], "$tests": "State tests are better done by a script that can control how many times a node evaluates" } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial28/OgnTutorialVectorizedPassthrough.cpp
// Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnTutorialVectorizedPassthroughDatabase.h> // The method used by the computation to perform the passthrough // 0 = simple copy, no vectorization #define TUTO_PASSTHROUGH_METHOD_SIMPLE 0 // 1 = vectorized copy by moving the entire database to the next instance #define TUTO_PASSTHROUGH_METHOD_DB 1 // 2 = vectorized copy by indexing the instance directly per attribute #define TUTO_PASSTHROUGH_METHOD_ATTR 2 // 3 = vectorized copy using raw data #define TUTO_PASSTHROUGH_METHOD_RAW 3 //By default, use the most efficient method #define TUTO_PASSTHROUGH_METHOD TUTO_PASSTHROUGH_METHOD_RAW // This node perform a copy of its input to its output class OgnTutorialVectorizedPassthrough { public: #if TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_SIMPLE // begin-regular static bool compute(OgnTutorialVectorizedPassthroughDatabase& db) { db.outputs.value() = db.inputs.value(); return true; } // end-regular #elif TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_DB // begin-db static size_t computeVectorized(OgnTutorialVectorizedPassthroughDatabase& db, size_t count) { for(size_t idx = 0; idx < count; ++idx) { db.outputs.value() = db.inputs.value(); db.moveToNextInstance(); } return count; } // end-db #elif TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_ATTR // begin-attr static size_t computeVectorized(OgnTutorialVectorizedPassthroughDatabase& db, size_t count) { for(size_t idx = 0; idx < count; ++idx) db.outputs.value(idx) = db.inputs.value(idx); return count; } // end-attr #elif TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_RAW // begin-raw static size_t computeVectorized(OgnTutorialVectorizedPassthroughDatabase& db, size_t count) { auto spanIn = db.inputs.value.vectorized(count); auto spanOut = db.outputs.value.vectorized(count); memcpy(spanOut.data(), spanIn.data(), count * sizeof(float)); return count; } // end-raw #endif }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial28/OgnTutorialVectorizedPassthrough.ogn
{ "TutorialVectorizedPassThrough": { "version": 1, "description": "Simple passthrough node that copy its input to its output in a vectorized way", "categories": "tutorials", "uiName": "Tutorial Node: Vectorized Passthrough", "inputs":{ "value":{ "type": "float", "description": "input value" } }, "outputs": { "value": { "type": "float", "description": "output value" } }, "tests" : [ { "inputs:value": 1, "outputs:value": 1 }, { "inputs:value": 2, "outputs:value": 2 }, { "inputs:value": 3, "outputs:value": 3 }, { "inputs:value": 4, "outputs:value": 4 } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/OgnTutorialBundleAddAttributesPy.ogn
{ "BundleAddAttributesPy": { "version": 1, "categories": "tutorials", "description": [ "This is a Python tutorial node. It exercises functionality for adding and removing attributes on", "output bundles." ], "language": "python", "uiName": "Tutorial Python Node: Bundle Add Attributes", "inputs": { "typesToAdd": { "type": "token[]", "description": [ "List of type descriptions to add to the bundle. The strings in this list correspond to the", "strings that represent the attribute types in the .ogn file (e.g. float[3][], colord[3], bool" ], "uiName": "Attribute Types To Add" }, "addedAttributeNames": { "type": "token[]", "description": [ "Names for the attribute types to be added. The size of this array must match the size", "of the 'typesToAdd' array to be legal." ] }, "removedAttributeNames": { "type": "token[]", "description": "Names for the attribute types to be removed. Non-existent attributes will be ignored." }, "useBatchedAPI": { "type": "bool", "description": "Controls whether or not to used batched APIS for adding/removing attributes" } }, "outputs": { "bundle": { "type": "bundle", "description": ["This is the bundle with all attributes added by compute."], "uiName": "Constructed Bundle" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/tutorial21.rst
.. _ogn_tutorial_bundle_add_attributes: Tutorial 21 - Adding Bundled Attributes ======================================= Sometimes instead of simply copying data from an input or input bundle into an output bundle you might want to construct a bundle from some other criteria. For example a bundle construction node could take in an array of names and attribute types and output a bundle consisting of those attributes with some default values. The bundle accessor provides a simple method that can accomplish this task. Adding a new attribute is as simple as providing those two values to the bundle for every attribute you wish to add. There is also a complementary function to remove named bundle attributes. OgnTutorialBundleAddAttributes.ogn ---------------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.BundleData", which has one input bundle and one output bundle. .. literalinclude:: OgnTutorialBundleAddAttributes.ogn :linenos: :language: json OgnTutorialBundleAddAttributes.cpp ---------------------------------- The *cpp* file contains the implementation of the compute method. It accesses the attribute descriptions on the inputs and creates a bundle with attributes matching those descriptions as its output. .. literalinclude:: OgnTutorialBundleAddAttributes.cpp :linenos: :language: c++ OgnTutorialBundleAddAttributesPy.py ----------------------------------- The *py* file contains the same algorithm as the C++ node, with only the implementation language being different. .. literalinclude:: OgnTutorialBundleAddAttributesPy.py :linenos: :language: python
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/OgnTutorialBundleAddAttributes.ogn
{ "BundleAddAttributes": { "description": [ "This is a tutorial node. It exercises functionality for adding and removing attributes on", "output bundles." ], "version": 1, "categories": "tutorials", "uiName": "Tutorial Node: Bundle Add Attributes", "inputs": { "typesToAdd": { "type": "token[]", "description": [ "List of type descriptions to add to the bundle. The strings in this list correspond to the", "strings that represent the attribute types in the .ogn file (e.g. float[3][], colord[3], bool" ], "uiName": "Attribute Types To Add" }, "addedAttributeNames": { "type": "token[]", "description": [ "Names for the attribute types to be added. The size of this array must match the size", "of the 'typesToAdd' array to be legal." ] }, "removedAttributeNames": { "type": "token[]", "description": "Names for the attribute types to be removed. Non-existent attributes will be ignored." }, "useBatchedAPI": { "type": "bool", "description": "Controls whether or not to used batched APIS for adding/removing attributes" } }, "outputs": { "bundle": { "type": "bundle", "description": ["This is the bundle with all attributes added by compute."], "uiName": "Constructed Bundle" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/OgnTutorialBundleAddAttributesPy.py
""" Implementation of the Python node adding attributes with a given description to an output bundle. """ import omni.graph.core as og class OgnTutorialBundleAddAttributesPy: """Exercise the bundled data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialBundleAddAttributes.cpp using the Python bindings to the bundle method """ # Start with an empty output bundle. output_bundle = db.outputs.bundle output_bundle.clear() if db.inputs.useBatchedAPI: attr_types = [og.AttributeType.type_from_ogn_type_name(type_name) for type_name in db.inputs.typesToAdd] output_bundle.add_attributes(attr_types, db.inputs.addedAttributeNames) output_bundle.remove_attributes(db.inputs.removedAttributeNames) else: for attribute_type_name, attribute_name in zip(db.inputs.typesToAdd, db.inputs.addedAttributeNames): attribute_type = og.AttributeType.type_from_ogn_type_name(attribute_type_name) output_bundle.insert((attribute_type, attribute_name)) # Remove attributes from the bundle that were already added. This is a somewhat contrived operation that # allows testing of both adding and removal within a simple environment. for attribute_name in db.inputs.removedAttributeNames: output_bundle.remove(attribute_name) return True
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/OgnTutorialBundleAddAttributes.cpp
// 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. // #include <OgnTutorialBundleAddAttributesDatabase.h> #include <omni/graph/core/IAttributeType.h> using omni::graph::core::Type; class OgnTutorialBundleAddAttributes { public: static bool compute(OgnTutorialBundleAddAttributesDatabase& db) { const auto& attributeTypeNames = db.inputs.typesToAdd(); const auto& attributeNames = db.inputs.addedAttributeNames(); const auto& useBatchedAPI = db.inputs.useBatchedAPI(); auto& outputBundle = db.outputs.bundle(); // The usual error checking. Being diligent about checking the data ensures you will have an easier time // debugging the graph if anything goes wrong. if (attributeTypeNames.size() != attributeNames.size()) { db.logWarning( "Number of attribute types (%zu) does not match number of attribute names (%zu)", attributeTypeNames.size(), attributeNames.size() ); return false; } // Make sure the bundle is starting from empty outputBundle.clear(); if (useBatchedAPI) { // // unfortunately we need to build a vector of the types // auto typeNameIt = std::begin(attributeTypeNames); std::vector<Type> types; types.reserve(attributeTypeNames.size()); for (; typeNameIt != std::end(attributeTypeNames); ++typeNameIt) { auto typeName = *typeNameIt; types.emplace_back(db.typeFromName(typeName)); } outputBundle.addAttributes(attributeTypeNames.size(), attributeNames.data(), types.data()); // Remove attributes from the bundle that were already added. This is a somewhat contrived operation that // allows testing of both adding and removal within a simple environment. if (db.inputs.removedAttributeNames().size()) { outputBundle.removeAttributes(db.inputs.removedAttributeNames().size(), db.inputs.removedAttributeNames().data()); } } else { // Since the two arrays are the same size a dual loop can be used to walk them in pairs auto typeNameIt = std::begin(attributeTypeNames); auto attributeNameIt = std::begin(attributeNames); for (; typeNameIt != std::end(attributeTypeNames) && attributeNameIt != std::end(attributeNames); ++typeNameIt, ++attributeNameIt) { auto typeName = *typeNameIt; auto attributeName = *attributeNameIt; auto typeNameString = db.tokenToString(typeName); Type newType = db.typeFromName(typeName); // Ignore the output since for this example there will not be any values set on the new attribute (void)outputBundle.addAttribute(attributeName, newType); } // Remove attributes from the bundle that were already added. This is a somewhat contrived operation that // allows testing of both adding and removal within a simple environment. for (const auto& toRemove : db.inputs.removedAttributeNames()) { outputBundle.removeAttribute(toRemove); } } return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial8/tutorial8.rst
.. _ogn_tutorial_cudaData: Tutorial 8 - GPU Data Node ========================== The GPU data node creates various attributes for use in a CUDA-based GPU compute. Several representative types are used, though the list of potential attribute types is not exhaustive. See :ref:`ogn_attribute_types` for the full list. This node also introduces the notion of attribute typedefs; a useful concept when passing data around in functions. OgnTutorialCudaData.ogn ----------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CudaData", which has inputs and outputs of various types to use in various computations. Three different CUDA methods are created to show how each of the types is passed through to the GPU and used by CUDA. .. literalinclude:: OgnTutorialCudaData.ogn :linenos: :language: json OgnTutorialCudaData.cpp ----------------------- The *cpp* file contains the implementation of the compute method, which in turn calls the three CUDA algorithms. .. literalinclude:: OgnTutorialCudaData.cpp :linenos: :language: c++ OgnTutorialCudaData_CUDA.cu --------------------------- The *cu* file contains the implementation of the algorithms on the GPU using CUDA. .. literalinclude:: OgnTutorialCudaData_CUDA.cu :linenos: :language: c++ GPU Attribute Access -------------------- Here is the set of generated attributes from the database. The attributes living on the GPU return pointers to memory as the CPU side cannot dereference it into its actual type (e.g. a `float` value, which would be returned as a `float&` on the CPU side is returned instead as a `float*` on the GPU side.) In addition, when calling into CUDA code the data changes type as it crosses the GPU boundary. On the CUDA side it uses the CUDA native data types when it can, which are bytewise compatible with their CPU counterparts. Note that in the case of the CPU attribute *multiplier* the data is passed to the CUDA code by value, since it has to be copied from CPU to GPU. +---------------------+---------+--------------------+-----------------+ | Database Function | Is GPU? | CPU Type | CUDA Type | +=====================+=========+====================+=================+ | inputs.a() | Yes | const float* | const float* | +---------------------+---------+--------------------+-----------------+ | inputs.b() | Yes | const float* | const float* | +---------------------+---------+--------------------+-----------------+ | outputs.sum() | Yes | float* | float* | +---------------------+---------+--------------------+-----------------+ | inputs.half() | Yes | const pxr::GfHalf* | __half* | +---------------------+---------+--------------------+-----------------+ | outputs.half() | Yes | pxr::GfHalf* | __half* | +---------------------+---------+--------------------+-----------------+ | inputs.color() | Yes | const GfVec3d* | const double3* | +---------------------+---------+--------------------+-----------------+ | outputs.color() | Yes | GfVec3d* | double3* | +---------------------+---------+--------------------+-----------------+ | inputs.matrix() | Yes | const GfMatrix4d* | const Matrix4d* | +---------------------+---------+--------------------+-----------------+ | outputs.matrix() | Yes | GfMatrix4d* | Matrix4d* | +---------------------+---------+--------------------+-----------------+ | inputs.multiplier() | No | const GfVec3f& | const float3 | +---------------------+---------+--------------------+-----------------+ | inputs.points() | Yes | const GfVec3f* | const float3** | +---------------------+---------+--------------------+-----------------+ | outputs.points() | Yes | GfVec3f* | float3** | +---------------------+---------+--------------------+-----------------+ The array attribute *points* does not have an array-like wrapper as the CUDA code would rather deal with raw pointers. In order to provide the size information, when calling the CUDA code the value ``inputs.points.size()`` should also be passed in. Notice the subtle difference in types on the CPU side for GPU-based data. Instead of references to data there are pointers, necessary since the data lives in a different memory-space, and all pointers have an extra level of indirection for the same reason. There is also a section of this generated file dedicated to information relevant to the CUDA code. In this section the CUDA attribute data types are defined. It is protected with ``#ifdef __CUDACC__`` so that it is only processed when included through the CUDA compiler (and vice versa, so none of the other setup code will be processed on the CUDA side). .. code-block:: c++ #include <cuda_fp16.h> #include <omni/graph/core/cuda/CUDAUtils.h> #include <omni/graph/core/cuda/Matrix4d.h> namespace OgnTutorialCudaDataCudaTypes { namespace inputs { using a_t = const float*; using b_t = const float*; using points_t = const float3**; using multiplier_t = const float3*; using half_t = const __half*; using color_t = const double3*; using matrix_t = const Matrix4d*; } namespace outputs { using sum_t = float*; using points_t = float3**; using half_t = __half*; using color_t = double3*; using matrix_t = Matrix4d*; } } using namespace OgnTutorialCudaDataCudaTypes; Notice the inclusion of the file *cuda_fp16.h*, needed due to the use of the CUDA type *__half*, and the files *omni/graph/core/cuda/CUDAUtils.h* and *omni/graph/core/cuda/Matrix4d.h*, which provide support functions for CUDA math. The data types used by CUDA are compatible with their equivalents on the C++ side, so you can specify passing arguments into CUDA from C++ by using a declaration such as this on the C++ side: .. code-block:: c++ // In this code "inputs::points_t" is the type "GfVec3f*". // The size of that array must be passed in as well since it is not implicit in the data type. extern "C" void cudaCompute( inputs::points_t*, size_t pointSize, inputs::multiplier_t*, outputs::points_t* ); which corresponds to this function defined in the .cu file: .. code-block:: c++ // In this code "inputs::points_t" is the type "float3*" extern "C" void cudaCompute( inputs::points_t* inPoints, size_t pointSize, inputs::multiplier_t* multiplier, outputs::points_t* outPoints ) {...} Pointers are used in the calls rather than being part of the type definitions in order to emphasize the fact that the values passed through are pointers to the real data in the flatcache, which in this case is data in GPU memory.
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial8/OgnTutorialCudaData.cpp
// 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. // #include <omni/graph/core/GpuArray.h> #include <OgnTutorialCudaDataDatabase.h> // This function exercises referencing simple data types on the GPU, something you normally wouldn't do as // there is no efficiency gain in doing that versus just passing in the CPU value. extern "C" void applyAddGPU(outputs::sum_t sum, inputs::a_t a, inputs::b_t b); // This function exercises referencing of array data on the GPU. // The CUDA code takes its own "float3" data types, which are castable equivalents to the generated GfVec3f. // The GpuArray/ConstGpuArray wrappers isolate the GPU pointers from the CPU code. extern "C" void applyDeformationGPU(outputs::points_t outputPoints, inputs::points_t inputPoints, inputs::multiplier_t multiplier, size_t numberOfPoints); // This function exercises referencing non-standard data types on the GPU to illustrate how data of different // types are passed to the GPU. extern "C" void applyDataTypes(outputs::half_t halfOutput, outputs::color_t colorOutput, outputs::matrix_t matrixOutput, inputs::half_t halfInput, inputs::color_t colorInput, inputs::matrix_t matrixInput); // This node runs a couple of algorithms on the GPU, while accessing parameters from the CPU class OgnTutorialCudaData { public: static bool compute(OgnTutorialCudaDataDatabase& db) { // ================ algorithm 1 ========================================================= // It's an important distinction here that GPU data is always returned as raw pointers since the CPU code // in the node cannot directly access it. The raw pointers are passed into the GPU code for dereferencing. applyAddGPU(db.outputs.sum(), db.inputs.a(), db.inputs.b()); // ================ algorithm 2 ========================================================= size_t numberOfPoints = db.inputs.points.size(); db.outputs.points.resize(numberOfPoints); const auto& multiplier = db.inputs.multiplier(); if (numberOfPoints > 0) { applyDeformationGPU(db.outputs.points(), db.inputs.points(), db.inputs.multiplier(), numberOfPoints); } // ================ algorithm 3 ========================================================= applyDataTypes(db.outputs.half(), db.outputs.color(), db.outputs.matrix(), db.inputs.half(), db.inputs.color(), db.inputs.matrix()); return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial8/OgnTutorialCudaData.ogn
{ "CudaData" : { "version": 1, "categories": "tutorials", "scheduling": ["threadsafe"], "memoryType": "cuda", "description": [ "This is a tutorial node. It performs different functions on the GPU to illustrate different types of", "data access. The first adds inputs 'a' and 'b' to yield output 'sum', all of which are on the GPU.", "The second is a sample expansion deformation that multiplies every point on a set of input points,", "stored on the GPU, by a constant value, stored on the CPU, to yield a set of output points, also on the GPU.", "The third is an assortment of different data types illustrating how different data is passed to the GPU.", "This particular node uses CUDA for its GPU computations, as indicated in the memory type value.", "Normal use case for GPU compute is large amounts of data. For testing purposes this node only handles", "a very small amount but the principle is the same." ], "metadata": { "uiName": "Tutorial Node: Attributes With CUDA Data" }, "inputs": { "a": { "type": "float", "description": ["First value to be added in algorithm 1"], "default": 0.0 }, "b": { "type": "float", "description": ["Second value to be added in algorithm 1"], "default": 0.0 }, "points": { "type": "float[3][]", "description": ["Points to be moved by algorithm 2"], "default": [] }, "multiplier": { "type": "float[3]", "memoryType": "cpu", "description": ["Amplitude of the expansion for the input points in algorithm 2"], "default": [1.0, 1.0, 1.0] }, "half": { "type": "half", "description": ["Input of type half for algorithm 3"], "default": 1.0 }, "color": { "type": "colord[3]", "description": ["Input with three doubles as a color for algorithm 3"], "default": [1.0, 0.5, 1.0] }, "matrix": { "type": "matrixd[4]", "description": ["Input with 16 doubles interpreted as a double-precision 4d matrix"], "default": [[1.0,0.0,0.0,0.0], [0.0,1.0,0.0,0.0], [0.0,0.0,1.0,0.0], [0.0,0.0,0.0,1.0]] } }, "outputs": { "sum": { "type": "float", "description": ["Sum of the two inputs from algorithm 1"] }, "points": { "type": "float[3][]", "description": ["Final positions of points from algorithm 2"] }, "half": { "type": "half", "description": ["Output of type half for algorithm 3"] }, "color": { "type": "colord[3]", "description": ["Output with three doubles as a color for algorithm 3"] }, "matrix": { "type": "matrixd[4]", "description": ["Output with 16 doubles interpreted as a double-precision 4d matrix"] } }, "$why": "By putting inputs but no outputs in tests I can run the compute without failing on extraction", "tests": [ { "inputs:a": 1.0, "inputs:b": 2.0, "inputs:half": 1.0, "inputs:color": [0.5, 0.6, 0.7], "inputs:matrix": [[1.0,2.0,3.0,4.0],[2.0,3.0,4.0,5.0],[3.0,4.0,5.0,6.0],[4.0,5.0,6.0,7.0]], "inputs:points": [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], "inputs:multiplier": [2.0, 3.0, 4.0] } ], "$tests_disabled_until_gpu_data_extraction_works": [ { "inputs:a": 1.0, "inputs:b": 2.0, "outputs:sum": 3.0 }, { "inputs:a": 5.0, "inputs:b": 3.0, "outputs:sum": 8.0 }, { "inputs:half": 1.0, "outputs:half": 2.0, "inputs:color": [0.5, 0.6, 0.7], "outputs:color": [0.5, 0.4, 0.3], "inputs:matrix": [[1.0,2.0,3.0,4.0],[2.0,3.0,4.0,5.0],[3.0,4.0,5.0,6.0],[4.0,5.0,6.0,7.0]], "outputs:matrix": [[30.0,40.0,50.0,60.0],[40.0,54.0,68.0,82.0],[50.0,68.0,86.0,104.0],[60.0,82.0,104.0,126.0]], "inputs:points": [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], "inputs:multiplier": [2.0, 3.0, 4.0], "outputs:points": [[2.0, 6.0, 12.0], [4.0, 9.0, 16.0]] } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial10/OgnTutorialSimpleDataPy.py
""" Implementation of the Python node accessing all of the simple data types. This class exercises access to the DataModel through the generated database class for all simple data types. It implements the same algorithm as the C++ node OgnTutorialSimpleData.cpp """ import omni.graph.tools.ogn as ogn class OgnTutorialSimpleDataPy: """Exercise the simple data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Perform a trivial computation on all of the simple data types to make testing easy""" # Inside the database the contained object "inputs" holds the data references for all input attributes and the # contained object "outputs" holds the data references for all output attributes. # Each of the attribute accessors are named for the name of the attribute, with the ":" replaced by "_". # The colon is used in USD as a convention for creating namespaces so it's safe to replace it without # modifying the meaning. The "inputs:" and "outputs:" prefixes in the generated attributes are matched # by the container names. # For example attribute "inputs:translate:x" would be accessible as "db.inputs.translate_x" and attribute # "outputs:matrix" would be accessible as "db.outputs.matrix". # The "compute" of this method modifies each attribute in a subtle way so that a test can be written # to verify the operation of the node. See the .ogn file for a description of tests. db.outputs.a_bool = not db.inputs.a_bool db.outputs.a_half = 1.0 + db.inputs.a_half db.outputs.a_int = 1 + db.inputs.a_int db.outputs.a_int64 = 1 + db.inputs.a_int64 db.outputs.a_double = 1.0 + db.inputs.a_double db.outputs.a_float = 1.0 + db.inputs.a_float db.outputs.a_uchar = 1 + db.inputs.a_uchar db.outputs.a_uint = 1 + db.inputs.a_uint db.outputs.a_uint64 = 1 + db.inputs.a_uint64 db.outputs.a_string = db.inputs.a_string.replace("hello", "world") db.outputs.a_objectId = 1 + db.inputs.a_objectId # The token interface is made available in the database as well, for convenience. # By calling "db.token" you can look up the token ID of a given string. if db.inputs.a_token == "helloToken": db.outputs.a_token = "worldToken" # Path just gets a new child named "Child". # In the implementation the string is manipulated directly, as it does not care if the SdfPath is valid or # not. If you want to manipulate it using the pxr.Sdf.Path API this is how you could do it: # # from pxr import Sdf # input_path Sdf.Path(db.inputs.a_path) # if input_path.IsValid(): # db.outputs.a_path() = input_path.AppendChild("/Child").GetString(); # db.outputs.a_path = db.inputs.a_path + "/Child" # To access the metadata you have to go out to the ABI, though the hardcoded metadata tags are in the # OmniGraph Python namespace assert db.node.get_attribute("inputs:a_bool").get_metadata(ogn.MetadataKeys.UI_NAME) == "Simple Boolean Input" # You can also use the database interface to get the same data db.outputs.a_nodeTypeUiName = db.get_metadata(ogn.MetadataKeys.UI_NAME) db.outputs.a_a_boolUiName = db.get_metadata(ogn.MetadataKeys.UI_NAME, db.attributes.inputs.a_bool) return True
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial10/OgnTutorialSimpleDataPy.ogn
{ "SimpleDataPy" : { "version": 1, "categories": "tutorials", "description": [ "This is a tutorial node. It creates both an input and output attribute of every simple ", "supported data type. The values are modified in a simple way so that the compute modifies values. ", "It is the same as node omni.graph.tutorials.SimpleData, except it is implemented in Python instead of C++." ], "language": "python", "$iconOverride": [ "If for some reason the default name or colors for the icon are inappropriate you can override like this.", "This gives an alternative icon path, a shape color of Green, a border color of Red, and a background", "color of half-opaque Blue. If you just want to override the icon path then instead of a dictionary you", "can just use the string path, as in \"icon\": \"Tutorial10Icon.svg\"." ], "icon": { "path": "Tutorial10Icon.svg", "color": "#FF00FF00", "borderColor": [255, 0, 0, 255], "backgroundColor": "#7FFF0000" }, "metadata": { "uiName": "Tutorial Python Node: Attributes With Simple Data" }, "inputs": { "a_bool": { "type": "bool", "metadata": { "uiName": "Simple Boolean Input" }, "description": ["This is an attribute of type boolean"], "default": true, "$optional": "When this is set there is no checking for validity before calling compute()", "optional": true }, "a_half": { "type": "half", "description": ["This is an attribute of type 16 bit float"], "$comment": "0 is used as the decimal portion due to reduced precision of this type", "default": 0.0 }, "a_int": { "type": "int", "description": ["This is an attribute of type 32 bit integer"], "default": 0 }, "a_int64": { "type": "int64", "description": ["This is an attribute of type 64 bit integer"], "default": 0 }, "a_float": { "type": "float", "description": ["This is an attribute of type 32 bit floating point"], "default": 0 }, "a_double": { "type": "double", "description": ["This is an attribute of type 64 bit floating point"], "default": 0 }, "a_path": { "type": "path", "description": ["This is an attribute of type path"], "default": "" }, "a_string": { "type": "string", "description": ["This is an attribute of type string"], "default": "helloString" }, "a_token": { "type": "token", "description": ["This is an attribute of type interned string with fast comparison and hashing"], "default": "helloToken" }, "a_objectId": { "type": "objectId", "description": ["This is an attribute of type objectId"], "default": 0 }, "a_uchar": { "type": "uchar", "description": ["This is an attribute of type unsigned 8 bit integer"], "default": 0 }, "a_uint": { "type": "uint", "description": ["This is an attribute of type unsigned 32 bit integer"], "default": 0 }, "a_uint64": { "type": "uint64", "description": ["This is an attribute of type unsigned 64 bit integer"], "default": 0 }, "a_constant_input": { "type": "int", "description": ["This is an input attribute whose value can be set but can only be connected as a source."], "metadata": { "outputOnly": "1" } } }, "outputs": { "a_bool": { "type": "bool", "description": ["This is a computed attribute of type boolean"] }, "a_half": { "type": "half", "description": ["This is a computed attribute of type 16 bit float"] }, "a_int": { "type": "int", "description": ["This is a computed attribute of type 32 bit integer"] }, "a_int64": { "type": "int64", "description": ["This is a computed attribute of type 64 bit integer"] }, "a_float": { "type": "float", "description": ["This is a computed attribute of type 32 bit floating point"] }, "a_double": { "type": "double", "description": ["This is a computed attribute of type 64 bit floating point"] }, "a_path": { "type": "path", "description": ["This is a computed attribute of type path"], "default": "/Child" }, "a_string": { "type": "string", "description": ["This is a computed attribute of type string"], "default": "This string is empty" }, "a_token": { "type": "token", "description": ["This is a computed attribute of type interned string with fast comparison and hashing"] }, "a_objectId": { "type": "objectId", "description": ["This is a computed attribute of type objectId"] }, "a_uchar": { "type": "uchar", "description": ["This is a computed attribute of type unsigned 8 bit integer"] }, "a_uint": { "type": "uint", "description": ["This is a computed attribute of type unsigned 32 bit integer"] }, "a_uint64": { "type": "uint64", "description": ["This is a computed attribute of type unsigned 64 bit integer"] }, "a_nodeTypeUiName": { "type": "string", "description": "Computed attribute containing the UI name of this node type" }, "a_a_boolUiName": { "type": "string", "description": "Computed attribute containing the UI name of input a_bool" } }, "tests": [ { "$comment": ["Each test has a description of the test and a set of input and output values. ", "The test runs by setting all of the specified inputs on the node to their values, ", "running the compute, then comparing the computed outputs against the values ", "specified in the test. Only the inputs in the list are set; others will use their ", "default values. Only the outputs in the list are checked; others are ignored."], "description": "Check that false becomes true", "inputs:a_bool": false, "outputs:a_bool": true }, { "$comment": "This is a more verbose format of test data that provides a different grouping of values", "description": "Check that true becomes false", "inputs": { "a_bool": true }, "outputs": { "a_bool": false, "a_a_boolUiName": "Simple Boolean Input", "a_nodeTypeUiName": "Tutorial Python Node: Attributes With Simple Data" } }, { "$comment": "Make sure the path append does the right thing", "inputs:a_path": "/World/Domination", "outputs:a_path": "/World/Domination/Child" }, { "$comment": "Even though these computations are all independent they can be checked in a single test.", "description": "Check all attributes against their computed values", "inputs:a_bool": false, "outputs:a_bool": true, "inputs:a_double": 1.1, "outputs:a_double": 2.1, "inputs:a_float": 3.3, "outputs:a_float": 4.3, "inputs:a_half": 5.0, "outputs:a_half": 6.0, "inputs:a_int": 7, "outputs:a_int": 8, "inputs:a_int64": 9, "outputs:a_int64": 10, "inputs:a_token": "helloToken", "outputs:a_token": "worldToken", "inputs:a_string": "helloString", "outputs:a_string": "worldString", "inputs:a_objectId": 10, "outputs:a_objectId": 11, "inputs:a_uchar": 11, "outputs:a_uchar": 12, "inputs:a_uint": 13, "outputs:a_uint": 14, "inputs:a_uint64": 15, "outputs:a_uint64": 16 } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial10/tutorial10.rst
.. _ogn_tutorial_simpleDataPy: Tutorial 10 - Simple Data Node in Python ======================================== The simple data node creates one input attribute and one output attribute of each of the simple types, where "simple" refers to data types that have a single component and are not arrays. (e.g. "float" is simple, "float[3]" is not, nor is "float[]"). See also :ref:`ogn_tutorial_simpleData` for a similar example in C++. Automatic Python Node Registration ---------------------------------- By implementing the standard Carbonite extension interfact in Python, OmniGraph will know to scan your Python import path for to recursively scan the directory, import all Python node files it finds, and register those nodes. It will also deregister those nodes when the extension shuts down. Here is an example of the directory structure for an extension with a single node in it. (For extensions that have a `premake5.lua` build script this will be in the build directory. For standalone extensions it is in your source directory.) .. code-block:: text omni.my.extension/ omni/ my/ extension/ nodes/ OgnMyNode.ogn OgnMyNode.py OgnTutorialSimpleDataPy.ogn --------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.SimpleDataPy", which has one input and one output attribute of each simple type. .. literalinclude:: OgnTutorialSimpleDataPy.ogn :linenos: :language: json OgnTutorialSimpleDataPy.py -------------------------- The *py* file contains the implementation of the compute method, which modifies each of the inputs in a simple way to create outputs that have different values. .. literalinclude:: OgnTutorialSimpleDataPy.py :linenos: :language: python Note how the attribute values are available through the ``OgnTutorialSimpleDataPyDatabase`` class. The generated interface creates access methods for every attribute, named for the attribute itself. They are all implemented as Python properties, where inputs only have get methods and outputs have both get and set methods. Pythonic Attribute Data ----------------------- Three subsections are creating in the generated database class. The main section implements the node type ABI methods and uses introspection on your node class to call any versions of the ABI methods you have defined (see later tutorials for examples of how this works). The other two subsections are classes containing attribute access properties for inputs and outputs. For naming consistency the class members are called *inputs* and *outputs*. For example, you can access the value of the input attribute named *foo* by referencing ``OgnTutorialSimpleDataPyDatabase.inputs.foo``. For the curious, here is an example of how the boolean attribute access is set up on the simple tutorial node: .. code-block:: python class OgnTutorialSimpleDataPyDatabase: class InputAttributes: def __init__(self, context_helper, node): self.context_helper = context_helper self.node = node # A lock is used to prevent inputs from inadvertently being modified during a compute. # This is equivalent to the "const" approach used in C++. self.setting_locked = False # Caching the Attribute object lets future data access run faster self._a_bool = node.get_attribute('inputs:a_bool') @property def a_bool(self): return self.context_helper.get_attr_value(self._a_bool) @a_bool.setter def a_bool(self, value): if self.setting_locked: raise AttributeError('inputs:a_bool') self.context_helper.set_attr_value(value, self._a_bool) class OutputAttributes: def __init__(self, context_helper, node): self.context_helper = context_helper self.node = node self._a_bool = node.get_attribute('outputs:a_bool') @property def a_bool(self): return self.context_helper.get_attr_value(self._a_bool) @a_bool.setter def a_bool(self, value): self.context_helper.set_attr_value(value, self._a_bool) def __init__(self, context, node): self.context = context self.node = node self.context_helper = ContextHelper(context) self.inputs = OgnTutorialSimpleDataPyDatabase.InputAttributes(self.context_helper, node) self.outputs = OgnTutorialSimpleDataPyDatabase.OutputAttributes(self.context_helper, node) Pythonic Attribute Access ------------------------- In the USD file the attribute names are automatically namespaced as *inputs:FOO* or *outputs:BAR*. In the Python interface the colon is illegal so the contained classes above are used to make use of the dot-separated equivalent, as *inputs.FOO* or *outputs.BAR*. While the underlying data types are stored in their exact form there is conversion when they are passed back to Python as Python has a more limited set of data types, though they all have compatible ranges. For this class, these are the types the properties provide: +-------------------+---------------+ | Database Property | Returned Type | +===================+===============+ | inputs.a_bool | bool | +-------------------+---------------+ | inputs.a_half | float | +-------------------+---------------+ | inputs.a_int | int | +-------------------+---------------+ | inputs.a_int64 | int | +-------------------+---------------+ | inputs.a_float | float | +-------------------+---------------+ | inputs.a_double | float | +-------------------+---------------+ | inputs.a_token | str | +-------------------+---------------+ | outputs.a_bool | bool | +-------------------+---------------+ | outputs.a_half | float | +-------------------+---------------+ | outputs.a_int | int | +-------------------+---------------+ | outputs.a_int64 | int | +-------------------+---------------+ | outputs.a_float | float | +-------------------+---------------+ | outputs.a_double | float | +-------------------+---------------+ | outputs.a_token | str | +-------------------+---------------+ The data returned are all references to the real data in the FlatCache, our managed memory store, pointed to the correct location at evaluation time. Python Helpers -------------- A few helpers are provided in the database class definition to help make coding with it more natural. Python logging ++++++++++++++ Two helper functions are providing in the database class to help provide more information when the compute method of a node has failed. Two methods are provided, both taking a formatted string describing the problem. ``log_error(message)`` is used when the compute has run into some inconsistent or unexpected data, such as two input arrays that are supposed to have the same size but do not, like the normals and vertexes on a mesh. ``log_warning(message)`` can be used when the compute has hit an unusual case but can still provide a consistent output for it, for example the deformation of an empty mesh would result in an empty mesh and a warning since that is not a typical use for the node. Direct Pythonic ABI Access ++++++++++++++++++++++++++ All of the generated database classes provide access to the underlying *INodeType* ABI for those rare situations where you want to access the ABI directly. There are two members provided, which correspond to the objects passed in to the ABI compute method. There is the graph evaluation context member, ``context: Py_GraphContext``, for accessing the underlying OmniGraph evaluation context and its interface. There is also the OmniGraph node member, ``node: Py_Node``, for accessing the underlying OmniGraph node object and its interface.
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial13/OgnTutorialStatePy.py
""" Implementation of a Python node that uses internal state information to compute outputs. There are two types of state information in use here: - OgnTutorialStatePy.step (per-class state information) This is inherently dangerous in a multi-threaded multi-hardware evaluation so it must be used with care. In this case the value is only used when a node is created, which for now is a safe single-threaded operation - per-node state information. """ class OgnTutorialStatePyInternalState: """Convenience class for maintaining per-node state information""" def __init__(self): """Instantiate the per-node state information. Note: For convenience, per-node state data is maintained as members of this class, imposing the minor restriction of having no parameters allowed in this constructor. The presence of the "state" section in the .ogn node has flagged to omnigraph the fact that this node will be managing some per-node state data. """ # Start all nodes with a monotinic increment value of 0 self.increment_value = 0 # Get this node's internal step value from the per-class state information self.node_step = OgnTutorialStatePy.step # Update the per-class state information for the next node OgnTutorialStatePy.step += 1 def update_state(self): """Helper function to update the node's internal state based on the previous values and the per-class state""" self.increment_value += self.node_step class OgnTutorialStatePy: """Use internal node state information in addition to inputs""" # This is a simplified bit of internal per-class state information. In real applications this would be a complex # structure, potentially keyed off of combinations of inputs or real time information. # # This value increases for each node and indicates the value at which a node's own internal state value increments. # e.g. the first instance of this node type will increment its state value by 1, the second instance of it by 2, # and so on... step = 1 # Defining this method, in conjunction with adding the "state" section in the .ogn file, tells OmniGraph that you # intend to maintain opaque internal state information on your node. OmniGraph will ensure that your node is not # scheduled for evaluation in such a way that it would compromise the thread-safety of your node due to this state # information, however you are responsible for updating the values and/or maintaining your own dirty bits when # required. @staticmethod def internal_state(): """Returns an object that will contain per-node state information""" return OgnTutorialStatePyInternalState() @staticmethod def compute(db) -> bool: """Compute the output based on inputs and internal state""" # This illustrates how internal state and inputs can be used in conjunction. The inputs can be used # to divert to a different computation path. if db.inputs.override: db.outputs.monotonic = db.inputs.overrideValue else: # OmniGraph ensures that the database contains the correct internal state information for the node # being evaluated. Beyond that it has no knowledge of the data within that state. db.outputs.monotonic = db.internal_state.increment_value # Update the node's internal state data for the next evaluation. db.internal_state.update_state() return True
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial13/tutorial13.rst
.. _ogn_tutorial_state_py: Tutorial 13 - Python State Node =============================== This node illustrates how you can use internal state information, so long as you inform OmniGraph that you are doing so in order for it to make more intelligent execution scheduling decisions. OgnTutorialStatePy.ogn ---------------------- The *.ogn* file containing the implementation of a node named "omni.graph.tutorials.StatePy", with an empty state set to inform OmniGraph of its intention to compute using internal state information. .. literalinclude:: OgnTutorialStatePy.ogn :linenos: :language: json OgnTutorialStatePy.py --------------------- The *.py* file contains the compute method and the internal state information used to run the algorithm. By overriding the special method ``internal_state`` you can define an object that will contain per-node data that you can manage yourself. It will not be visible to OmniGraph. .. literalinclude:: OgnTutorialStatePy.py :linenos: :language: python
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial13/OgnTutorialStatePy.ogn
{ "StatePy" : { "version": 1, "categories": "tutorials", "description": [ "This is a tutorial node. It makes use of internal state information", "to continuously increment an output." ], "language": "python", "metadata": { "uiName": "Tutorial Python Node: Internal States" }, "state": { "$comment": "The existence of this state section, even if it contains no attributes, means there is internal state that is entirely managed by the node" }, "inputs": { "overrideValue": { "type": "int64", "description": "Value to use instead of the monotonically increasing internal one when 'override' is true", "default": 0 }, "override": { "type": "bool", "description": "When true get the output from the overrideValue, otherwise use the internal value", "default": false } }, "outputs": { "monotonic": { "type": "int64", "description": "Monotonically increasing output, set by internal state information", "default": 0 } }, "tests": [ { "inputs:overrideValue": 5, "inputs:override": true, "outputs:monotonic": 5 } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/OgnTutorialExtendedTypesPy.ogn
{ "ExtendedTypesPy": { "version": 1, "categories": "tutorials", "description": [ "This is a tutorial node. It exercises functionality for the manipulation of the extended", "attribute types. It is identical to OgnTutorialExtendedTypes.ogn, except the language of", "implementation is selected to be python." ], "language": "python", "uiName": "Tutorial Python Node: Extended Attribute Types", "inputs": { "floatOrToken": { "$comment": [ "Support for a union of types is noted by putting a list into the attribute type.", "Each element of the list must be a legal attribute type from the supported type list." ], "type": ["float", "token"], "description": "Attribute that can either be a float value or a token value", "uiName": "Float Or Token", "unvalidated": true }, "toNegate": { "$comment": "An example showing that array and tuple types are also legal members of a union.", "type": ["bool[]", "float[]"], "description": "Attribute that can either be an array of booleans or an array of floats", "uiName": "To Negate", "unvalidated": true }, "tuple": { "$comment": "Tuple types are also allowed, implemented as 'any' to show similarities", "type": "any", "description": "Variable size/type tuple values", "uiName": "Tuple Values", "unvalidated": true }, "flexible": { "$comment": "You don't even have to have the same shape of data in a union", "type": ["float[3][]", "token"], "description": "Flexible data type input", "uiName": "Flexible Values", "unvalidated": true } }, "outputs": { "doubledResult": { "type": "any", "description": ["If the input 'floatOrToken' is a float this is 2x the value.", "If it is a token this contains the input token repeated twice." ], "uiName": "Doubled Input Value", "unvalidated": true }, "negatedResult": { "type": ["bool[]", "float[]"], "description": "Result of negating the data from the 'toNegate' input", "uiName": "Negated Array Values", "unvalidated": true }, "tuple": { "type": "any", "description": "Negated values of the tuple input", "uiName": "Negative Tuple Values", "unvalidated": true }, "flexible": { "type": ["float[3][]", "token"], "description": "Flexible data type output", "uiName": "Inverted Flexible Values", "unvalidated": true } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/OgnTutorialExtendedTypesPy.py
""" Implementation of the Python node accessing attributes whose type is determined at runtime. This class exercises access to the DataModel through the generated database class for all simple data types. """ import omni.graph.core as og # Hardcode each of the expected types for easy comparison FLOAT_TYPE = og.Type(og.BaseDataType.FLOAT) TOKEN_TYPE = og.Type(og.BaseDataType.TOKEN) BOOL_ARRAY_TYPE = og.Type(og.BaseDataType.BOOL, array_depth=1) FLOAT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, array_depth=1) FLOAT3_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3) INT2_TYPE = og.Type(og.BaseDataType.INT, tuple_count=2) FLOAT3_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1) class OgnTutorialExtendedTypesPy: """Exercise the runtime data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialExtendedTypes.cpp. It follows the same code pattern for easier comparison, though in practice you would probably code Python nodes differently from C++ nodes to take advantage of the strengths of each language. """ def __compare_resolved_types(input_attribute, output_attribute) -> og.Type: """Returns the resolved type if they are the same, outputs a warning and returns None otherwise""" resolved_input_type = input_attribute.type resolved_output_type = output_attribute.type if resolved_input_type != resolved_output_type: db.log_warn(f"Resolved types do not match {resolved_input_type} -> {resolved_output_type}") return None return resolved_input_type if resolved_input_type.base_type != og.BaseDataType.UNKNOWN else None # --------------------------------------------------------------------------------------------------- def _compute_simple_values(): """Perform the first algorithm on the simple input data types""" # Unlike C++ code the Python types are flexible so you must check the data types to do the right thing. # This works out better when the operation is the same as you don't even have to check the data type. In # this case the "doubling" operation is slightly different for floats and tokens. resolved_type = __compare_resolved_types(db.inputs.floatOrToken, db.outputs.doubledResult) if resolved_type == FLOAT_TYPE: db.outputs.doubledResult.value = db.inputs.floatOrToken.value * 2.0 elif resolved_type == TOKEN_TYPE: db.outputs.doubledResult.value = db.inputs.floatOrToken.value + db.inputs.floatOrToken.value # A Pythonic way to do the same thing by just applying an operation and checking for compatibility is: # try: # db.outputs.doubledResult = db.inputs.floatOrToken * 2.0 # except TypeError: # # Gets in here for token types since multiplying string by float is not legal # db.outputs.doubledResult = db.inputs.floatOrToken + db.inputs.floatOrToken return True # --------------------------------------------------------------------------------------------------- def _compute_array_values(): """Perform the second algorithm on the array input data types""" resolved_type = __compare_resolved_types(db.inputs.toNegate, db.outputs.negatedResult) if resolved_type == BOOL_ARRAY_TYPE: db.outputs.negatedResult.value = [not value for value in db.inputs.toNegate.value] elif resolved_type == FLOAT_ARRAY_TYPE: db.outputs.negatedResult.value = [-value for value in db.inputs.toNegate.value] return True # --------------------------------------------------------------------------------------------------- def _compute_tuple_values(): """Perform the third algorithm on the 'any' data types""" resolved_type = __compare_resolved_types(db.inputs.tuple, db.outputs.tuple) # Notice how, since the operation is applied the same for both recognized types, the # same code can handle both of them. if resolved_type in (FLOAT3_TYPE, INT2_TYPE): db.outputs.tuple.value = tuple(-x for x in db.inputs.tuple.value) # An unresolved type is a temporary state and okay, resolving to unsupported types means the graph is in # an unsupported configuration that needs to be corrected. elif resolved_type is not None: type_name = resolved_type.get_type_name() db.log_error(f"Only float[3] and int[2] types are supported by this node, not {type_name}") return False return True # --------------------------------------------------------------------------------------------------- def _compute_flexible_values(): """Perform the fourth algorithm on the multi-shape data types""" resolved_type = __compare_resolved_types(db.inputs.flexible, db.outputs.flexible) if resolved_type == FLOAT3_ARRAY_TYPE: db.outputs.flexible.value = [(-x, -y, -z) for (x, y, z) in db.inputs.flexible.value] elif resolved_type == TOKEN_TYPE: db.outputs.flexible.value = db.inputs.flexible.value[::-1] return True # --------------------------------------------------------------------------------------------------- compute_success = _compute_simple_values() compute_success = _compute_array_values() and compute_success compute_success = _compute_tuple_values() and compute_success compute_success = _compute_flexible_values() and compute_success # --------------------------------------------------------------------------------------------------- # As Python has a much more flexible typing system it can do things in a few lines that require a lot # more in C++. One such example is the ability to add two arbitrary data types. Here is an example of # how, using "any" type inputs "a", and "b", with an "any" type output "result" you can generically # add two elements without explicitly checking the type, failing only when Python cannot support # the operation. # # try: # db.outputs.result = db.inputs.a + db.inputs.b # return True # except TypeError: # a_type = inputs.a.type().get_type_name() # b_type = inputs.b.type().get_type_name() # db.log_error(f"Cannot add attributes of type {a_type} and {b_type}") # return False return True @staticmethod def on_connection_type_resolve(node) -> None: # There are 4 sets of type-coupled attributes in this node, meaning that the base_type of the attributes # must be the same for the node to function as designed. # 1. floatOrToken <-> doubledResult # 2. toNegate <-> negatedResult # 3. tuple <-> tuple # 4. flexible <-> flexible # # The following code uses a helper function to resolve the attribute types of the coupled pairs. Note that # without this logic a chain of extended-attribute connections may result in a non-functional graph, due to # the requirement that types be resolved before graph evaluation, and the ambiguity of the graph without knowing # how the types are related. og.resolve_fully_coupled( [node.get_attribute("inputs:floatOrToken"), node.get_attribute("outputs:doubledResult")] ) og.resolve_fully_coupled([node.get_attribute("inputs:toNegate"), node.get_attribute("outputs:negatedResult")]) og.resolve_fully_coupled([node.get_attribute("inputs:tuple"), node.get_attribute("outputs:tuple")]) og.resolve_fully_coupled([node.get_attribute("inputs:flexible"), node.get_attribute("outputs:flexible")])
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/OgnTutorialExtendedTypes.cpp
// 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. // #include <OgnTutorialExtendedTypesDatabase.h> #include <algorithm> // // Attributes whose data types resolve at runtime ("any" or "union" types) are resolved by having connections made // to them of a resolved type. Say you have a chain of A->B->C where B has inputs and outputs of these types. The // connection from A->B will determine the type of data at B's input and the connection B->C will determine the type // of data at B's output (assuming A's outputs and C's inputs are well-defined types). // // For this reason it is the node's responsibility to verify the type resolution of the attributes as part of the // compute method. Any unresolved types (db.Xputs.attrName().resolved() == false) that are required by the compute // should result in a warning and compute failure. Any attributes resolved to incompatible types, for example an input // that resolves to a string where a number is needed, should also result in a warning and compute failure. // // It is up to the node to decide how flexible the resolution requirements are to be. In the string/number case above // the node may choose to parse the string as a number instead of failing, or using the length of the string as the // input number. The only requirement from OmniGraph is that the node handle all of the resolution types it has // claimed it will handle in the .ogn file. "any" attributes must handle all data types, even if some types result in // warnings or errors. "union" attributes must handle all types specified in the union. // class OgnTutorialExtendedTypes { public: static bool compute(OgnTutorialExtendedTypesDatabase& db) { bool computedOne = false; auto typeWarning = [&](const char* message, const Type& type1, const Type& type2) { db.logWarning("%s (%s -> %s)", message, getOgnTypeName(type1).c_str(), getOgnTypeName(type2).c_str()); }; auto typeError = [&](const char* message, const Type& type1, const Type& type2) { db.logError("%s (%s -> %s)", message, getOgnTypeName(type1).c_str(), getOgnTypeName(type2).c_str()); }; auto computeSimpleValues = [&]() { // ==================================================================================================== // Compute for the union types that resolve to simple values. // Accepted value types are floats and tokens. As these were the only types specified in the union definition // the node does not have to worry about other numeric types, such as int or double. // The node can decide what the meaning of an attempt to compute with unresolved types is. // For this particular node they are treated as silent success. const auto& floatOrToken = db.inputs.floatOrToken(); auto& doubledResult = db.outputs.doubledResult(); if (floatOrToken.resolved() && doubledResult.resolved()) { // Check for an exact type match for the input and output if (floatOrToken.type() != doubledResult.type()) { // Mismatched types are possible, and result in no compute typeWarning("Simple resolved types do not match", floatOrToken.type(), doubledResult.type()); return false; } // When extracting extended types the templated get<> method returns an object that contains the cast data. // It can be cast to a boolean for quick checks for matching types. // // Note: The single "=" in these if statements is intentional. It facilitates one-line set-and-test of the // typed values. // if (auto floatValue = floatOrToken.get<float>()) { // Once the existence of the cast type is verified it can be dereferenced to get at the raw data, // whose types are described in the tutorial on bundled data. if (auto doubledValue = doubledResult.get<float>()) { *doubledValue = *floatValue * 2.0f; } else { // This could be an assert because it should never happen. The types were confirmed above to match, // so they should have cast to the same types without incident. typeError("Simple types were matched as bool then failed to cast properly", floatOrToken.type(), doubledResult.type()); return false; } } else if (auto tokenValue = floatOrToken.get<OgnToken>()) { if (auto doubledValue = doubledResult.get<OgnToken>()) { std::string inputString{ db.tokenToString(*tokenValue) }; inputString += inputString; *doubledValue = db.stringToToken(inputString.c_str()); } else { // This could be an assert because it should never happen. The types were confirmed above to match, // so they should have cast to the same types without incident. typeError("Simple types were matched as token then failed to cast properly", floatOrToken.type(), doubledResult.type()); return false; } } else { // As Union types are supposed to restrict the data types being passed in to the declared types // any unrecognized types are an error, not a warning. typeError("Simple types resolved to unknown types", floatOrToken.type(), doubledResult.type()); return false; } } else { // Unresolved types are reasonable, resulting in no compute return true; } return true; }; auto computeArrayValues = [&]() { // ==================================================================================================== // Compute for the union types that resolve to arrays. // Accepted value types are arrays of bool or arrays of float, which are extracted as interfaces to // those values so that resizing can happen transparently through the fabric. // // These interfaces are similar to what you've seen in regular array attributes - they support resize(), // operator[], and range-based for loops. // const auto& toNegate = db.inputs.toNegate(); auto& negatedResult = db.outputs.negatedResult(); if (toNegate.resolved() && negatedResult.resolved()) { // Check for an exact type match for the input and output if (toNegate.type() != negatedResult.type()) { // Mismatched types are possible, and result in no compute typeWarning("Array resolved types do not match", toNegate.type(), negatedResult.type()); return false; } // Extended types can be any legal attribute type. Here the types in the extended attribute can be either // an array of booleans or an array of integers. if (auto boolArray = toNegate.get<bool[]>()) { auto valueAsBoolArray = negatedResult.get<bool[]>(); if (valueAsBoolArray) { valueAsBoolArray.resize( boolArray->size() ); size_t index{ 0 }; for (auto& value : *boolArray) { (*valueAsBoolArray)[index++] = ! value; } } else { // This could be an assert because it should never happen. The types were confirmed above to match, // so they should have cast to the same types without incident. typeError("Array types were matched as bool[] then failed to cast properly", toNegate.type(), negatedResult.type()); return false; } } else if (auto floatArray = toNegate.get<float[]>()) { auto valueAsFloatArray = negatedResult.get<float[]>(); if (valueAsFloatArray) { valueAsFloatArray.resize( floatArray->size() ); size_t index{ 0 }; for (auto& value : *floatArray) { (*valueAsFloatArray)[index++] = - value; } } else { // This could be an assert because it should never happen. The types were confirmed above to match, // so they should have cast to the same types without incident. typeError("Array types were matched as float[] then failed to cast properly", toNegate.type(), negatedResult.type()); return false; } } else { // As Union types are supposed to restrict the data types being passed in to the declared types // any unrecognized types are an error, not a warning. typeError("Array type not recognized", toNegate.type(), negatedResult.type()); return false; } } else { // Unresolved types are reasonable, resulting in no compute return true; } return true; }; auto computeTupleValues = [&]() { // ==================================================================================================== // Compute for the "any" types that only handle tuple values. In practice you'd only use "any" when the // type of data you handle is unrestricted. This is more an illustration to show how in practical use the // two types of attribute are accessed exactly the same way, the only difference is restrictions that the // OmniGraph system will put on potential connections. // // For simplicity this node will treat unrecognized type as a warning with success. // Full commentary and error checking is elided as it will be the same as for the above examples. // The algorithm for tuple values is a component-wise negation. const auto& tupleInput = db.inputs.tuple(); auto& tupleOutput = db.outputs.tuple(); if (tupleInput.resolved() && tupleOutput.resolved()) { if (tupleInput.type() != tupleOutput.type()) { typeWarning("Tuple resolved types do not match", tupleInput.type(), tupleOutput.type()); return false; } // This node will only recognize the float[3] and int[2] cases, to illustrate that tuple count and // base type are both flexible. if (auto float3Input = tupleInput.get<float[3]>()) { if (auto float3Output = tupleOutput.get<float[3]>()) { (*float3Output)[0] = -(*float3Input)[0]; (*float3Output)[1] = -(*float3Input)[1]; (*float3Output)[2] = -(*float3Input)[2]; } } else if (auto int2Input = tupleInput.get<int[2]>()) { if (auto int2Output = tupleOutput.get<int[2]>()) { (*int2Output)[0] = -(*int2Input)[0]; (*int2Output)[1] = -(*int2Input)[1]; } } else { // As "any" types are not restricted in their data types but this node is only handling two of // them an unrecognized type is just unimplemented code. typeWarning("Unimplemented type combination", tupleInput.type(), tupleOutput.type()); return true; } } else { // Unresolved types are reasonable, resulting in no compute return true; } return true; }; auto computeFlexibleValues = [&]() { // ==================================================================================================== // Complex union type that handles both simple values and an array of tuples. It illustrates how the // data types in a union do not have to be related in any way. // // Full commentary and error checking is elided as it will be the same as for the above examples. // The algorithm for tuple array values is to negate everything in the float3 array values, and to reverse // the string for string values. const auto& flexibleInput = db.inputs.flexible(); auto& flexibleOutput = db.outputs.flexible(); if (flexibleInput.resolved() && flexibleOutput.resolved()) { if (flexibleInput.type() != flexibleOutput.type()) { typeWarning("Flexible resolved types do not match", flexibleInput.type(), flexibleOutput.type()); return false; } // Arrays of tuples are handled with the same interface as with normal attributes. if (auto float3ArrayInput = flexibleInput.get<float[][3]>()) { if (auto float3ArrayOutput = flexibleOutput.get<float[][3]>()) { float3ArrayOutput.resize( float3ArrayInput.size() ); size_t index{ 0 }; for (auto& value : *float3ArrayInput) { (*float3ArrayOutput)[index][0] = - value[0]; (*float3ArrayOutput)[index][1] = - value[1]; (*float3ArrayOutput)[index][2] = - value[2]; index++; } } } else if (auto tokenInput = flexibleInput.get<OgnToken>()) { if (auto tokenOutput = flexibleOutput.get<OgnToken>()) { std::string toReverse{ db.tokenToString(*tokenInput) }; std::reverse( toReverse.begin(), toReverse.end() ); *tokenOutput = db.stringToToken(toReverse.c_str()); } } else { typeError("Unrecognized type combination", flexibleInput.type(), flexibleOutput.type()); return false; } } else { // Unresolved types are reasonable, resulting in no compute return true; } return true; }; // This approach lets either section fail while still computing the other. computedOne = computeSimpleValues(); computedOne = computeArrayValues() || computedOne; computedOne = computeTupleValues() || computedOne; computedOne = computeFlexibleValues() || computedOne; if (! computedOne) { db.logWarning("None of the inputs had resolved type, resulting in no compute"); } return ! computedOne; } static void onConnectionTypeResolve(const NodeObj& nodeObj) { // The attribute types resolve in pairs AttributeObj pairs[][2] { { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::floatOrToken.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::doubledResult.token()) }, { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::toNegate.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::negatedResult.token()) }, { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::tuple.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::tuple.token()) }, { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::flexible.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::flexible.token()) } }; for (auto& pair : pairs) { nodeObj.iNode->resolveCoupledAttributes(nodeObj, &pair[0], 2); } } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/tutorial19.rst
.. _ogn_tutorial_extended_types: Tutorial 19 - Extended Attribute Types ====================================== Extended attribute types are so-named because they extend the types of data an attribute can accept from one type to several types. Extended attributes come in two flavours. The _any_ type is the most flexible. It allows a connection with any other attribute type: .. code-block:: json :emphasize-lines: 4 "inputs": { "myAnyAttribute": { "description": "Accepts an incoming connection from any type of attribute", "type": "any", } } The union type, represented as an array of type names, allows a connection from a limited subset of attribute types. Here's one that can connect to attributes of type _float[3]_ and _double[3]_: .. code-block:: json :emphasize-lines: 4 "inputs": { "myUnionAttribute": { "description": "Accepts an incoming connection from attributes with a vector of a 3-tuple of numbers", "type": ["float[3]", "double[3]"], } } .. note:: "union" is not an actual type name, as the type names are specified by a list. It is just the nomenclature used for the set of all attributes that can be specified in this way. More details about union types can be found in :ref:`ogn_attribute_types`. As you will see in the code examples, the value extracted from the database for such attributes has to be checked for the actual resolved data type. Until an extended attribute is connected its data type will be unresolved and it will not have a value. For this reason _"default"_ values are not allowed on extended attributes. OgnTutorialExtendedTypes.ogn ---------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.ExtendedTypes", which has inputs and outputs with the extended attribute types. .. literalinclude:: OgnTutorialExtendedTypes.ogn :linenos: :language: json OgnTutorialExtendedTypes.cpp ---------------------------- The *cpp* file contains the implementation of the compute method. It illustrates how to determine and set the data types on extended attribute types. .. literalinclude:: OgnTutorialExtendedTypes.cpp :linenos: :language: c++ Information on the raw types extracted from the extended type values can be seen in :ref:`ogn_tutorial_bundle_data`. OgnTutorialExtendedTypesPy.py ----------------------------- This is a Python version of the above C++ node with exactly the same set of attributes and the same algorithm. It shows the parallels between manipulating extended attribute types in both languages. (The .ogn file is omitted for brevity, being identical to the previous one save for the addition of a ``"language": "python"`` property. .. literalinclude:: OgnTutorialExtendedTypesPy.py :linenos: :language: python
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/OgnTutorialExtendedTypes.ogn
{ "ExtendedTypes": { "version": 1, "categories": "tutorials", "scheduling": ["threadsafe"], "description": ["This is a tutorial node. It exercises functionality for the manipulation of the extended", "attribute types." ], "uiName": "Tutorial Node: Extended Attribute Types", "inputs": { "floatOrToken": { "$comment": [ "Support for a union of types is noted by putting a list into the attribute type.", "Each element of the list must be a legal attribute type from the supported type list." ], "type": ["float", "token"], "description": "Attribute that can either be a float value or a token value", "uiName": "Float Or Token", "unvalidated": true }, "toNegate": { "$comment": "An example showing that array and tuple types are also legal members of a union.", "type": ["bool[]", "float[]"], "description": "Attribute that can either be an array of booleans or an array of floats", "uiName": "To Negate", "unvalidated": true }, "tuple": { "$comment": "Tuple types are also allowed, implemented as 'any' to show similarities", "type": "any", "description": "Variable size/type tuple values", "uiName": "Tuple Values", "unvalidated": true }, "flexible": { "$comment": "You don't even have to have the same shape of data in a union", "type": ["float[3][]", "token"], "description": "Flexible data type input", "uiName": "Flexible Values", "unvalidated": true } }, "outputs": { "doubledResult": { "type": "any", "description": ["If the input 'simpleInput' is a float this is 2x the value.", "If it is a token this contains the input token repeated twice." ], "uiName": "Doubled Input Value", "unvalidated": true }, "negatedResult": { "type": ["bool[]", "float[]"], "description": "Result of negating the data from the 'toNegate' input", "uiName": "Negated Array Values", "unvalidated": true }, "tuple": { "type": "any", "description": "Negated values of the tuple input", "uiName": "Negative Tuple Values", "unvalidated": true }, "flexible": { "type": ["float[3][]", "token"], "description": "Flexible data type output", "uiName": "Inverted Flexible Values", "unvalidated": true } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/tutorial23.rst
.. _ogn_tutorial_cpu_gpu_extended: Tutorial 23 - Extended Attributes On The GPU ============================================ Extended attributes are no different from other types of attributes with respect to where their memory will be located. The difference is that there is a slightly different API for accessing their data, illustrating by these examples. This node also illustrates the new concept of having a node create an ABI function override that handles the runtime type resolution of extended attribute types. In this case when any of the two input attributes or one output attribute become resolved then the other two attributes are resolved to the same type, if possible. OgnTutorialCpuGpuExtended.ogn ----------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CpuGpuExtended" with an input **'any'** attribute on the CPU, an input **'any'** attribute on the GPU, and an output whose memory location is decided at runtime by a boolean. .. literalinclude:: OgnTutorialCpuGpuExtended.ogn :linenos: :language: json OgnTutorialCpuGpuExtended.cpp ----------------------------- The *cpp* file contains the implementation of the compute method. It sums two inputs on either the CPU or GPU based on the input boolean. For simplicity only the **float[3][]** attribute type is processed, with all others resulting in a compute failure. .. literalinclude:: OgnTutorialCpuGpuExtended.cpp :linenos: :language: c++ OgnTutorialCpuGpuExtendedPy.py ------------------------------ The *py* file contains the same algorithm as the C++ node, with the node implementation language being different. .. literalinclude:: OgnTutorialCpuGpuExtendedPy.py :linenos: :language: python
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/OgnTutorialCpuGpuExtended.ogn
{ "CpuGpuExtended": { "version": 1, "categories": "tutorials", "description": [ "This is a tutorial node. It exercises functionality for accessing data in extended attributes that", "are on the GPU as well as those whose CPU/GPU location is decided at runtime. The compute", "adds the two inputs 'gpuData' and 'cpuData' together, placing the result in `cpuGpuSum`, whose", "memory location is determined by the 'gpu' flag.", "This node is identical to OgnTutorialCpuGpuExtendedPy.ogn, except is is implemented in C++." ], "tags": ["tutorial", "extended", "gpu"], "uiName": "Tutorial Node: CPU/GPU Extended Attributes", "inputs": { "cpuData": { "type": "any", "description": "Input attribute whose data always lives on the CPU", "uiName": "CPU Input Attribute" }, "gpuData": { "type": "any", "memoryType": "cuda", "description": "Input attribute whose data always lives on the GPU", "uiName": "GPU Input Attribute" }, "gpu": { "type": "bool", "description": "If true then put the sum on the GPU, otherwise put it on the CPU", "uiName": "Results To GPU" } }, "outputs": { "cpuGpuSum": { "type": "any", "memoryType": "any", "description": [ "This is the attribute with the selected data. If the 'gpu' attribute is set to true then this", "attribute's contents will be entirely on the GPU, otherwise it will be on the CPU." ], "uiName": "Sum" } }, "tests": [ { "inputs:cpuData": { "type": "pointf[3][]", "value": [ [ 1.0, 2.0, 3.0 ], [ 4.0, 5.0, 6.0 ] ] }, "inputs:gpuData": { "type": "pointf[3][]", "value": [ [ 7.0, 8.0, 9.0 ], [ 10.0, 11.0, 12.0 ] ] }, "inputs:gpu": false, "outputs:cpuGpuSum": { "type": "pointf[3][]", "value": [ [ 8.0, 10.0, 12.0 ], [ 14.0, 16.0, 18.0 ] ] } }, { "inputs:cpuData": { "type": "pointf[3][]", "value": [ [ 4.0, 5.0, 6.0 ] ] }, "inputs:gpuData": { "type": "pointf[3][]", "value": [ [ 7.0, 8.0, 9.0 ] ] }, "inputs:gpu": true, "outputs:cpuGpuSum": { "type": "pointf[3][]", "value": [ [ 11.0, 13.0, 15.0 ] ] } } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/OgnTutorialCpuGpuExtendedPy.ogn
{ "CpuGpuExtendedPy": { "version": 1, "categories": "tutorials", "description": [ "This is a tutorial node. It exercises functionality for accessing data in extended attributes that", "are on the GPU as well as those whose CPU/GPU location is decided at runtime. The compute", "adds the two inputs 'gpuData' and 'cpuData' together, placing the result in `cpuGpuSum`, whose", "memory location is determined by the 'gpu' flag.", "This node is identical to OgnTutorialCpuGpuExtended.ogn, except is is implemented in Python." ], "language": "python", "tags": ["tutorial", "extended", "gpu"], "uiName": "Tutorial Python Node: CPU/GPU Extended Attributes", "inputs": { "cpuData": { "type": "any", "description": "Input attribute whose data always lives on the CPU", "uiName": "CPU Input Attribute" }, "gpuData": { "type": "any", "memoryType": "cuda", "description": "Input attribute whose data always lives on the GPU", "uiName": "GPU Input Attribute" }, "gpu": { "type": "bool", "description": "If true then put the sum on the GPU, otherwise put it on the CPU", "uiName": "Results To GPU" } }, "outputs": { "cpuGpuSum": { "type": "any", "memoryType": "any", "description": [ "This is the attribute with the selected data. If the 'gpu' attribute is set to true then this", "attribute's contents will be entirely on the GPU, otherwise it will be on the CPU." ], "uiName": "Sum" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/OgnTutorialCpuGpuExtended.cpp
// 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. // #include <OgnTutorialCpuGpuExtendedDatabase.h> extern "C" void cpuGpuSumCPU(float const(*p1)[3], float const(*p2)[3], float(*sums)[3], size_t); extern "C" void cpuGpuSumGPU(float const (**p1)[3], float const (**p2)[3], float(**sums)[3]); namespace omni { namespace graph { namespace tutorials { // Only the pointf[3][] type is accepted. Make a shortcut to the type information describing it for comparison core::Type acceptedType(core::BaseDataType::eFloat, 3, 1, core::AttributeRole::ePosition); // Template for reporting type inconsistencies. The data types are different for the attributes but the checks are // the same so this avoids duplication template <typename P1, typename P2, typename P3> bool verifyDataTypes(OgnTutorialCpuGpuExtendedDatabase& db, const P1& points1, const P2& points2, P3& sums, const char* type) { if (! points1) { db.logWarning("Skipping compute - The %s attribute was not a valid pointf[3][]", type); } else if (! points2) { db.logWarning("Skipping compute - The %s attribute was not a valid pointf[3][]", type); } else if (! sums) { db.logWarning("Skipping compute - The %s output attribute was not a valid pointf[3][]", type); } else if (points1.size() != points2.size()) { db.logWarning("Skipping compute - Point arrays are different sizes (%zu and %zu)", points1.size(), points2.size()); } else { sums.resize(points1.size()); return true; } return false; } class OgnTutorialCpuGpuExtended { bool m_allAttributesResolved{ false }; public: static bool compute(OgnTutorialCpuGpuExtendedDatabase& db) { if (! db.sharedState<OgnTutorialCpuGpuExtended>().m_allAttributesResolved) { db.logWarning("All types are not yet resolved. Cannot run the compute."); return false; } const auto& gpu = db.inputs.gpu(); const auto cpuData = db.inputs.cpuData(); const auto gpuData = db.inputs.gpuData(); auto cpuGpuSum = db.outputs.cpuGpuSum(); if ((cpuData.type() != acceptedType) || (gpuData.type() != acceptedType) || (cpuGpuSum.type() != acceptedType)) { db.logWarning("Skipping compute - All of the attributes do not have the accepted resolved type pointf[3][]"); return false; } if (gpu) { // Computation on the GPU has been requested so get the GPU versions of the attribute data const auto points1 = cpuData.getGpu<float[][3]>(); const auto points2 = gpuData.get<float[][3]>(); auto sums = cpuGpuSum.getGpu<float[][3]>(); if (!verifyDataTypes(db, points1, points2, sums, "GPU")) { return false; } cpuGpuSumGPU(points1(), points2(), sums()); } else { // Computation on the CPU has been requested so get the CPU versions of the attribute data const auto points1 = cpuData.get<float[][3]>(); const auto points2 = gpuData.getCpu<float[][3]>(); auto sums = cpuGpuSum.getCpu<float[][3]>(); if (!verifyDataTypes(db, points1, points2, sums, "CPU")) { return false; } cpuGpuSumCPU(points1->data(), points2->data(), sums->data(), points1.size()); } return true; } static void onConnectionTypeResolve(const NodeObj& nodeObj) { // If any one type is resolved the others should resolve to the same type. Calling this helper function // makes that happen automatically. If it returns false then the resolution failed for some reason. The // node's user data, which is just a copy of this class, is used to keep track of the resolution state so // that the compute method can quickly exit when the types are not resolved. AttributeObj attributes[3] { nodeObj.iNode->getAttributeByToken(nodeObj, inputs::cpuData.token()), nodeObj.iNode->getAttributeByToken(nodeObj, inputs::gpuData.token()), nodeObj.iNode->getAttributeByToken(nodeObj, outputs::cpuGpuSum.token()) }; auto& state = OgnTutorialCpuGpuExtendedDatabase::sInternalState<OgnTutorialCpuGpuExtended>(nodeObj); state.m_allAttributesResolved = nodeObj.iNode->resolveCoupledAttributes(nodeObj, attributes, 3); } }; REGISTER_OGN_NODE() } // namespace tutorials } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/OgnTutorialCpuGpuExtendedPy.py
""" Implementation of the Python node accessing extended attributes whose memory location is determined at runtime. """ import omni.graph.core as og # Only one type of data is handled by the compute - pointf[3][] POINT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION) class OgnTutorialCpuGpuExtendedPy: """Exercise GPU access for extended attributes through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialCpuGpuExtended.cpp. It follows the same code pattern for easier comparison, though in practice you would probably code Python nodes differently from C++ nodes to take advantage of the strengths of each language. """ # Find and verify the attributes containing the points if db.attributes.inputs.cpuData.get_resolved_type() != POINT_ARRAY_TYPE: db.log_warning("Skipping compute - CPU attribute type did not resolve to pointf[3][]") return False if db.attributes.inputs.gpuData.get_resolved_type() != POINT_ARRAY_TYPE: db.log_warning("Skipping compute - GPU attribute type did not resolve to pointf[3][]") return False if db.attributes.outputs.cpuGpuSum.get_resolved_type() != POINT_ARRAY_TYPE: db.log_warning("Skipping compute - Sum attribute type did not resolve to pointf[3][]") return False # Put accessors into local variables for convenience gpu_data = db.inputs.gpuData cpu_data = db.inputs.cpuData sums = db.outputs.cpuGpuSum # Mismatched sizes cannot be computed if gpu_data.size != cpu_data.size: db.log_warning(f"Skipping compute - Point arrays are different sizes ({gpu_data.size} and {cpu_data.size})") # Set the size to what is required for the dot product calculation sums.size = cpu_data.size # Use the correct data access based on whether the output is supposed to be on the GPU or not if db.inputs.gpu: # The second line is how the values would be extracted if Python supported GPU data extraction. # When it does this tutorial will be updated sums.cpu_value = cpu_data.value + gpu_data.cpu_value # sums.gpu_value = cpu_data.gpu_value + gpu_data.value else: sums.cpu_value = cpu_data.value + gpu_data.cpu_value return True @staticmethod def on_connection_type_resolve(node: og.Node) -> None: """Whenever any of the inputs or the output get a resolved type the others should get the same resolution""" attribs = [ node.get_attribute("inputs:cpuData"), node.get_attribute("inputs:gpuData"), node.get_attribute("outputs:cpuGpuSum"), ] og.resolve_fully_coupled(attribs)
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/OgnTutorialCpuGpuBundles.ogn
{ "CpuGpuBundles": { "version": 1, "categories": "tutorials", "description": [ "This is a tutorial node. It exercises functionality for accessing data in bundles that", "are on the GPU as well as bundles whose CPU/GPU location is decided at runtime. The", "compute looks for bundled attributes named 'points' and, if they are found, computes", "their dot products. If the bundle on the output contains an integer array type named", "'dotProducts' then the results are placed there, otherwise a new attribute of that name and", "type is created on the output bundle to hold the results.", "This node is identical to OgnTutorialCpuGpuBundlesPy.ogn, except it is implemented in C++." ], "tags": ["tutorial", "bundle", "gpu"], "tokens": ["points", "dotProducts"], "uiName": "Tutorial Node: CPU/GPU Bundles", "inputs": { "cpuBundle": { "type": "bundle", "description": "Input bundle whose data always lives on the CPU", "uiName": "CPU Input Bundle" }, "gpuBundle": { "type": "bundle", "memoryType": "cuda", "description": "Input bundle whose data always lives on the GPU", "uiName": "GPU Input Bundle" }, "gpu": { "type": "bool", "description": "If true then copy gpuBundle onto the output, otherwise copy cpuBundle", "uiName": "Results To GPU" } }, "outputs": { "cpuGpuBundle": { "type": "bundle", "memoryType": "any", "description": [ "This is the bundle with the merged data. If the 'gpu' attribute is set to true then this", "bundle's contents will be entirely on the GPU, otherwise they will be on the CPU." ], "uiName": "Constructed Bundle" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/OgnTutorialCpuGpuBundlesPy.py
""" Implementation of the Python node accessing attributes whose memory location is determined at runtime. """ import numpy as np import omni.graph.core as og # Types to check on bundled attributes FLOAT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, array_depth=1) FLOAT3_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION) class OgnTutorialCpuGpuBundlesPy: """Exercise bundle members through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialCpuGpuBundles.cpp. It follows the same code pattern for easier comparison, though in practice you would probably code Python nodes differently from C++ nodes to take advantage of the strengths of each language. """ if db.inputs.gpu: # Invalid data yields no compute if not db.inputs.gpuBundle.valid: return True db.outputs.cpuGpuBundle = db.inputs.gpuBundle else: if not db.inputs.cpuBundle.valid: return True db.outputs.cpuGpuBundle = db.inputs.cpuBundle # Find and verify the attributes containing the points cpu_points = db.inputs.cpuBundle.attribute_by_name(db.tokens.points) if cpu_points.type != FLOAT3_ARRAY_TYPE: db.log_warning( f"Skipping compute - No valid float[3][] attribute named '{db.tokens.points}' on the CPU bundle" ) return False gpu_points = db.inputs.gpuBundle.attribute_by_name(db.tokens.points) if gpu_points.type != FLOAT3_ARRAY_TYPE: db.log_warning( f"Skipping compute - No valid float[3][] attribute named '{db.tokens.points}' on the GPU bundle" ) return False # If the attribute is not already on the output bundle then add it dot_product = db.outputs.cpuGpuBundle.attribute_by_name(db.tokens.dotProducts) if dot_product is None: dot_product = db.outputs.cpuGpuBundle.insert((og.Type(og.BaseDataType.FLOAT, array_depth=1), "dotProducts")) elif dot_product.type != FLOAT_ARRAY_TYPE: # Python types do not use a cast to find out if they are the correct type so explicitly check it instead db.log_warning( f"Skipping compute - No valid float[] attribute named '{db.tokens.dotProducts}' on the output bundle" ) return False # Set the size to what is required for the dot product calculation dot_product.size = cpu_points.size # Use the correct data access based on whether the output is supposed to be on the GPU or not if db.inputs.gpu: # The second line is how the values would be extracted if Python supported GPU data extraction. # When it does this tutorial will be updated dot_product.cpu_value = np.einsum("ij,ij->i", cpu_points.value, gpu_points.cpu_value) # dot_product.gpu_value = np.einsum("ij,ij->i", cpu_points.gpu_value, gpu_points.value) else: dot_product.cpu_value = np.einsum("ij,ij->i", cpu_points.value, gpu_points.cpu_value) return True
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/OgnTutorialCpuGpuBundlesPy.ogn
{ "CpuGpuBundlesPy": { "version": 1, "categories": "tutorials", "description": [ "This is a tutorial node. It exercises functionality for accessing data in bundles that", "are on the GPU as well as bundles whose CPU/GPU location is decided at runtime. The", "compute looks for bundled attributes named 'points' and, if they are found, computes", "the dot products. If the bundle on the output contains an integer array type named", "'dotProducts' then the results are placed there, otherwise a new attribute of that name and", "type is created on the output bundle to hold the results.", "This node is identical to OgnTutorialCpuGpuBundles.ogn, except is is implemented in Python." ], "language": "python", "tags": ["tutorial", "bundle", "gpu"], "tokens": ["points", "dotProducts"], "uiName": "Tutorial Python Node: CPU/GPU Bundles", "inputs": { "cpuBundle": { "type": "bundle", "description": "Input bundle whose data always lives on the CPU", "uiName": "CPU Input Bundle" }, "gpuBundle": { "type": "bundle", "memoryType": "cuda", "description": "Input bundle whose data always lives on the GPU", "uiName": "GPU Input Bundle" }, "gpu": { "type": "bool", "description": "If true then copy gpuBundle onto the output, otherwise copy cpuBundle", "uiName": "Results To GPU" } }, "outputs": { "cpuGpuBundle": { "type": "bundle", "memoryType": "any", "description": [ "This is the bundle with the merged data. If the 'gpu' attribute is set to true then this", "bundle's contents will be entirely on the GPU, otherwise it will be on the CPU." ], "uiName": "Constructed Bundle" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/OgnTutorialCpuGpuBundles.cpp
// 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. // #include <OgnTutorialCpuGpuBundlesDatabase.h> extern "C" void cpuGpuDotProductCPU(float const(*p1)[3], float const(*p2)[3], float*, size_t); extern "C" void cpuGpuDotProductGPU(float const (**p1)[3], float const (**p2)[3], float**, size_t); namespace omni { namespace graph { namespace tutorials { class OgnTutorialCpuGpuBundles { public: static bool compute(OgnTutorialCpuGpuBundlesDatabase& db) { const auto& gpu = db.inputs.gpu(); // Bundles are merely abstract representations of a collection of attributes so you don't have to do anything // different when they are marked for GPU, or ANY memory location. const auto& cpuBundle = db.inputs.cpuBundle(); const auto& gpuBundle = db.inputs.gpuBundle(); auto& outputBundle = db.outputs.cpuGpuBundle(); // Assign the correct destination bundle to the output based on the gpu flag if (gpu) { outputBundle = gpuBundle; } else { outputBundle = cpuBundle; } // Get the attribute references. They're the same whether the bundles are on the CPU or GPU const auto pointsCpuAttribute = cpuBundle.attributeByName(db.tokens.points); const auto pointsGpuAttribute = gpuBundle.attributeByName(db.tokens.points); auto dotProductAttribute = outputBundle.attributeByName(db.tokens.dotProducts); if (! dotProductAttribute.isValid()) { dotProductAttribute = outputBundle.addAttribute(db.tokens.dotProducts, Type(BaseDataType::eFloat, 1, 1)); } // Find the bundle contents to be processed if (gpu) { const auto points1 = pointsCpuAttribute.getGpu<float[][3]>(); const auto points2 = pointsGpuAttribute.get<float[][3]>(); auto dotProducts = dotProductAttribute.getGpu<float[]>(); if (! points1) { db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the CPU bundle", db.tokenToString(db.tokens.points)); return false; } if (! points2) { db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the GPU bundle", db.tokenToString(db.tokens.points)); return false; } if (points1.size() != points2.size()) { db.logWarning("Skipping compute - Point arrays are different sizes (%zu and %zu)", points1.size(), points2.size()); return false; } dotProducts.resize(points1.size()); if (! dotProducts) { db.logWarning("Skipping compute - No valid float[] attribute named '%s' on the output bundle", db.tokenToString(db.tokens.dotProducts)); return false; } cpuGpuDotProductGPU(points1(), points2(), dotProducts(), points1.size()); } else { const auto points1 = pointsCpuAttribute.get<float[][3]>(); const auto points2 = pointsGpuAttribute.getCpu<float[][3]>(); auto dotProducts = dotProductAttribute.getCpu<float[]>(); if (! points1) { db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the CPU bundle", db.tokenToString(db.tokens.points)); return false; } if (! points2) { db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the GPU bundle", db.tokenToString(db.tokens.points)); return false; } if (points1.size() != points2.size()) { db.logWarning("Skipping compute - Point arrays are different sizes (%zu and %zu)", points1.size(), points2.size()); return false; } dotProducts.resize(points1.size()); if (! dotProducts) { db.logWarning("Skipping compute - No valid dot product attribute on the output bundle"); return false; } cpuGpuDotProductCPU(points1->data(), points2->data(), dotProducts->data(), points1.size()); } return true; } }; REGISTER_OGN_NODE() } // namespace tutorials } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/tutorial22.rst
.. _ogn_tutorial_cpu_gpu_bundles: Tutorial 22 - Bundles On The GPU ================================ Bundles are not exactly data themselves, they are a representation of a collection of attributes whose composition is determined at runtime. As such, they will always live on the CPU. However the attributes they are encapsulating have the same flexibility as other attributes to live on the CPU, GPU, or have their location decided at runtime. For that reason it's convenient to use the same "cpu", "cuda", and "any" memory types for the bundle attributes, with a slightly different interpretation. - **cpu** all attributes in the bundle will be on the CPU - **gpu** all attributes in the bundle will be on the GPU - **any** either some attributes in the bundle are on the CPU and some are on the GPU, or that decision will be made at runtime For example if you had a bundle of attributes consisting of a large array of points and a boolean that controls the type of operation you will perform on them it makes sense to leave the boolean on the CPU and move the points to the GPU for more efficient processing. OgnTutorialCpuGpuBundles.ogn ---------------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CpuGpuBundles" with an input bundle on the CPU, an input bundle on the GPU, and an output bundle whose memory location is decided at runtime by a boolean. .. literalinclude:: OgnTutorialCpuGpuBundles.ogn :linenos: :language: json OgnTutorialCpuGpuBundles.cpp ---------------------------------- The *cpp* file contains the implementation of the compute method. It creates a merged bundle in either the CPU or GPU based on the input boolean and runs an algorithm on the output location. .. literalinclude:: OgnTutorialCpuGpuBundles.cpp :linenos: :language: c++ OgnTutorialCpuGpuBundlesPy.py ----------------------------------- The *py* file contains the same algorithm as the C++ node, with the node implementation language being different. .. literalinclude:: OgnTutorialCpuGpuBundlesPy.py :linenos: :language: python
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/OgnTutorialBundleDataPy.py
""" Implementation of the Python node accessing attributes through the bundle in which they are contained. """ import numpy as np import omni.graph.core as og # Types recognized by the integer filter _INTEGER_TYPES = [og.BaseDataType.INT, og.BaseDataType.UINT, og.BaseDataType.INT64, og.BaseDataType.UINT64] class OgnTutorialBundleDataPy: """Exercise the bundled data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialBundleData.cpp As Python is so much more flexible it doubles values on any attribute type that can handle it, unlike the C++ node which only operates on integer types """ input_bundle = db.inputs.bundle output_bundle = db.outputs.bundle # This does a copy of the full bundle contents from the input bundle to the output bundle so that the # output data can be modified directly. output_bundle.bundle = input_bundle # The "attributes" member is a list that can be iterated. The members of the list do not contain real # og.Attribute objects, which must always exist, they are wrappers on og.AttributeData objects, which can # come and go at runtime. for bundled_attribute in output_bundle.attributes: attribute_type = bundled_attribute.type # Only integer types are recognized for this node's operation (doubling all integral values). # It does operate on tuples and arrays though so that part does not need to be set. # if attribute_type.base_type not in _INTEGER_TYPES: # continue # This operation does the right thing on all compatible types, unlike the C++ equivalent where it # requires special handling for each variation of the data types it can handle. if attribute_type.base_type == og.BaseDataType.TOKEN: if attribute_type.array_depth > 0: bundled_attribute.value = [f"{element}{element}" for element in bundled_attribute.value] else: bundled_attribute.value = f"{bundled_attribute.value}{bundled_attribute.value}" elif attribute_type.role in [og.AttributeRole.TEXT, og.AttributeRole.PATH]: bundled_attribute.value = f"{bundled_attribute.value}{bundled_attribute.value}" else: try: bundled_attribute.value = np.multiply(bundled_attribute.value, 2) except TypeError: db.log_error(f"This node does not handle data of type {attribute_type.get_type_name()}") return True
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/tutorial16.rst
.. _ogn_tutorial_bundle_data: Tutorial 16 - Bundle Data ========================= Attribute bundles are a construct that packages up groups of attributes into a single entity that can be passed around the graph. These attributes have all of the same properties as a regular attribute, you just have to go through an extra step to access their values. This node illustrates how to break open a bundle to access and modify values in the bundled attributes. OgnTutorialBundleData.ogn ------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.BundleData", which has one input bundle and one output bundle. .. literalinclude:: OgnTutorialBundleData.ogn :linenos: :language: json OgnTutorialBundleData.cpp ------------------------- The *cpp* file contains the implementation of the compute method. It accesses any attributes in the bundle that have integral base types and doubles the values of those attributes. .. literalinclude:: OgnTutorialBundleData.cpp :linenos: :language: c++ Bundled Attribute Data Manipulation Methods ------------------------------------------- These are the methods for accessing the data that the bundled attributes encapsulate. In regular attributes the code generated from the .ogn file provides accessors with predetermined data types. The data types of attributes within bundles are unknown until compute time so it is up to the node writer to explicitly cast to the correct data type. Extracting Bundled Attribute Data - Simple Types ++++++++++++++++++++++++++++++++++++++++++++++++ For reference, simple types, tuple types, array types, tuple array types, and role types are all described in :ref:`ogn_attribute_types`. However, unlike normal attributes the bundled attributes are always accessed as their raw native data types. For example instead of ``pxr::GfVec3f`` you will access with ``float[3]``, which can always be cast to the explicit types if desired. .. note:: One exception to the type casting is tokens. In normal attributes you retrieve tokens as ``NameToken``. Due to certain compiler restrictions the bundled attributes will be retrieved as the helper type ``OgnToken``, which is castable to ``NameToken`` for subsequent use. .. code-block:: cpp :emphasize-lines: 5 // As the attribute data types are only known at runtime you must perform a type-specific cast // to get the data out in its native form. const auto& inputBundle = db.inputs.bundle(); // Note the "const" here, to ensure we are not inadvertently modifying the input data. const auto weight = inputBundle.attributeByName(weightToken); const float* weightValue = weight.value<float>(); // nullptr return means the data is not of the requested type asssert( nullptr == weight.value<int>() ); Extracting Bundled Attribute Data - Tuple Types +++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 4 // The tuple data types can be accessed in exactly the same way as simple data types, with the proper cast. const auto& inputBundle = db.inputs.bundle(); const auto weight3 = inputBundle.attributeByName(weight3Token); const auto weight3Value = weight3.value<float[3]>(); // type of weight3Value == const float[3]* // If you have a preferred library for manipulating complex types you can cast to them if they are compatible. static_assert( std::is_convertible(pxr::GfVec3f, float[3]) ); const pxr::GfVec3f* usdWeight = reinterpret_cast<const pxr::GfVec3f*>(weight3Value); Extracting Bundled Attribute Data - Array Types +++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 4,11 // As with tuple types, the array types are extracted directly with the native array cast const auto& inputBundle = db.inputs.bundle(); const auto weights = inputBundle.attributeByName(weightsToken); const auto weightsValue = weights.value<float[]>(); // type == const float[]* auto& outputBundle = db.outputs.bundle(); // As this is an output, the const is omitted so that the data can be modified auto nWeights = outputBundle.attributeByName(nWeightsToken); // As with regular attributes, bundled array outputs must be resized to allocate space before filling them. // These array types also have the normal array capabilities, with a size() method and range-based for loops. nWeights.resize( weights.size() ); size_t index = 0; for (const auto& weightValue : *weightsValue) { nWeights[index++] = weightValue / 256.0f; } Extracting Bundled Attribute Data - Tuple Array Types +++++++++++++++++++++++++++++++++++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 4 // Tuple-arrays behave as you would expect, using the native tuple-array as the cast type const auto& inputBundle = db.inputs.bundle(); const auto weights3 = inputBundle.attributeByName(weights3Token); const auto weights3Value = weights.value<float[][3]>(); // type == const float[][3]* OgnTutorialBundleDataPy.py -------------------------- This is a Python version of the above C++ node with exactly the same set of attributes and a similar algorithm. The main difference is that for the Python version the type definitions are much more flexible so the algorithm can be applied to every type of bundled attribute with minimal code. (The .ogn file is omitted for brevity, being identical to the previous one save for the addition of a ``"language": "python"`` property.) .. literalinclude:: OgnTutorialBundleDataPy.py :linenos: :language: python
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/OgnTutorialBundleDataPy.ogn
{ "BundleDataPy": { "version": 1, "categories": "tutorials", "description": ["This is a tutorial node. It exercises functionality for access of data within", "bundle attributes. The configuration is the same as omni.graph.tutorials.BundleData", "except that the implementation language is Python" ], "language": "python", "metadata": { "uiName": "Tutorial Python Node: Bundle Data" }, "inputs": { "bundle": { "type": "bundle", "description": ["Bundle whose contents are modified for passing to the output"], "metadata": { "uiName": "Input Bundle" } } }, "outputs": { "bundle": { "type": "bundle", "description": ["This is the bundle with values of known types doubled."], "uiName": "Output Bundle" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/OgnTutorialBundleData.cpp
// 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. // #include <OgnTutorialBundleDataDatabase.h> using omni::graph::core::Type; using omni::graph::core::NameToken; using omni::graph::core::BaseDataType; namespace { // The function of this node is to double the values for all bundled attributes // with integral types, including tuples and arrays. // // The parameter is a ogn::RuntimeAttribute<kOgnOutput, ogn::kCpu>, which is the type of data returned when iterating // over an output bundle on the CPU. // It contains a description of the attribute within the bundle and access to the attribute's data. // BundledInput is a similar type, which is what you get when iterating over an input bundle. The main difference // between the two is the ability to modify the attribute or its data. template <typename POD> bool doubleSimple(ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& bundledAttribute) { // When an attribute is cast to the wrong type (e.g. an integer attribute is extracted with a float // template parameter on the get<,>() method) a nullptr is returned. That can be used to determine // the attribute type. You can also use the bundledAttribute.type() method to access the full type // information and select a code path using that. auto podValue = bundledAttribute.get<POD>(); if (podValue) { *podValue *= 2; return true; } return false; }; // Array and tuple data has iterator capabilities for easy access to individual elements template <typename CppType> bool doubleArray(ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& bundledAttribute) { // Strings and paths look like uint8_t[] but are not, so don't process them if ((bundledAttribute.type().role == AttributeRole::eText) || (bundledAttribute.type().role == AttributeRole::ePath)) { return false; } auto arrayValue = bundledAttribute.get<CppType>(); if (arrayValue) { for (auto& arrayElement : *arrayValue) { arrayElement *= 2; } return true; } return false; }; // Tuple arrays must have nested iteration template <typename CppType> bool doubleTupleArray(ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& bundledAttribute) { auto tupleSize = bundledAttribute.type().componentCount; auto tupleArrayValue = bundledAttribute.get<CppType>(); if (tupleArrayValue) { for (auto& arrayElement : *tupleArrayValue) { for (size_t i=0; i<tupleSize; ++i) { arrayElement[i] *= 2; } } return true; } return false; }; } class OgnTutorialBundleData { public: static bool compute(OgnTutorialBundleDataDatabase& db) { // Bundle attributes are extracted from the database in the same way as any other attribute. // The only difference is that a different interface class is provided, suited to bundle manipulation. const auto& inputBundle = db.inputs.bundle(); auto& outputBundle = db.outputs.bundle(); for (const auto& bundledAttribute : inputBundle) { auto podValue = bundledAttribute.get<int>(); } // Copying the entire bundle is more efficient than adding one member at a time. As the output bundle // will have the same attributes as the input, even though the values will be different, this is the best // approach. If the attribute lists were different then you would copy or create the individual attributes // as required. outputBundle = inputBundle; // Now walk the bundle to look for types to be modified for (auto& bundledAttribute : outputBundle) { // This shows how using a templated function can simplify handling of several different bundled // attribute types. The data types for each of the POD attributes is fully explained in the documentation // page titled "Attribute Data Types". The list of available POD data types is: // // bool // double // float // pxr::GfHalf // int // int64_t // NameToken // uint8_t // uint32_t // uint64_t // if (doubleSimple<int>(bundledAttribute)) continue; if (doubleSimple<int64_t>(bundledAttribute)) continue; if (doubleSimple<uint8_t>(bundledAttribute)) continue; if (doubleSimple<uint32_t>(bundledAttribute)) continue; if (doubleSimple<uint64_t>(bundledAttribute)) continue; // Plain ints are the only integral types supporting tuples. Double those here if (doubleArray<int[2]>(bundledAttribute)) continue; if (doubleArray<int[3]>(bundledAttribute)) continue; if (doubleArray<int[4]>(bundledAttribute)) continue; // Arrays are looped differently than tupls so they are also handled differently if (doubleArray<int[]>(bundledAttribute)) continue; if (doubleArray<int64_t[]>(bundledAttribute)) continue; if (doubleArray<uint8_t[]>(bundledAttribute)) continue; if (doubleArray<uint32_t[]>(bundledAttribute)) continue; if (doubleArray<uint64_t[]>(bundledAttribute)) continue; // Tuple arrays require a two level iteration if (doubleTupleArray<int[][2]>(bundledAttribute)) continue; if (doubleTupleArray<int[][3]>(bundledAttribute)) continue; if (doubleTupleArray<int[][4]>(bundledAttribute)) continue; // Any attributes not passing the above tests are not integral and therefore not handled by this node. } return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/OgnTutorialBundleData.ogn
{ "BundleData": { "version": 1, "categories": "tutorials", "description": ["This is a tutorial node. It exercises functionality for access of data within", "bundle attributes." ], "metadata": { "uiName": "Tutorial Node: Bundle Data" }, "inputs": { "bundle": { "type": "bundle", "description": ["Bundle whose contents are modified for passing to the output"], "metadata": { "uiName": "Input Bundle" } } }, "outputs": { "bundle": { "type": "bundle", "description": ["This is the bundle with values of known types doubled."] } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial9/OgnTutorialCpuGpuData.cpp
// 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. // #include <OgnTutorialCpuGpuDataDatabase.h> // This helper file keeps the GPU and CPU functions organized for easy access. // It's only for illustration purposes; you can choose to organize your functions any way you wish. // The first algorithm is a simple add, to illustrate passing non-array types. extern "C" void cpuGpuAddCPU(outputs::sum_t_cpu, inputs::a_t_cpu, inputs::b_t_cpu, size_t); extern "C" void cpuGpuAddGPU(outputs::sum_t_gpu, inputs::a_t_gpu, inputs::b_t_gpu); // The second algorithm shows the more common case of accessing array data. extern "C" void cpuGpuMultiplierCPU(outputs::points_t_gpu, inputs::multiplier_t_gpu, inputs::points_t_gpu, size_t); extern "C" void cpuGpuMultiplierGPU(outputs::points_t_gpu, inputs::multiplier_t_gpu, inputs::points_t_gpu, size_t); class OgnTutorialCpuGpuData { public: static bool compute(OgnTutorialCpuGpuDataDatabase& db) { // Computing the size of the output is independent of CPU/GPU as the size update is lazy and will happen // when the data is requested from the fabric. size_t numberOfPoints = db.inputs.points.size(); db.outputs.points.resize(numberOfPoints); // Use the runtime input to determine where the calculation should take place. // // Another helpful use of this technique is to first measure the size of data being evaluated and // if it meets a certain minimum threshold move the calculation to the GPU. if (db.inputs.is_gpu()) { cpuGpuAddGPU(db.outputs.sum.gpu(), db.inputs.a.gpu(), db.inputs.b.gpu()); // GPU data is just raw pointers so the size must be passed down to the algorithm cpuGpuMultiplierGPU( db.outputs.points.gpu(), db.inputs.multiplier.gpu(), db.inputs.points.gpu(), numberOfPoints); } else { // CPU version calls the shared CPU/GPU algorithm directly. This could also be implemented in the // CUDA file as an extern "C" function but it is so simple that this is easier. cpuGpuAddCPU(db.outputs.sum.cpu(), db.inputs.a.cpu(), db.inputs.b.cpu(), 0); // Extract the CPU data and iterate over all of the points, calling the shared deformation algorithm. // The data is passed through as raw CUDA-compatible bytes so that the deformation algorithm can live // all in one file. If the code were all on the CPU side then the data types could be used as regular // arrays, as showing in the tutorial on array data types. auto rawOutputPoints = db.outputs.points.cpu().data(); auto rawInputPoints = db.inputs.points.cpu().data(); cpuGpuMultiplierCPU(&rawOutputPoints, &db.inputs.multiplier.cpu(), &rawInputPoints, numberOfPoints); } return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial9/tutorial9.rst
.. _ogn_tutorial_cpuGpuData: Tutorial 9 - Runtime CPU/GPU Decision ===================================== The CPU/GPU data node creates various attributes for use in a CUDA-based GPU compute or a CPU-based compute, where the decision of which to use is made at runtime rather than compile time. A few representative types are used, though the list of potential attribute types is not exhaustive. See :ref:`ogn_attribute_types` for the full list. OgnTutorialCpuGpuData.ogn ------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CpuGpuData", which has attributes whose memory type is determined at runtime by the input named *isGPU*. The algorithm of the node is implemented in CUDA, but in such a way that it can run on either the CPU or the GPU, depending on where the attribute data lives. .. literalinclude:: OgnTutorialCpuGpuData.ogn :linenos: :language: json OgnTutorialCpuGpuData.cpp ------------------------- The *cpp* file contains the implementation of the compute method, which checks the value of the *isGPU* attribute and then extracts the data of the specified type to pass to the algorithm in the .cu file. .. literalinclude:: OgnTutorialCpuGpuData.cpp :linenos: :language: c++ OgnTutorialCpuGpuData_CUDA.cu ----------------------------- The *cu* file contains the implementation of the deformation on the CPU and GPU using CUDA. .. literalinclude:: OgnTutorialCpuGpuData_CUDA.cu :linenos: :language: c++ CPU/GPU Attribute Access ------------------------ Here is how the attribute values are returned from the database. Up until now the attribute name has sufficed as the database member that accesses the value through its *operator()*. The addition of the runtime switch of memory locations is facilitated by the addition of the *gpu()* and *cpu()* members. +-------------------------+----------------+-------------------------+-----------------+----------------+ | CPU Function | CPU Type | GPU Function | GPU Type | CUDA Type | +=========================+================+=========================+=================+================+ | inputs.a.cpu() | const float& | inputs.a_t_gpu | const float* | const float* | +-------------------------+----------------+-------------------------+-----------------+----------------+ | inputs.b.cpu() | const float& | inputs.b.gpu() | const float* | const float* | +-------------------------+----------------+-------------------------+-----------------+----------------+ | outputs.sum.cpu() | float& | outputs.sum.gpu() | float* | float* | +-------------------------+----------------+-------------------------+-----------------+----------------+ | inputs.multiplier.cpu() | const GfVec3f& | inputs.multiplier.gpu() | const GfVec3f* | const float3 | +-------------------------+----------------+-------------------------+-----------------+----------------+ | inputs.points.cpu() | const GfVec3f* | inputs.points.gpu() | const GfVec3f** | const float3** | +-------------------------+----------------+-------------------------+-----------------+----------------+ | outputs.points.cpu() | GfVec3f* | outputs.points.gpu() | const GfVec3f** | float3** | +-------------------------+----------------+-------------------------+-----------------+----------------+ Type Information ++++++++++++++++ As there are three different potential types for each attribute when it varies location at runtime (CPU, CPU being passed to GPU, and GPU) there are extra types introduced in order to handle each of them. The CUDA types are handled as before, but on the CPU side there are extra types for the data being passed from the CPU to the GPU. +----------------------+----------------+--------------------------+-----------------+ | CPU Type Method | CPU Data Type | GPU Type Method | GPU Data Type | +======================+================+==========================+=================+ | inputs::a_t | const float& | inputs::a_t_gpu | const float* | +----------------------+----------------+--------------------------+-----------------+ | inputs::b_t | const float& | inputs::b_t_gpu | const float* | +----------------------+----------------+--------------------------+-----------------+ | outputs::sum_t | float& | outputs::sum_t_gpu | float* | +----------------------+----------------+--------------------------+-----------------+ | inputs::multiplier_t | const GfVec3f& | inputs::multiplier_t_gpu | const GfVec3f* | +----------------------+----------------+--------------------------+-----------------+ | inputs::points_t | const GfVec3f* | inputs::points_t_gpu | const GfVec3f** | +----------------------+----------------+--------------------------+-----------------+ | outputs::points_t | GfVec3f* | outputs::points_t_gpu | const GfVec3f** | +----------------------+----------------+--------------------------+-----------------+ On the C++ side the functions defined in the CUDA file are declared as: .. code-block:: c++ extern "C" void cpuGpuMultiplierCPU(outputs::points_t, inputs::multiplier_t, inputs::points_t, size_t); extern "C" void cpuGpuMultiplierGPU(outputs::points_t_gpu, inputs::multiplier_t_gpu, inputs::points_t_gpu, size_t); The addition of the **_gpu** suffix mostly adds an extra layer of indirection to the values, since they exist in the GPU memory namespace. Care must be taken to call the correct version with the correctly extracted data: .. code-block:: c++ if (db.inputs.is_gpu()) { cpuGpuMultiplierGPU( db.outputs.points.gpu(), db.inputs.multiplier.gpu(), db.inputs.points.gpu(), numberOfPoints ); } else { // Note how array data is extracted in its raw form for passing to the function on the CUDA side. // This would be unnecessary if the implementation were entirely on the CPU side. cpuGpuMultiplierCPU( db.outputs.points.cpu().data(), db.inputs.multiplier.cpu(), db.inputs.points.cpu().data(), numberOfPoints ); } On the CUDA side the function definitions use the existing CUDA types, so their signatures are: .. code-block:: c++ extern "C" void cpuGpuMultiplierCPU(outputs::points_t, inputs::multiplier_t, inputs::points_t, size_t); extern "C" void cpuGpuMultiplierGPU(outputs::points_t, inputs::multiplier_t, inputs::points_t, size_t);
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial9/OgnTutorialCpuGpuData.ogn
{ "CpuGpuData" : { "version": 1, "categories": "tutorials", "memoryType": "any", "description": [ "This is a tutorial node. It illustrates how to access data whose memory location, CPU or GPU, is ", "determined at runtime in the compute method. The data types are the same as for the purely CPU and ", "purely GPU tutorials, it is only the access method that changes. The input 'is_gpu' determines where ", "the data of the other attributes can be accessed." ], "metadata": { "uiName": "Tutorial Node: Attributes With CPU/GPU Data" }, "inputs": { "is_gpu": { "type": "bool", "memoryType": "cpu", "description": ["Runtime switch determining where the data for the other attributes lives."], "default": false }, "a": { "type": "float", "description": ["First value to be added in algorithm 1"], "default": 0.0 }, "b": { "type": "float", "description": ["Second value to be added in algorithm 1"], "default": 0.0 }, "points": { "type": "float[3][]", "description": ["Points to be moved by algorithm 2"], "default": [] }, "multiplier": { "type": "float[3]", "description": ["Amplitude of the expansion for the input points in algorithm 2"], "default": [1.0, 1.0, 1.0] } }, "outputs": { "sum": { "type": "float", "description": ["Sum of the two inputs from algorithm 1"] }, "points": { "type": "float[3][]", "description": ["Final positions of points from algorithm 2"] } }, "tests": [ { "inputs:is_gpu": false, "inputs:a": 1.0, "inputs:b": 2.0, "outputs:sum": 3.0 }, { "inputs:is_gpu": false, "inputs:a": 5.0, "inputs:b": 3.0, "outputs:sum": 8.0 }, { "inputs:is_gpu": false, "inputs:points": [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], "inputs:multiplier": [2.0, 3.0, 4.0], "outputs:points": [[2.0, 6.0, 12.0], [4.0, 9.0, 16.0]] }, { "inputs:is_gpu": true, "inputs:a": 1.0, "inputs:b": 2.0, "inputs:points": [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], "inputs:multiplier": [2.0, 3.0, 4.0] } ], "$why_disabled": "GPU extraction is not yet implemented so for those tests only inputs are provided", "$tests_disabled_until_gpu_data_extraction_works": [ { "inputs:is_gpu": true, "inputs:a": 1.0, "inputs:b": 2.0, "outputs:sum": 3.0, "gpu": ["outputs:sum"] }, { "inputs:is_gpu": true, "inputs:a": 5.0, "inputs:b": 3.0, "outputs:sum": 8.0, "gpu": ["outputs:sum"] }, { "inputs:is_gpu": true, "inputs:points": [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], "inputs:multiplier": [2.0, 3.0, 4.0], "outputs:points": [[2.0, 6.0, 12.0], [4.0, 9.0, 16.0]], "gpu": ["outputs:points"] } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/OgnTutorialCudaDataCpuPy.ogn
{ "CudaCpuArraysPy" : { "version": 1, "memoryType": "cuda", "cudaPointers": "cpu", "language": "python", "description": [ "This is a tutorial node. It illustrates the alternative method of extracting pointers to GPU array data", "in which the pointer returned is a CPU pointer and can be dereferenced on the CPU side. Without the", "cudaPointers value set that pointer would be a GPU pointer to an array of GPU pointers and could", "only be dereferenced on the device. Both plain attribute and bundle attribute extraction are shown." ], "uiName": "Python Tutorial Node: Attributes With CUDA Array Pointers In Cpu Memory", "categories": "tutorials", "inputs": { "points": { "type": "float[3][]", "description": ["Array of points to be moved"], "default": [] }, "multiplier": { "type": "float[3]", "description": ["Amplitude of the expansion for the input points"], "default": [1.0, 1.0, 1.0] } }, "outputs": { "points": { "type": "float[3][]", "description": ["Final positions of points"] }, "outBundle": { "type": "bundle", "memoryType": "any", "description": "Bundle containing a copy of the output points" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/OgnTutorialCudaDataCpuPy.py
""" Implementation of the Python node accessing CUDA attributes in a way that accesses the GPU arrays with a CPU pointer. No actual computation is done here as the tutorial nodes are not set up to handle GPU computation. """ import ctypes import omni.graph.core as og # Only one type of data is handled by the compute - pointf[3][] POINT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION) def get_address(attr: og.Attribute) -> int: """Returns the contents of the memory the attribute points to""" ptr_type = ctypes.POINTER(ctypes.c_size_t) ptr = ctypes.cast(attr.memory, ptr_type) return ptr.contents.value class OgnTutorialCudaDataCpuPy: """Exercise GPU access for extended attributes through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Accesses the CUDA data, which for arrays exists as wrappers around CPU memory pointers to GPU pointer arrays. No compute is done here. """ # Put accessors into local variables for convenience input_points = db.inputs.points multiplier = db.inputs.multiplier # Set the size to what is required for the multiplication - this can be done without accessing GPU data. # Notice that since this is CPU pointers to GPU data the size has to be taken from the data type description # rather than the usual method of taking len(input_points). db.outputs.points_size = input_points.dtype.size # After changing the size the memory isn't allocated immediately (when necessary). It is delayed until you # request access to it, which is what this line will do. output_points = db.outputs.points # This is a separate test to add a points attribute to the output bundle to show how when a bundle has # CPU pointers to the GPU data that information propagates to its children # Start with an empty output bundle. output_bundle = db.outputs.outBundle output_bundle.clear() output_bundle.add_attributes([og.Type(og.BaseDataType.FLOAT, 3, 1)], ["points"]) bundle_attr = output_bundle.attribute_by_name("points") # As for the main attributes, setting the bundle member size readies the buffer of the given size on the GPU bundle_attr.size = input_points.dtype.size # The output cannot be written to here through the normal assignment mechanisms, e.g. the typical step of # copying input points to the output points, as the data is not accessible on the GPU through Python directly. # Instead you can access the GPU memory pointers through the attribute values and send it to CUDA code, either # generated from the Python code or accessed through something like pybind wrappers. print("Locations in CUDA() should be in GPU memory space") print(f" CPU Location for reference = {hex(id(db))}", flush=True) print(f" Input points are {input_points} at CUDA({hex(get_address(input_points))})", flush=True) print(f" Multiplier is CUDA({multiplier})", flush=True) print(f" Output points are {output_points} at CUDA({hex(get_address(output_points))})", flush=True) print(f" Bundle {bundle_attr.gpu_value} at CUDA({hex(get_address(bundle_attr.gpu_value))})", flush=True) return True
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/OgnTutorialCudaDataCpu.cpp
// 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. // #include <omni/graph/core/GpuArray.h> #include <OgnTutorialCudaDataCpuDatabase.h> // This function exercises referencing of array data on the GPU. // The CUDA code takes its own "float3" data types, which are castable equivalents to the generated GfVec3f. // The GpuArray/ConstGpuArray wrappers isolate the GPU pointers from the CPU code. extern "C" void applyDeformationCpuToGpu(pxr::GfVec3f* outputPoints, const pxr::GfVec3f* inputPoints, const pxr::GfVec3f* multiplier, size_t numberOfPoints); // This node runs a couple of algorithms on the GPU, while accessing parameters from the CPU class OgnTutorialCudaDataCpu { public: static bool compute(OgnTutorialCudaDataCpuDatabase& db) { size_t numberOfPoints = db.inputs.points.size(); db.outputs.points.resize(numberOfPoints); if (numberOfPoints > 0) { // The main point to note here is how the pointer can be dereferenced on the CPU side, whereas normally // you would have to send it to the GPU for dereferencing. (The long term purpose of the latter is to make // it more efficient to handle arrays-of-arrays on the GPU, however since that is not yet implemented // we can get away with a single dereference here.) applyDeformationCpuToGpu(*db.outputs.points(), *db.inputs.points.gpu(), db.inputs.multiplier(), numberOfPoints); // Just as a test now also reference the points as CPU data to ensure the value casts correctly const float* pointsAsCpu = reinterpret_cast<const float*>(db.inputs.points.cpu().data()); } return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/OgnTutorialCudaDataCpu.ogn
{ "CudaCpuArrays" : { "version": 1, "memoryType": "cuda", "cudaPointers": "cpu", "description": [ "This is a tutorial node. It illustrates the alternative method of extracting pointers to GPU array data", "in which the pointer returned is a CPU pointer and can be dereferenced on the CPU side. Without the", "cudaPointers value set that pointer would be a GPU pointer to an array of GPU pointers and could", "only be dereferenced on the device." ], "metadata": { "uiName": "Tutorial Node: Attributes With CUDA Array Pointers In Cpu Memory" }, "categories": "tutorials", "inputs": { "points": { "type": "float[3][]", "memoryType": "any", "description": ["Array of points to be moved"], "default": [] }, "multiplier": { "type": "float[3]", "description": ["Amplitude of the expansion for the input points"], "default": [1.0, 1.0, 1.0] } }, "outputs": { "points": { "type": "float[3][]", "description": ["Final positions of points"] } }, "tests": [ { "inputs:multiplier": [1.0, 2.0, 3.0], "inputs:points": [[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]], "outputs:points": [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [3.0, 6.0, 9.0]] } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/tutorial27.rst
.. _ogn_tutorial_cudaDataOnCpu: Tutorial 27 - GPU Data Node with CPU Array Pointers =================================================== The GPU data node illustrates the alternative method of extracting array data from the GPU by returning a CPU pointer to the GPU array. Normally the data returns a GPU pointer to an array of GPU pointers, optimized for future use in parallel processing of GPU array data. By returning a CPU pointer to the array you can use host-side processing to dereference the pointers. OgnTutorialCudaDataCpu.ogn -------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CudaCpuArrays", which has an input and an output of type `float[3][]`, along with the special keyword to indicate that the pointer to the CUDA arrays should be in CPU space. .. literalinclude:: OgnTutorialCudaDataCpu.ogn :linenos: :language: json :emphasize-lines: 5 OgnTutorialCudaDataCpu.cpp -------------------------- The *cpp* file contains the implementation of the compute method, which in turn calls the CUDA algorithm. .. literalinclude:: OgnTutorialCudaDataCpu.cpp :linenos: :language: c++ :emphasize-lines: 31-35 OgnTutorialCudaDataCpu_CUDA.cu ------------------------------ The *cu* file contains the implementation of the algorithm on the GPU using CUDA. .. literalinclude:: OgnTutorialCudaDataCpu_CUDA.cu :linenos: :language: c++ OgnTutorialCudaDataCpuPy.py --------------------------- The *py* file contains the implementation of the compute method, which for this example doesn't actually compute as extra extension support is required for Python to run on the GPU (e.g. a Python -> CUDA compiler). .. literalinclude:: OgnTutorialCudaDataCpuPy.py :linenos: :language: python :emphasize-lines: 31-35
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial30/OgnTutorialSIMDAdd.ogn
{ "TutorialSIMDFloatAdd": { "version": 1, "description": "Add 2 floats together using SIMD instruction set", "categories": "tutorials", "uiName": "Tutorial Node: SIMD Add", "inputs": { "a": { "type": "float", "description": "first input operand" }, "b": { "type": "float", "description": "second input operand" } }, "outputs": { "result": { "type": "float", "description": "the sum of a and b" } } } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial30/OgnTutorialSIMDAdd.cpp
// Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #if !defined(__arm__) && !defined(__aarch64__) #define SIMD_AVAILABLE #endif #include <OgnTutorialSIMDAddDatabase.h> #ifdef SIMD_AVAILABLE #include <immintrin.h> #endif // This node perform a sum using SIMD instruction set class OgnTutorialSIMDAdd { public: static size_t computeVectorized(OgnTutorialSIMDAddDatabase& db, size_t count) { // Constants static size_t constexpr kSIMDSize = 4 * sizeof(float); static size_t constexpr kMask = kSIMDSize - 1; // Retrieve data auto opA = db.inputs.a.vectorized(count); auto opB = db.inputs.b.vectorized(count); auto res = db.outputs.result.vectorized(count); //Regular loop definition auto regularLoop = [&](size_t const begin, size_t const end) -> size_t const { for (size_t idx = begin; idx < end; ++idx) res[idx] = opA[idx] + opB[idx]; return end; }; #ifdef SIMD_AVAILABLE //Alignment must be identical bool const correctlyAligned = ((size_t(opA.data()) & kMask) == (size_t(opB.data()) & kMask)) && ((size_t(opA.data()) & kMask) == (size_t(res.data()) & kMask)); if (!correctlyAligned) { regularLoop(0, count); } else { // Unaligned elements size_t const maskedAdress = (size_t(opA.data()) & kMask); size_t const unalignedCount = maskedAdress ? regularLoop(0, (kSIMDSize - maskedAdress) / sizeof(float)) : 0; // Vectorized elements size_t const vectorizedCount = (count - unalignedCount) & (~kMask); size_t const vectorizedLoop = vectorizedCount / (kSIMDSize / sizeof(float)); __m128* aSIMD = (__m128*)(opA.data() + unalignedCount); __m128* bSIMD = (__m128*)(opB.data() + unalignedCount); __m128* resSIMD = (__m128*)(res.data() + unalignedCount); for (size_t idx = 0; idx < vectorizedLoop; ++idx) resSIMD[idx] = _mm_add_ps(aSIMD[idx], bSIMD[idx]); // Remaining elements regularLoop(unalignedCount + vectorizedCount, count); } #else regularLoop(0, count); #endif return count; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/extensionTutorial/extensionTutorial.rst
.. _ogn_extension_tutorial: Example Setup - Creating An OGN-enabled Extension ================================================= This document assumes familiarity with the extension 2.0 implementation described in the Extensions doc. Implementation details that relate to the extension system but not to .ogn files in particular will not be described in detail. Refer to the above document for more information. .. only:: internal Internal: link to Extensions / exts-main-doc broken until kit_repo_docs migration completed (bidirectional dependency bad) For the purposes of illustration an extension names `omni.my.extension` will be created, with a single node `OgnMyNode`. .. contents:: .. _ogn_recommended_directory_structure: Recommended Directory Structure ------------------------------- The OGN helper scripts presume a certain directory structure, setting up helper variables that default to values supporting that structure. You're free to use any other structure, you will just have more work to do in your build file to support them. To start with are the directories. .. code-block:: text :emphasize-lines: 1,2,4,6,8,12,15,19,21,23,26 omni.my.extension/ ├── bindings/ | └── BindingsPython.cpp ├── config/ | └── extension.toml ├── data/ | └── preview.png ├── docs/ | ├── README.md | ├── CHANGELOG.md | └── index.rst ├── nodes/ | ├── OgnMyNode.cpp | └── OgnMyNode.ogn ├── plugins/ | ├── PluginInterface.cpp | └── IMyExtension.h ├── premake5.lua └── python/ ├── __init__.py ├── _impl/ | extension.py | └── nodes/ | ├── OgnMyPythonNode.py | └── OgnMyPythonNode.ogn └── tests/ └── test_my_extension.py **omni.my.extension** is the top level directory for the extension, keeping all related files together. **config** is the common location for the extension configuration file. **data** is the common location for data files used by your extension. **docs** is the common location for published documentation for your extension. **nodes** is a directory you can put all of your node files. If there is a large number of nodes for a single extension then this directory can be subdivided (e.g. **nodes/math**, **nodes/core**, **nodes/vectors**...) **plugins** is for the common C++ code. In particular the files connecting to the Carbonite plugin ABI, but also other files used by the plugin that aren't specifically node files. **python** contains just the __init__.py script used to load the extension. The main feature of this file is that it is used to import everything in the **python/_impl** subdirectory that will be exposed as the public API. Although this is just a convention, as every function will always be accessible for the user that digs deep enough, setting up your intended API in this way makes it more clear exactly what parts of your module are intended for public use, and hence expected to be more stable. **python/_impl** contains all of the Python scripts. At the top level this can be UI files, commands, and helper scripts. **python/_impl/nodes** contains all of your nodes implemented in Python. Separating them into their own directory makes it easier for the OGN processor to find them. **python/tests** is for the scripts used to test the functionality in your extension. These are your armour, keeping your extension safe from changes others make, and providing confidence when you refactor. premake5.lua ------------ The *.lua* file containing an extension 2.0 implementation of an extension. The OGN-specific additions are commented. (Other lines would normally be commented as well in good build code; omitted here for clarity.) .. literalinclude:: premake5.lua :linenos: :language: lua Here is that same file with appropriate comments that can be used as a starting template. .. literalinclude:: premake5-template.lua :linenos: :language: lua Changing Type Definitions +++++++++++++++++++++++++ By default the code generator uses certain C++, CUDA, and Python data types for the code it produces. Sometimes you may wish to use alternative types, e.g. your favourite math library's types. This information can be modified through a type definition file. To modify the type definitions for an entire project you add an extra parameter to the call to `get_ogn_project_information()` in your ``premake5.lua`` file, with details described in :ref:`ogn_type_definition_overrides`. bindings/BindingsPython.cpp --------------------------- This file is set up as per the regular extension set up you can find in the Extensions doc with no OGN-specific changes required. .. only:: internal Internal: link to Extensions / exts-main-doc broken until kit_repo_docs migration completed (bidirectional dependency bad) config/extension.toml --------------------- In addition to the other required dependencies, the OmniGraph dependencies need to be added for the extension loading to work properly. These are the OmniGraph core, and the Kit async engine used for running tests. .. code-block:: toml :linenos: :emphasize-lines: 8-11,15-16 [package] title = "My Feature" # Main module for the Python interface [[python.module]] name = "omni.my.feature" # Watch the .ogn files for hot reloading (only works for Python files) [fswatcher.patterns] include = ["*.ogn", "*.py"] exclude = ["Ogn*Database.py"] # Other extensions that need to load before this one [dependencies] "omni.graph" = {} "omni.graph.tools" = {} [[native.plugin]] path = "bin/${platform}/${config}/*.plugin" recursive = false data/preview.png ---------------- This file is an image that will be displayed in the extension manager. Nothing extra needs to be done to make that happen; just create the file and ensure that the **data/** directory is installed into the extension's destination directory. docs/README.md -------------- Markdown format documentation for your extension that will appear in the extension manager. It should be a short description of what the extension does. Here is a minimal version of a readme. .. code-block:: md # My Extension [omni.my.extension] My extension can cook your breakfast, mow your lawn, and fix the clog in your kitchen sink. docs/CHANGELOG.md ----------------- Markdown format documentation for your extension changes that will appear in the extension manager. Here is a simple template that uses a standard approach to maintaining change logs. .. code-block:: 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] ## [1.0.0] - 2021-03-01 ### Initial Version docs/index.rst -------------- ReStructuredText format documentation for your extension. The node's documentation will be generated automatically by the OGN processor. nodes/OgnMyNode.cpp,OgnMyNode.ogn --------------------------------- These files contain the description and implementation of your node. See the detailed examples in :ref:`ogn_tutorial_nodes` for information on what can go into these files. The naming of the files is important. They must both have the same base name (``OgnMyNode`` in this case). It is also a good idea to have the common prefix `Ogn` as that makes nodes easier to locate. plugins/PluginInterface.cpp --------------------------- This file sets up your plugin. The OGN processing requires a couple of small additions to enable the automatic registration and deregistration of nodes when your plugin starts up and shuts down. .. code-block:: c++ :linenos: :emphasize-lines: 6,7,16-18,28,33 #include "IOmniMyFeature.h" #include <carb/Framework.h> #include <carb/PluginUtils.h> #include <omni/graph/core/iComputeGraph.h> #include <omni/graph/core/ogn/Registration.h> #include <omni/kit/IEditor.h> #include <omni/kit/IMinimal.h> const struct carb::PluginImplDesc pluginDesc = { "omni.my.feature.plugin", "My Feature", "NVIDIA", carb::PluginHotReload::eEnabled, "dev" }; CARB_PLUGIN_IMPL(pluginDesc, omni::my::feature::IOmniMyFeature) CARB_PLUGIN_IMPL_DEPS(omni::kit::IEditor, omni::graph::core::IGraphRegistry, carb::flatcache::IToken) DECLARE_OGN_NODES() // carbonite interface for this plugin (may contain multiple compute nodes) void fillInterface(omni::my::feature::IOmniMyFeature& iface) { iface = {}; } CARB_EXPORT void carbOnPluginStartup() { INITIALIZE_OGN_NODES() } CARB_EXPORT void carbOnPluginShutdown() { RELEASE_OGN_NODES() } plugins/IMyExtension.h ---------------------- This file is set up as per the extension description with no OGN-specific changes required. python/__init__.py ------------------ This file initializes the extension's Python module as per the extension model. This will import your intended Python API for general use. .. code-block:: python from ._impl.utilities import useful_utility from ._impl.utilities import other_utility from ._impl.commands import cmds With this setup the extension user can access your Python API through the main module (similarly to how popular public packages such as `numpy` and `pandas` are structured). .. code-block:: python import omni.my.feature as mf mf.useful_utility(["Bart", "Lisa", "Maggie", "Marge", "Homer"]) python/tests/__init__.py ------------------------ This file may contain setup code for your manually written test scripts that appear in this directory. It should contain the snippet below, which will enable automatic registration of your tests at runtime. .. code-block:: python """ Presence of this file allows the tests directory to be imported as a module so that all of its contents can be scanned to automatically add tests that are placed into this directory. """ scan_for_test_modules = True Test files should all have a PEP8-compliant name of the form ``test_my_good_test_file.py``. The `test` prefix ensures that the files will be automatically recognized as containing Python unit tests. Sample Skeleton Test -------------------- Here's an example of a simple test that does nothing more than run a graph evaluation on a graph consisting of two nodes with a connection between them, verifying the output of a node. While .ogn files have the ability to specify their own automated test configurations, it is very limited and you'll want to use something like this for more complex testing. .. literalinclude:: test_example.py :linenos: :language: python
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/extensionTutorial/premake5-template.lua
-- ---------------------------------------------------------------------- -- Set up standard extension information local ext = get_current_extension_info() -- ---------------------------------------------------------------------- -- Set up standard OGN information local ogn = get_ogn_project_information(ext, "omni/my/extension") -- Put the extension into a top-level group and define the main project ext.group = "simulation" project_ext( ext ) -- ---------------------------------------------------------------------- -- Define the plugin project, which contains all of the C++ code project_ext_plugin( ext, ogn.plugin_project ) -- ---------------------------------------------------------------------- -- Add the files to the project, reorganizing to make them easier to find in the Visual Studio project add_files("ogn/", ogn.nodes_path) add_files("impl", ogn.plugin_path) add_files("config", "config") add_files("docs", ogn.docs_path) -- ---------------------------------------------------------------------- -- Set up all build dependencies required by the OGN generated code add_ogn_dependencies(ogn) -- ---------------------------------------------------------------------- -- Add dependent libraries to the extension link phase links {"carb", "vt", "gf", "sdf", "arch", "usd", "tf", "usdUtils", "usdGeom", "usdSkel"} -- ---------------------------------------------------------------------- -- Create a project for processing the .ogn files to create the generated code. project_ext_ogn( ext, ogn ) -- ---------------------------------------------------------------------- -- Create a project for providing the Python interface to the extension project_ext_bindings { ext = ext, project_name = ogn.python_project, module = ogn.bindings_module, src = ogn.bindings_path, target_subdir = ogn.bindings_target_path } -- ---------------------------------------------------------------------- -- Add the files to the project, reorganizing to make them easier to find in the Visual Studio project add_files("bindings", "bindings") add_files("python", "python/*.py") add_files("python/_impl", "python/_impl") add_files("python/tests", "python/tests") -- ---------------------------------------------------------------------- -- Python bindings have OGN dependencies so set them up here. add_ogn_dependencies(ogn, {"python/_impl/nodes"}) -- ---------------------------------------------------------------------- -- Copy the init script directly into the build tree to avoid reload conflicts. repo_build.prebuild_copy { { "python/__init__.py", ogn.python_target_path }, } -- Linking directories allows them to hot reload when files are modified in the source tree repo_build.prebuild_link { { "python/_impl", ogn.python_target_path.."/_impl" }, { "python/tests", ogn.python_tests_target_path }, }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/extensionTutorial/premake5.lua
local ext = get_current_extension_info() -- ---------------------------------------------------------------------- -- Initialize a helper variable containing standard configuration information for projects containing OGN files local ogn = get_ogn_project_information(ext, "omni/my/extension") -- This group is just for keeping things organized in the generated build files. ext.group = "simulation" project_ext( ext ) -- ---------------------------------------------------------------------- -- The main project is for building your plugin, mainly C++ nodes and the plugin support code. project_ext_plugin( ext, ogn.plugin_project ) -- ---------------------------------------------------------------------- -- OGN files can be grouped together. By default "ogn.nodes_path" is just "nodes", as per the directory structure add_files("ogn/", ogn.nodes_path) add_files("impl", ogn.plugin_path) add_files("config", "config") add_files("docs", ogn.docs_path) -- ---------------------------------------------------------------------- -- This sets up the OGN project dependencies, including the include path, library path, and extension dependencies add_ogn_dependencies(ogn) links {"carb", "vt", "gf", "sdf", "arch", "usd", "tf", "usdUtils", "usdGeom", "usdSkel"} -- ---------------------------------------------------------------------- -- This creates a separate project tasked with processing the .ogn files to create the generated code. -- By making it a separate project the build is guaranteed to always process the files before trying to compile. -- The dependency on this project is auto-generated by the add_ogn_dependencies() function above. project_ext_ogn( ext, ogn ) -- ---------------------------------------------------------------------- -- Note how the ogn object is used to populate the Python binding and script information project_ext_bindings { ext = ext, project_name = ogn.python_project, module = ogn.bindings_module, src = ogn.bindings_path, target_subdir = ogn.bindings_target_path } add_files("bindings", "bindings") add_files("python", "python/*.py") add_files("python/_impl", "python/_impl") add_files("python/tests", "python/tests") -- ---------------------------------------------------------------------- -- If you do not have Python node implementations this line may be safely omitted. -- The second parameter is a list of directories containing Python node files, which enables OmniGraph to -- hot-load the Python node files when they change, so that you can modify their behaviour live. add_ogn_dependencies(ogn, {"python/_impl/nodes"}) -- ---------------------------------------------------------------------- -- Copy the init script directly into the build tree to avoid reload conflicts. repo_build.prebuild_copy { { "python/__init__.py", ogn.python_target_path }, } -- Linking directories allows them to hot reload when files are modified in the source tree repo_build.prebuild_link { { "python/_impl", ogn.python_target_path.."/_impl" }, { "python/tests", ogn.python_tests_target_path }, }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/extensionTutorial/test_example.py
"""Tests for my simple math nodes""" # To make code more concise use a shortform in the import, much as you would for numpy -> np import omni.graph.core as og # This module contains some useful testing utilities import omni.graph.core.tests as ogts # By using the standard test case base class you get scene setUp() and tearDown(), and the current set of default # OmniGraph settings. If you wish to use any non-standard settings, leave the scene in place after the test completes, # or add your own scoped setting variables see the set of classes that derive from ogts.OmniGraphTestCase and look at # the test configuration factory function ogts.test_case_class(). class TestMySimpleNodes(ogts.OmniGraphTestCase): """Class containing tests for my simple nodes. The base class allows the tests to be run asynchronously""" # ---------------------------------------------------------------------- async def test_math(self): """Run a node network with the math operation (A + 6) * 10 = B Exercises the math nodes for addition (my.node.add) and multiplication (my.node.multiply) """ # The Controller class is useful for manipulating the OmniGraph. See the Python help on it for details. # Using this shortcut keeps the graph configuration specification more readable. keys = og.Controller.Keys # This sets up the graph in the configuration required for the math operation to work (graph, (plus_node, times_node), _, _) = og.Controller.edit( "/mathGraph", { keys.CREATE_NODES: [("plus", "my.extension.addInts"), ("times", "my.extension.multiplyInts")], keys.CONNECT: [("plus.outputs:result", "times.inputs:a")], keys.SET_VALUES: [("plus.inputs:a", 6), ("times.inputs:b", 10)], }, ) # This contains pairs of (A, B) values that should satisfy the math equation. test_data = [(1, 70), (0, 60), (-6, 0)] # Creating specific controllers tied to the attributes that will be accessed multiple times in the loop # makes the access a little bit faster. in_controller = og.Controller(og.Controller.attribute("inputs:b", plus_node)) out_controller = og.Controller(og.Controller.attribute("outputs:result", times_node)) # Loop through the operation to set the input and test the output for (value_a, value_b) in test_data: # Set the test input on the node in_controller.set(value_a) # This has to be done to ensure the nodes do their computation before testing the results await og.Controller.evaluate(graph) # Compare the expected value from the test data against the computed value from the node self.assertEqual(value_b, out_controller.get())
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial14/OgnTutorialDefaults.cpp
// 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. // #include <OgnTutorialDefaultsDatabase.h> class OgnTutorialDefaults { public: static bool compute(OgnTutorialDefaultsDatabase& db) { // Simple values db.outputs.a_bool() = db.inputs.a_bool(); db.outputs.a_half() = db.inputs.a_half(); db.outputs.a_int() = db.inputs.a_int(); db.outputs.a_int64() = db.inputs.a_int64(); db.outputs.a_double() = db.inputs.a_double(); db.outputs.a_float() = db.inputs.a_float(); db.outputs.a_uchar() = db.inputs.a_uchar(); db.outputs.a_uint() = db.inputs.a_uint(); db.outputs.a_uint64() = db.inputs.a_uint64(); db.outputs.a_token() = db.inputs.a_token(); db.outputs.a_string() = db.inputs.a_string(); // A few representative tuples db.outputs.a_int2() = db.inputs.a_int2(); db.outputs.a_matrix() = db.inputs.a_matrix(); // And an array db.outputs.a_array().resize(db.inputs.a_array().size()); db.outputs.a_array() = db.inputs.a_array(); return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial14/OgnTutorialDefaults.ogn
{ "Defaults": { "version": 1, "categories": "tutorials", "scheduling": ["threadsafe"], "description": ["This is a tutorial node. It will move the values of inputs to corresponding outputs.", "Inputs all have unspecified, and therefore empty, default values." ], "metadata": { "uiName": "Tutorial Node: Defaults" }, "inputs": { "a_bool": { "type": "bool", "description": ["This is an attribute of type boolean"] }, "a_half": { "type": "half", "description": ["This is an attribute of type 16 bit floating point"] }, "a_int": { "type": "int", "description": ["This is an attribute of type 32 bit integer"] }, "a_int64": { "type": "int64", "description": ["This is an attribute of type 64 bit integer"] }, "a_float": { "type": "float", "description": ["This is an attribute of type 32 bit floating point"] }, "a_double": { "type": "double", "description": ["This is an attribute of type 64 bit floating point"] }, "a_string": { "type": "string", "description": ["This is an attribute of type string"] }, "a_token": { "type": "token", "description": ["This is an attribute of type interned string with fast comparison and hashing"] }, "a_uchar": { "type": "uchar", "description": ["This is an attribute of type unsigned 8 bit integer"] }, "a_uint": { "type": "uint", "description": ["This is an attribute of type unsigned 32 bit integer"] }, "a_uint64": { "type": "uint64", "description": ["This is an attribute of type unsigned 64 bit integer"] }, "a_int2": { "type": "int[2]", "description": ["This is an attribute of type 2-tuple of integers"] }, "a_matrix": { "type": "matrixd[2]", "description": ["This is an attribute of type 2x2 matrix"] }, "a_array": { "type": "float[]", "description": ["This is an attribute of type array of floats"] } }, "outputs": { "a_bool": { "type": "bool", "description": ["This is a computed attribute of type boolean"] }, "a_half": { "type": "half", "description": ["This is a computed attribute of type 16 bit floating point"] }, "a_int": { "type": "int", "description": ["This is a computed attribute of type 32 bit integer"] }, "a_int64": { "type": "int64", "description": ["This is a computed attribute of type 64 bit integer"] }, "a_float": { "type": "float", "description": ["This is a computed attribute of type 32 bit floating point"] }, "a_double": { "type": "double", "description": ["This is a computed attribute of type 64 bit floating point"] }, "a_string": { "type": "string", "description": ["This is a computed attribute of type string"] }, "a_token": { "type": "token", "description": ["This is a computed attribute of type interned string with fast comparison and hashing"] }, "a_uchar": { "type": "uchar", "description": ["This is a computed attribute of type unsigned 8 bit integer"] }, "a_uint": { "type": "uint", "description": ["This is a computed attribute of type unsigned 32 bit integer"] }, "a_uint64": { "type": "uint64", "description": ["This is a computed attribute of type unsigned 64 bit integer"] }, "a_int2": { "type": "int[2]", "description": ["This is a computed attribute of type 2-tuple of integers"] }, "a_matrix": { "type": "matrixd[2]", "description": ["This is a computed attribute of type 2x2 matrix"] }, "a_array": { "type": "float[]", "description": ["This is a computed attribute of type array of floats"] } }, "tests": [ { "outputs:a_bool": false, "outputs:a_double": 0.0, "outputs:a_float": 0.0, "outputs:a_half": 0.0, "outputs:a_int": 0, "outputs:a_int64": 0, "outputs:a_string": "", "outputs:a_token": "", "outputs:a_uchar": 0, "outputs:a_uint": 0, "outputs:a_uint64": 0, "outputs:a_int2": [0, 0], "outputs:a_matrix": [[1.0, 0.0], [0.0, 1.0]], "outputs:a_array": [] } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial14/tutorial14.rst
.. _ogn_tutorial_defaults: Tutorial 14 - Defaults ====================== While most inputs are required to have default values it's not strictly necessary to provide explicit values for those defaults. If a default is required and not specified then it will get a default value equal to an empty value. See the table at the bottom for what is considered an "empty" value for each type of attribute. OgnTutorialDefaults.ogn ------------------------ The *ogn* file shows the implementation of a node named "omni.graph.tutorials.Defaults", which has sample inputs of several types without default values and matching outputs. .. literalinclude:: OgnTutorialDefaults.ogn :linenos: :language: json OgnTutorialDefaults.cpp ------------------------ The *cpp* file contains the implementation of the compute method, which copies the input values over to the corresponding outputs. All values should be the empty defaults. .. literalinclude:: OgnTutorialDefaults.cpp :linenos: :language: c++ Empty Values For Attribute Types -------------------------------- The empty values for each of the attribute types is defined below. Having no default specified in the .ogn file for any of them is equivalent to defining a default of the given value. +-----------+---------------+ | Type Name | Empty Default | +===========+===============+ | bool | False | +-----------+---------------+ | double | 0.0 | +-----------+---------------+ | float | 0.0 | +-----------+---------------+ | half | 0.0 | +-----------+---------------+ | int | 0 | +-----------+---------------+ | int64 | 0 | +-----------+---------------+ | string | "" | +-----------+---------------+ | token | "" | +-----------+---------------+ | uchar | 0 | +-----------+---------------+ | uint | 0 | +-----------+---------------+ | uint64 | 0 | +-----------+---------------+ .. note:: All attributes that are array types have empty defaults equal to the empty array [] .. note:: All tuple types have empty defaults equal to a tuple of the correct count, each member containing the empty value for the base type. e.g. a float[2] will have empty default [0.0, 0.0], and a matrix[2] will have empty default [[0.0, 0.0], [0.0, 0.0]]
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial26/OgnTutorialGenericMathNode.py
import numpy as np import omni.graph.core as og # Mappings of possible numpy dtypes from the result data type and back dtype_from_basetype = { og.BaseDataType.INT: np.int32, og.BaseDataType.INT64: np.int64, og.BaseDataType.HALF: np.float16, og.BaseDataType.FLOAT: np.float32, og.BaseDataType.DOUBLE: np.float64, } supported_basetypes = [ og.BaseDataType.INT, og.BaseDataType.INT64, og.BaseDataType.HALF, og.BaseDataType.FLOAT, og.BaseDataType.DOUBLE, ] basetype_resolution_table = [ [0, 1, 3, 3, 4], # Int [1, 1, 4, 4, 4], # Int64 [3, 4, 2, 3, 4], # Half [3, 4, 3, 3, 4], # Float [4, 4, 4, 4, 4], # Double ] class OgnTutorialGenericMathNode: """Node to multiple two values of any type""" @staticmethod def compute(db) -> bool: """Compute the product of two values, if the types are all resolved. When the types are not compatible for multiplication, or the result type is not compatible with the resolved output type, the method will log an error and fail """ try: # To support multiplying array of vectors by array of scalars we need to broadcast the scalars to match the # shape of the vector array, and we will convert the result to whatever the result is resolved to atype = db.inputs.a.type btype = db.inputs.b.type rtype = db.outputs.product.type result_dtype = dtype_from_basetype.get(rtype.base_type, None) # Use numpy to perform the multiplication in order to automatically handle both scalar and array types # and automatically convert to the resolved output type if atype.array_depth > 0 and btype.array_depth > 0 and btype.tuple_count < atype.tuple_count: r = np.multiply(db.inputs.a.value, db.inputs.b.value[:, np.newaxis], dtype=result_dtype) else: r = np.multiply(db.inputs.a.value, db.inputs.b.value, dtype=result_dtype) db.outputs.product.value = r except TypeError as error: db.log_error(f"Multiplication could not be performed: {error}") return False return True @staticmethod def on_connection_type_resolve(node) -> None: # Resolves the type of the output based on the types of inputs atype = node.get_attribute("inputs:a").get_resolved_type() btype = node.get_attribute("inputs:b").get_resolved_type() productattr = node.get_attribute("outputs:product") producttype = productattr.get_resolved_type() # The output types can be only inferred when both inputs types are resolved. if ( atype.base_type != og.BaseDataType.UNKNOWN and btype.base_type != og.BaseDataType.UNKNOWN and producttype.base_type == og.BaseDataType.UNKNOWN ): # Resolve the base type using the lookup table base_type = og.BaseDataType.DOUBLE a_index = supported_basetypes.index(atype.base_type) b_index = supported_basetypes.index(btype.base_type) if a_index >= 0 and b_index >= 0: base_type = supported_basetypes[basetype_resolution_table[a_index][b_index]] productattr.set_resolved_type( og.Type(base_type, max(atype.tuple_count, btype.tuple_count), max(atype.array_depth, btype.array_depth)) )
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial26/tutorial26.rst
.. _ogn_tutorial_generic_math_node: Tutorial 26 - Generic Math Node ================================ This tutorial demonstrates how to compose nodes that perform mathematical operations in python using numpy. Using numpy has the advantage that it is api-compatible to cuNumeric. As demonstrated in the Extended Attributes tutorial, generic math nodes use extended attributes to allow inputs and outputs of arbitrary numeric types, specified using the "numerics" keyword. .. code-block:: json "inputs": { "myNumbericAttribute": { "description": "Accepts an incoming connection from any type of numeric value", "type": ["numerics"] } } OgnTutorialGenericMathNode.ogn -------------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.GenericMathNode", which takes inputs of any numeric types and performs a multiplication. .. literalinclude:: OgnTutorialGenericMathNode.ogn :linenos: :language: json OgnTutorialGenericMathNode.py --------------------------------- The *py* file contains the implementation of the node. It takes two numeric inputs and performs a multiplication, demonstrating how to handle cases where the inputs are both numeric types but vary in precision, format or dimension. .. literalinclude:: OgnTutorialGenericMathNode.py :linenos: :language: python
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial26/OgnTutorialGenericMathNode.ogn
{ "GenericMathNode": { "description": [ "This is a tutorial node. It is functionally equivalent to the built-in Multiply node,", "but written in python as a practical demonstration of using extended attributes to ", "write math nodes that work with any numeric types, including arrays and tuples." ], "version": 1, "language": "python", "uiName": "Tutorial Python Node: Generic Math Node", "categories": "tutorials", "inputs": { "a": { "type": ["numerics"], "description": "First number to multiply", "uiName": "A" }, "b": { "type": ["numerics"], "description": "Second number to multiply", "uiName": "B" } }, "outputs": { "product": { "type": ["numerics"], "description": "Product of the two numbers", "uiName": "Product" } }, "tests" : [ { "inputs:a": {"type": "int", "value": 2}, "inputs:b": {"type": "int", "value": 3}, "outputs:product": {"type": "int", "value": 6} }, { "inputs:a": {"type": "int", "value": 2}, "inputs:b": {"type": "int64", "value": 3}, "outputs:product": {"type": "int64", "value": 6} }, { "inputs:a": {"type": "int", "value": 2}, "inputs:b": {"type": "half", "value": 3}, "outputs:product": {"type": "float", "value": 6} }, { "inputs:a": {"type": "int", "value": 2}, "inputs:b": {"type": "float", "value": 3}, "outputs:product": {"type": "float", "value": 6} }, { "inputs:a": {"type": "int", "value": 2}, "inputs:b": {"type": "double", "value": 3}, "outputs:product": {"type": "double", "value": 6} }, { "inputs:a": {"type": "int64", "value": 2}, "inputs:b": {"type": "int64", "value": 3}, "outputs:product": {"type": "int64", "value": 6} }, { "inputs:a": {"type": "int64", "value": 2}, "inputs:b": {"type": "half", "value": 3}, "outputs:product": {"type": "double", "value": 6} }, { "inputs:a": {"type": "int64", "value": 2}, "inputs:b": {"type": "float", "value": 3}, "outputs:product": {"type": "double", "value": 6} }, { "inputs:a": {"type": "int64", "value": 2}, "inputs:b": {"type": "double", "value": 3}, "outputs:product": {"type": "double", "value": 6} }, { "inputs:a": {"type": "half", "value": 2}, "inputs:b": {"type": "half", "value": 3}, "outputs:product": {"type": "half", "value": 6} }, { "inputs:a": {"type": "half", "value": 2}, "inputs:b": {"type": "float", "value": 3}, "outputs:product": {"type": "float", "value": 6} }, { "inputs:a": {"type": "half", "value": 2}, "inputs:b": {"type": "double", "value": 3}, "outputs:product": {"type": "double", "value": 6} }, { "inputs:a": {"type": "float", "value": 2}, "inputs:b": {"type": "float", "value": 3}, "outputs:product": {"type": "float", "value": 6} }, { "inputs:a": {"type": "float", "value": 2}, "inputs:b": {"type": "double", "value": 3}, "outputs:product": {"type": "double", "value": 6} }, { "inputs:a": {"type": "double", "value": 2}, "inputs:b": {"type": "double", "value": 3}, "outputs:product": {"type": "double", "value": 6} }, { "inputs:a": {"type": "double[2]", "value": [1.0, 42.0]}, "inputs:b": {"type": "double[2]", "value": [2.0, 1.0]}, "outputs:product": {"type": "double[2]", "value": [2.0, 42.0]} }, { "inputs:a": {"type": "double[]", "value": [1.0, 42.0]}, "inputs:b": {"type": "double", "value": 2.0}, "outputs:product": {"type": "double[]", "value": [2.0, 84.0]} }, { "inputs:a": {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, "inputs:b": {"type": "double[2]", "value": [5, 5]}, "outputs:product": {"type": "double[2][]", "value": [[50, 25], [5, 5]]} } ] } }
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialTupleData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'outputs': [ ['outputs:a_double2', [2.1, 3.2], False], ['outputs:a_float2', [5.4, 6.5], False], ['outputs:a_half2', [8.0, 9.0], False], ['outputs:a_int2', [11, 12], False], ['outputs:a_float3', [7.6, 8.7, 9.8], False], ['outputs:a_double3', [2.1, 3.2, 4.3], False], ], }, { 'inputs': [ ['inputs:a_double2', [2.1, 3.2], False], ['inputs:a_float2', [5.1, 6.2], False], ['inputs:a_half2', [8.0, 9.0], False], ['inputs:a_int2', [11, 12], False], ['inputs:a_float3', [7.1, 8.2, 9.3], False], ['inputs:a_double3', [10.1, 11.2, 12.3], False], ], 'outputs': [ ['outputs:a_double2', [3.1, 4.2], False], ['outputs:a_float2', [6.1, 7.2], False], ['outputs:a_half2', [9.0, 10.0], False], ['outputs:a_int2', [12, 13], False], ['outputs:a_float3', [8.1, 9.2, 10.3], False], ['outputs:a_double3', [11.1, 12.2, 13.3], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_tutorials_TupleData", "omni.tutorials.TupleData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.tutorials.TupleData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_tutorials_TupleData","omni.tutorials.TupleData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.tutorials.TupleData User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_tutorials_TupleData", "omni.tutorials.TupleData", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.tutorials.TupleData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialTupleDataDatabase import OgnTutorialTupleDataDatabase test_file_name = "OgnTutorialTupleDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_tutorials_TupleData") database = OgnTutorialTupleDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a_double2")) attribute = test_node.get_attribute("inputs:a_double2") db_value = database.inputs.a_double2 expected_value = [1.1, 2.2] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_double3")) attribute = test_node.get_attribute("inputs:a_double3") db_value = database.inputs.a_double3 expected_value = [1.1, 2.2, 3.3] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_float2")) attribute = test_node.get_attribute("inputs:a_float2") db_value = database.inputs.a_float2 expected_value = [4.4, 5.5] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_float3")) attribute = test_node.get_attribute("inputs:a_float3") db_value = database.inputs.a_float3 expected_value = [6.6, 7.7, 8.8] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_half2")) attribute = test_node.get_attribute("inputs:a_half2") db_value = database.inputs.a_half2 expected_value = [7.0, 8.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int2")) attribute = test_node.get_attribute("inputs:a_int2") db_value = database.inputs.a_int2 expected_value = [10, 11] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:a_double2")) attribute = test_node.get_attribute("outputs:a_double2") db_value = database.outputs.a_double2 self.assertTrue(test_node.get_attribute_exists("outputs:a_double3")) attribute = test_node.get_attribute("outputs:a_double3") db_value = database.outputs.a_double3 self.assertTrue(test_node.get_attribute_exists("outputs:a_float2")) attribute = test_node.get_attribute("outputs:a_float2") db_value = database.outputs.a_float2 self.assertTrue(test_node.get_attribute_exists("outputs:a_float3")) attribute = test_node.get_attribute("outputs:a_float3") db_value = database.outputs.a_float3 self.assertTrue(test_node.get_attribute_exists("outputs:a_half2")) attribute = test_node.get_attribute("outputs:a_half2") db_value = database.outputs.a_half2 self.assertTrue(test_node.get_attribute_exists("outputs:a_int2")) attribute = test_node.get_attribute("outputs:a_int2") db_value = database.outputs.a_int2
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCpuGpuBundlesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCpuGpuBundlesPyDatabase import OgnTutorialCpuGpuBundlesPyDatabase test_file_name = "OgnTutorialCpuGpuBundlesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CpuGpuBundlesPy") database = OgnTutorialCpuGpuBundlesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:cpuBundle")) attribute = test_node.get_attribute("inputs:cpuBundle") db_value = database.inputs.cpuBundle self.assertTrue(test_node.get_attribute_exists("inputs:gpu")) attribute = test_node.get_attribute("inputs:gpu") db_value = database.inputs.gpu expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:gpuBundle")) attribute = test_node.get_attribute("inputs:gpuBundle") self.assertTrue(test_node.get_attribute_exists("outputs_cpuGpuBundle")) attribute = test_node.get_attribute("outputs_cpuGpuBundle") db_value = database.outputs.cpuGpuBundle
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCpuGpuExtended.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:cpuData', {'type': 'pointf[3][]', 'value': [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]}, False], ['inputs:gpuData', {'type': 'pointf[3][]', 'value': [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]}, True], ['inputs:gpu', False, False], ], 'outputs': [ ['outputs:cpuGpuSum', {'type': 'pointf[3][]', 'value': [[8.0, 10.0, 12.0], [14.0, 16.0, 18.0]]}, False], ], }, { 'inputs': [ ['inputs:cpuData', {'type': 'pointf[3][]', 'value': [[4.0, 5.0, 6.0]]}, False], ['inputs:gpuData', {'type': 'pointf[3][]', 'value': [[7.0, 8.0, 9.0]]}, True], ['inputs:gpu', True, False], ], 'outputs': [ ['outputs:cpuGpuSum', {'type': 'pointf[3][]', 'value': [[11.0, 13.0, 15.0]]}, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CpuGpuExtended", "omni.graph.tutorials.CpuGpuExtended", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CpuGpuExtended User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CpuGpuExtended","omni.graph.tutorials.CpuGpuExtended", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CpuGpuExtended User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCpuGpuExtendedDatabase import OgnTutorialCpuGpuExtendedDatabase test_file_name = "OgnTutorialCpuGpuExtendedTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CpuGpuExtended") database = OgnTutorialCpuGpuExtendedDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:gpu")) attribute = test_node.get_attribute("inputs:gpu") db_value = database.inputs.gpu expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialDynamicAttributes.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialDynamicAttributesDatabase import OgnTutorialDynamicAttributesDatabase test_file_name = "OgnTutorialDynamicAttributesTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_DynamicAttributes") database = OgnTutorialDynamicAttributesDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:value")) attribute = test_node.get_attribute("inputs:value") db_value = database.inputs.value expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCpuGpuBundles.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCpuGpuBundlesDatabase import OgnTutorialCpuGpuBundlesDatabase test_file_name = "OgnTutorialCpuGpuBundlesTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CpuGpuBundles") database = OgnTutorialCpuGpuBundlesDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:cpuBundle")) attribute = test_node.get_attribute("inputs:cpuBundle") db_value = database.inputs.cpuBundle self.assertTrue(test_node.get_attribute_exists("inputs:gpu")) attribute = test_node.get_attribute("inputs:gpu") db_value = database.inputs.gpu expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:gpuBundle")) attribute = test_node.get_attribute("inputs:gpuBundle") self.assertTrue(test_node.get_attribute_exists("outputs_cpuGpuBundle")) attribute = test_node.get_attribute("outputs_cpuGpuBundle") db_value = database.outputs.cpuGpuBundle
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCudaDataCpu.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:multiplier', [1.0, 2.0, 3.0], True], ['inputs:points', [[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]], True], ], 'outputs': [ ['outputs:points', [[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [3.0, 6.0, 9.0]], True], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CudaCpuArrays", "omni.graph.tutorials.CudaCpuArrays", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CudaCpuArrays User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CudaCpuArrays","omni.graph.tutorials.CudaCpuArrays", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CudaCpuArrays User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCudaDataCpuDatabase import OgnTutorialCudaDataCpuDatabase test_file_name = "OgnTutorialCudaDataCpuTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CudaCpuArrays") database = OgnTutorialCudaDataCpuDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") expected_value = [1.0, 1.0, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:points")) attribute = test_node.get_attribute("inputs:points") db_value = database.inputs.points.cpu expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points")
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCudaDataCpuPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCudaDataCpuPyDatabase import OgnTutorialCudaDataCpuPyDatabase test_file_name = "OgnTutorialCudaDataCpuPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CudaCpuArraysPy") database = OgnTutorialCudaDataCpuPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") expected_value = [1.0, 1.0, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:points")) attribute = test_node.get_attribute("inputs:points") expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("outputs_outBundle")) attribute = test_node.get_attribute("outputs_outBundle") db_value = database.outputs.outBundle self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points")
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialDynamicAttributesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialDynamicAttributesPyDatabase import OgnTutorialDynamicAttributesPyDatabase test_file_name = "OgnTutorialDynamicAttributesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_DynamicAttributesPy") database = OgnTutorialDynamicAttributesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:value")) attribute = test_node.get_attribute("inputs:value") db_value = database.inputs.value expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialSIMDAdd.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialSIMDAddDatabase import OgnTutorialSIMDAddDatabase test_file_name = "OgnTutorialSIMDAddTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_TutorialSIMDFloatAdd") database = OgnTutorialSIMDAddDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a")) attribute = test_node.get_attribute("inputs:a") db_value = database.inputs.a expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:b")) attribute = test_node.get_attribute("inputs:b") db_value = database.inputs.b expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialStateAttributesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'state_set': [ ['state:monotonic', 7, False], ], 'state_get': [ ['state:reset', False, False], ['state:monotonic', 8, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_StateAttributesPy", "omni.graph.tutorials.StateAttributesPy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.StateAttributesPy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_StateAttributesPy","omni.graph.tutorials.StateAttributesPy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.StateAttributesPy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialStateAttributesPyDatabase import OgnTutorialStateAttributesPyDatabase test_file_name = "OgnTutorialStateAttributesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_StateAttributesPy") database = OgnTutorialStateAttributesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:ignored")) attribute = test_node.get_attribute("inputs:ignored") db_value = database.inputs.ignored expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("state:monotonic")) attribute = test_node.get_attribute("state:monotonic") db_value = database.state.monotonic self.assertTrue(test_node.get_attribute_exists("state:reset")) attribute = test_node.get_attribute("state:reset") db_value = database.state.reset
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialArrayData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:original', [1.0, 2.0, 3.0], False], ['inputs:gates', [True, False, True], False], ['inputs:multiplier', 2.0, False], ], 'outputs': [ ['outputs:result', [2.0, 2.0, 6.0], False], ['outputs:negativeValues', [False, False, False], False], ['outputs:infoSize', 13, False], ], }, { 'inputs': [ ['inputs:original', [10.0, -20.0, 30.0], False], ['inputs:gates', [True, False, True], False], ], 'outputs': [ ['outputs:result', [10.0, -20.0, 30.0], False], ['outputs:negativeValues', [False, True, False], False], ], }, { 'inputs': [ ['inputs:info', ["Hello", "lamp\"post", "what'cha", "knowing"], False], ], 'outputs': [ ['outputs:infoSize', 29, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_ArrayData", "omni.graph.tutorials.ArrayData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.ArrayData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_ArrayData","omni.graph.tutorials.ArrayData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.ArrayData User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_ArrayData", "omni.graph.tutorials.ArrayData", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.ArrayData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialArrayDataDatabase import OgnTutorialArrayDataDatabase test_file_name = "OgnTutorialArrayDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_ArrayData") database = OgnTutorialArrayDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:gates")) attribute = test_node.get_attribute("inputs:gates") db_value = database.inputs.gates expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:info")) attribute = test_node.get_attribute("inputs:info") db_value = database.inputs.info expected_value = ['There', 'is', 'no', 'data'] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") db_value = database.inputs.multiplier expected_value = 1.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:original")) attribute = test_node.get_attribute("inputs:original") db_value = database.inputs.original expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:infoSize")) attribute = test_node.get_attribute("outputs:infoSize") db_value = database.outputs.infoSize self.assertTrue(test_node.get_attribute_exists("outputs:negativeValues")) attribute = test_node.get_attribute("outputs:negativeValues") db_value = database.outputs.negativeValues self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundlesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundlesPyDatabase import OgnTutorialBundlesPyDatabase test_file_name = "OgnTutorialBundlesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleManipulationPy") database = OgnTutorialBundlesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:filteredBundle")) attribute = test_node.get_attribute("inputs:filteredBundle") db_value = database.inputs.filteredBundle self.assertTrue(test_node.get_attribute_exists("inputs:filters")) attribute = test_node.get_attribute("inputs:filters") db_value = database.inputs.filters expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:fullBundle")) attribute = test_node.get_attribute("inputs:fullBundle") db_value = database.inputs.fullBundle self.assertTrue(test_node.get_attribute_exists("outputs_combinedBundle")) attribute = test_node.get_attribute("outputs_combinedBundle") db_value = database.outputs.combinedBundle
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialTokens.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:valuesToCheck', ["red", "Red", "magenta", "green", "cyan", "blue", "yellow"], False], ], 'outputs': [ ['outputs:isColor', [True, False, False, True, False, True, False], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Tokens", "omni.graph.tutorials.Tokens", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Tokens User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Tokens","omni.graph.tutorials.Tokens", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Tokens User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_Tokens", "omni.graph.tutorials.Tokens", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.Tokens User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialTokensDatabase import OgnTutorialTokensDatabase test_file_name = "OgnTutorialTokensTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_Tokens") database = OgnTutorialTokensDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:valuesToCheck")) attribute = test_node.get_attribute("inputs:valuesToCheck") db_value = database.inputs.valuesToCheck expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:isColor")) attribute = test_node.get_attribute("outputs:isColor") db_value = database.outputs.isColor
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialVectorizedABIPassthrough.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:value', 1, False], ], 'outputs': [ ['outputs:value', 1, False], ], }, { 'inputs': [ ['inputs:value', 2, False], ], 'outputs': [ ['outputs:value', 2, False], ], }, { 'inputs': [ ['inputs:value', 3, False], ], 'outputs': [ ['outputs:value', 3, False], ], }, { 'inputs': [ ['inputs:value', 4, False], ], 'outputs': [ ['outputs:value', 4, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TutorialVectorizedABIPassThrough", "omni.graph.tutorials.TutorialVectorizedABIPassThrough", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TutorialVectorizedABIPassThrough User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TutorialVectorizedABIPassThrough","omni.graph.tutorials.TutorialVectorizedABIPassThrough", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TutorialVectorizedABIPassThrough User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialVectorizedABIPassthroughDatabase import OgnTutorialVectorizedABIPassthroughDatabase test_file_name = "OgnTutorialVectorizedABIPassthroughTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_TutorialVectorizedABIPassThrough") database = OgnTutorialVectorizedABIPassthroughDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:value")) attribute = test_node.get_attribute("inputs:value") db_value = database.inputs.value expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:value")) attribute = test_node.get_attribute("outputs:value") db_value = database.outputs.value
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialABIPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:color', [0.2, 0.4, 0.4], False], ], 'outputs': [ ['outputs:h', 0.5, False], ['outputs:s', 0.5, False], ['outputs:v', 0.4, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_AbiPy", "omni.graph.tutorials.AbiPy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.AbiPy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_AbiPy","omni.graph.tutorials.AbiPy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.AbiPy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialABIPyDatabase import OgnTutorialABIPyDatabase test_file_name = "OgnTutorialABIPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_AbiPy") database = OgnTutorialABIPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:color")) attribute = test_node.get_attribute("inputs:color") db_value = database.inputs.color expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:h")) attribute = test_node.get_attribute("outputs:h") db_value = database.outputs.h self.assertTrue(test_node.get_attribute_exists("outputs:s")) attribute = test_node.get_attribute("outputs:s") db_value = database.outputs.s self.assertTrue(test_node.get_attribute_exists("outputs:v")) attribute = test_node.get_attribute("outputs:v") db_value = database.outputs.v
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCpuGpuData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:is_gpu', False, False], ['inputs:a', 1.0, True], ['inputs:b', 2.0, True], ], 'outputs': [ ['outputs:sum', 3.0, False], ], }, { 'inputs': [ ['inputs:is_gpu', False, False], ['inputs:a', 5.0, True], ['inputs:b', 3.0, True], ], 'outputs': [ ['outputs:sum', 8.0, False], ], }, { 'inputs': [ ['inputs:is_gpu', False, False], ['inputs:points', [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], True], ['inputs:multiplier', [2.0, 3.0, 4.0], True], ], 'outputs': [ ['outputs:points', [[2.0, 6.0, 12.0], [4.0, 9.0, 16.0]], False], ], }, { 'inputs': [ ['inputs:is_gpu', True, False], ['inputs:a', 1.0, True], ['inputs:b', 2.0, True], ['inputs:points', [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], True], ['inputs:multiplier', [2.0, 3.0, 4.0], True], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CpuGpuData", "omni.graph.tutorials.CpuGpuData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CpuGpuData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CpuGpuData","omni.graph.tutorials.CpuGpuData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CpuGpuData User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCpuGpuDataDatabase import OgnTutorialCpuGpuDataDatabase test_file_name = "OgnTutorialCpuGpuDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CpuGpuData") database = OgnTutorialCpuGpuDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a")) attribute = test_node.get_attribute("inputs:a") db_value = database.inputs.a.cpu expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:b")) attribute = test_node.get_attribute("inputs:b") db_value = database.inputs.b.cpu expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:is_gpu")) attribute = test_node.get_attribute("inputs:is_gpu") db_value = database.inputs.is_gpu expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") db_value = database.inputs.multiplier.cpu expected_value = [1.0, 1.0, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:points")) attribute = test_node.get_attribute("inputs:points") db_value = database.inputs.points.cpu expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points.cpu self.assertTrue(test_node.get_attribute_exists("outputs:sum")) attribute = test_node.get_attribute("outputs:sum") db_value = database.outputs.sum.cpu
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundleDataPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundleDataPyDatabase import OgnTutorialBundleDataPyDatabase test_file_name = "OgnTutorialBundleDataPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleDataPy") database = OgnTutorialBundleDataPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:bundle")) attribute = test_node.get_attribute("inputs:bundle") db_value = database.inputs.bundle self.assertTrue(test_node.get_attribute_exists("outputs_bundle")) attribute = test_node.get_attribute("outputs_bundle") db_value = database.outputs.bundle
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialCudaData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a', 1.0, True], ['inputs:b', 2.0, True], ['inputs:half', 1.0, True], ['inputs:color', [0.5, 0.6, 0.7], True], ['inputs:matrix', [1.0, 2.0, 3.0, 4.0, 2.0, 3.0, 4.0, 5.0, 3.0, 4.0, 5.0, 6.0, 4.0, 5.0, 6.0, 7.0], True], ['inputs:points', [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], True], ['inputs:multiplier', [2.0, 3.0, 4.0], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CudaData", "omni.graph.tutorials.CudaData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CudaData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_CudaData","omni.graph.tutorials.CudaData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.CudaData User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_CudaData", "omni.graph.tutorials.CudaData", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.CudaData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialCudaDataDatabase import OgnTutorialCudaDataDatabase test_file_name = "OgnTutorialCudaDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_CudaData") database = OgnTutorialCudaDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a")) attribute = test_node.get_attribute("inputs:a") expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:b")) attribute = test_node.get_attribute("inputs:b") expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:color")) attribute = test_node.get_attribute("inputs:color") expected_value = [1.0, 0.5, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:half")) attribute = test_node.get_attribute("inputs:half") expected_value = 1.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:matrix")) attribute = test_node.get_attribute("inputs:matrix") expected_value = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("inputs:multiplier")) attribute = test_node.get_attribute("inputs:multiplier") db_value = database.inputs.multiplier expected_value = [1.0, 1.0, 1.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:points")) attribute = test_node.get_attribute("inputs:points") expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("outputs:color")) attribute = test_node.get_attribute("outputs:color") self.assertTrue(test_node.get_attribute_exists("outputs:half")) attribute = test_node.get_attribute("outputs:half") self.assertTrue(test_node.get_attribute_exists("outputs:matrix")) attribute = test_node.get_attribute("outputs:matrix") self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") self.assertTrue(test_node.get_attribute_exists("outputs:sum")) attribute = test_node.get_attribute("outputs:sum")
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialGenericMathNode.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'int', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'int', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'int64', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'int64', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'half', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'float', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'float', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'float', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int64', 'value': 2}, False], ['inputs:b', {'type': 'int64', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'int64', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int64', 'value': 2}, False], ['inputs:b', {'type': 'half', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int64', 'value': 2}, False], ['inputs:b', {'type': 'float', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'int64', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'half', 'value': 2}, False], ['inputs:b', {'type': 'half', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'half', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'half', 'value': 2}, False], ['inputs:b', {'type': 'float', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'float', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'half', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'float', 'value': 2}, False], ['inputs:b', {'type': 'float', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'float', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'float', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'double', 'value': 2}, False], ['inputs:b', {'type': 'double', 'value': 3}, False], ], 'outputs': [ ['outputs:product', {'type': 'double', 'value': 6}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'double[2]', 'value': [1.0, 42.0]}, False], ['inputs:b', {'type': 'double[2]', 'value': [2.0, 1.0]}, False], ], 'outputs': [ ['outputs:product', {'type': 'double[2]', 'value': [2.0, 42.0]}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'double[]', 'value': [1.0, 42.0]}, False], ['inputs:b', {'type': 'double', 'value': 2.0}, False], ], 'outputs': [ ['outputs:product', {'type': 'double[]', 'value': [2.0, 84.0]}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'double[2][]', 'value': [[10, 5], [1, 1]]}, False], ['inputs:b', {'type': 'double[2]', 'value': [5, 5]}, False], ], 'outputs': [ ['outputs:product', {'type': 'double[2][]', 'value': [[50, 25], [5, 5]]}, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_GenericMathNode", "omni.graph.tutorials.GenericMathNode", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.GenericMathNode User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_GenericMathNode","omni.graph.tutorials.GenericMathNode", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.GenericMathNode User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialGenericMathNodeDatabase import OgnTutorialGenericMathNodeDatabase test_file_name = "OgnTutorialGenericMathNodeTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_GenericMathNode") database = OgnTutorialGenericMathNodeDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/__init__.py
"""====== GENERATED BY omni.graph.tools - DO NOT EDIT ======""" import omni.graph.tools._internal as ogi ogi.import_tests_in_directory(__file__, __name__)
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialSimpleDataPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a_bool', False, False], ], 'outputs': [ ['outputs:a_bool', True, False], ], }, { 'inputs': [ ['inputs:a_bool', True, False], ], 'outputs': [ ['outputs:a_bool', False, False], ['outputs:a_a_boolUiName', "Simple Boolean Input", False], ['outputs:a_nodeTypeUiName', "Tutorial Python Node: Attributes With Simple Data", False], ], }, { 'inputs': [ ['inputs:a_path', "/World/Domination", False], ], 'outputs': [ ['outputs:a_path', "/World/Domination/Child", False], ], }, { 'inputs': [ ['inputs:a_bool', False, False], ['inputs:a_double', 1.1, False], ['inputs:a_float', 3.3, False], ['inputs:a_half', 5.0, False], ['inputs:a_int', 7, False], ['inputs:a_int64', 9, False], ['inputs:a_token', "helloToken", False], ['inputs:a_string', "helloString", False], ['inputs:a_objectId', 10, False], ['inputs:a_uchar', 11, False], ['inputs:a_uint', 13, False], ['inputs:a_uint64', 15, False], ], 'outputs': [ ['outputs:a_bool', True, False], ['outputs:a_double', 2.1, False], ['outputs:a_float', 4.3, False], ['outputs:a_half', 6.0, False], ['outputs:a_int', 8, False], ['outputs:a_int64', 10, False], ['outputs:a_token', "worldToken", False], ['outputs:a_string', "worldString", False], ['outputs:a_objectId', 11, False], ['outputs:a_uchar', 12, False], ['outputs:a_uint', 14, False], ['outputs:a_uint64', 16, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_SimpleDataPy", "omni.graph.tutorials.SimpleDataPy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.SimpleDataPy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_SimpleDataPy","omni.graph.tutorials.SimpleDataPy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.SimpleDataPy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialSimpleDataPyDatabase import OgnTutorialSimpleDataPyDatabase test_file_name = "OgnTutorialSimpleDataPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_SimpleDataPy") database = OgnTutorialSimpleDataPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a_constant_input")) attribute = test_node.get_attribute("inputs:a_constant_input") db_value = database.inputs.a_constant_input expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_double")) attribute = test_node.get_attribute("inputs:a_double") db_value = database.inputs.a_double expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_float")) attribute = test_node.get_attribute("inputs:a_float") db_value = database.inputs.a_float expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_half")) attribute = test_node.get_attribute("inputs:a_half") db_value = database.inputs.a_half expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int")) attribute = test_node.get_attribute("inputs:a_int") db_value = database.inputs.a_int expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int64")) attribute = test_node.get_attribute("inputs:a_int64") db_value = database.inputs.a_int64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_objectId")) attribute = test_node.get_attribute("inputs:a_objectId") db_value = database.inputs.a_objectId expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_path")) attribute = test_node.get_attribute("inputs:a_path") db_value = database.inputs.a_path expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_string")) attribute = test_node.get_attribute("inputs:a_string") db_value = database.inputs.a_string expected_value = "helloString" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_token")) attribute = test_node.get_attribute("inputs:a_token") db_value = database.inputs.a_token expected_value = "helloToken" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_uchar")) attribute = test_node.get_attribute("inputs:a_uchar") db_value = database.inputs.a_uchar expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_uint")) attribute = test_node.get_attribute("inputs:a_uint") db_value = database.inputs.a_uint expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_uint64")) attribute = test_node.get_attribute("inputs:a_uint64") db_value = database.inputs.a_uint64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:a_a_boolUiName")) attribute = test_node.get_attribute("outputs:a_a_boolUiName") db_value = database.outputs.a_a_boolUiName self.assertTrue(test_node.get_attribute_exists("outputs:a_bool")) attribute = test_node.get_attribute("outputs:a_bool") db_value = database.outputs.a_bool self.assertTrue(test_node.get_attribute_exists("outputs:a_double")) attribute = test_node.get_attribute("outputs:a_double") db_value = database.outputs.a_double self.assertTrue(test_node.get_attribute_exists("outputs:a_float")) attribute = test_node.get_attribute("outputs:a_float") db_value = database.outputs.a_float self.assertTrue(test_node.get_attribute_exists("outputs:a_half")) attribute = test_node.get_attribute("outputs:a_half") db_value = database.outputs.a_half self.assertTrue(test_node.get_attribute_exists("outputs:a_int")) attribute = test_node.get_attribute("outputs:a_int") db_value = database.outputs.a_int self.assertTrue(test_node.get_attribute_exists("outputs:a_int64")) attribute = test_node.get_attribute("outputs:a_int64") db_value = database.outputs.a_int64 self.assertTrue(test_node.get_attribute_exists("outputs:a_nodeTypeUiName")) attribute = test_node.get_attribute("outputs:a_nodeTypeUiName") db_value = database.outputs.a_nodeTypeUiName self.assertTrue(test_node.get_attribute_exists("outputs:a_objectId")) attribute = test_node.get_attribute("outputs:a_objectId") db_value = database.outputs.a_objectId self.assertTrue(test_node.get_attribute_exists("outputs:a_path")) attribute = test_node.get_attribute("outputs:a_path") db_value = database.outputs.a_path self.assertTrue(test_node.get_attribute_exists("outputs:a_string")) attribute = test_node.get_attribute("outputs:a_string") db_value = database.outputs.a_string self.assertTrue(test_node.get_attribute_exists("outputs:a_token")) attribute = test_node.get_attribute("outputs:a_token") db_value = database.outputs.a_token self.assertTrue(test_node.get_attribute_exists("outputs:a_uchar")) attribute = test_node.get_attribute("outputs:a_uchar") db_value = database.outputs.a_uchar self.assertTrue(test_node.get_attribute_exists("outputs:a_uint")) attribute = test_node.get_attribute("outputs:a_uint") db_value = database.outputs.a_uint self.assertTrue(test_node.get_attribute_exists("outputs:a_uint64")) attribute = test_node.get_attribute("outputs:a_uint64") db_value = database.outputs.a_uint64
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialSimpleData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a_bool', False, False], ], 'outputs': [ ['outputs:a_bool', True, False], ], }, { 'inputs': [ ['inputs:a_bool', True, False], ], 'outputs': [ ['outputs:a_bool', False, False], ], }, { 'inputs': [ ['inputs:a_bool', False, False], ['inputs:a_double', 1.1, False], ['inputs:a_float', 3.3, False], ['inputs:a_half', 5.0, False], ['inputs:a_int', 7, False], ['inputs:a_int64', 9, False], ['inputs:a_token', "helloToken", False], ['inputs:a_string', "helloString", False], ['inputs:a_objectId', 5, False], ['inputs:unsigned:a_uchar', 11, False], ['inputs:unsigned:a_uint', 13, False], ['inputs:unsigned:a_uint64', 15, False], ], 'outputs': [ ['outputs:a_bool', True, False], ['outputs:a_double', 2.1, False], ['outputs:a_float', 4.3, False], ['outputs:a_half', 6.0, False], ['outputs:a_int', 8, False], ['outputs:a_int64', 10, False], ['outputs:a_token', "worldToken", False], ['outputs:a_string', "worldString", False], ['outputs:a_objectId', 6, False], ['outputs:unsigned:a_uchar', 12, False], ['outputs:unsigned:a_uint', 14, False], ['outputs:unsigned:a_uint64', 16, False], ], }, { 'inputs': [ ['inputs:a_token', "hello'Token", False], ['inputs:a_string', "hello\"String", False], ], 'outputs': [ ['outputs:a_token', "world'Token", False], ['outputs:a_string', "world\"String", False], ], }, { 'inputs': [ ['inputs:a_path', "/World/Domination", False], ], 'outputs': [ ['outputs:a_path', "/World/Domination/Child", False], ], }, { 'outputs': [ ['outputs:a_token', "worldToken", False], ['outputs:a_string', "worldString", False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_SimpleData", "omni.graph.tutorials.SimpleData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.SimpleData User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_SimpleData","omni.graph.tutorials.SimpleData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.SimpleData User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_SimpleData", "omni.graph.tutorials.SimpleData", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.SimpleData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialSimpleDataDatabase import OgnTutorialSimpleDataDatabase test_file_name = "OgnTutorialSimpleDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_SimpleData") database = OgnTutorialSimpleDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a_bool")) attribute = test_node.get_attribute("inputs:a_bool") db_value = database.inputs.a_bool expected_value = True actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_constant_input")) attribute = test_node.get_attribute("inputs:a_constant_input") db_value = database.inputs.a_constant_input expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_double")) attribute = test_node.get_attribute("inputs:a_double") db_value = database.inputs.a_double expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_float")) attribute = test_node.get_attribute("inputs:a_float") db_value = database.inputs.a_float expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_half")) attribute = test_node.get_attribute("inputs:a_half") db_value = database.inputs.a_half expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int")) attribute = test_node.get_attribute("inputs:a_int") db_value = database.inputs.a_int expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_int64")) attribute = test_node.get_attribute("inputs:a_int64") db_value = database.inputs.a_int64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_objectId")) attribute = test_node.get_attribute("inputs:a_objectId") db_value = database.inputs.a_objectId expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_path")) attribute = test_node.get_attribute("inputs:a_path") db_value = database.inputs.a_path expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_string")) attribute = test_node.get_attribute("inputs:a_string") db_value = database.inputs.a_string expected_value = "helloString" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_token")) attribute = test_node.get_attribute("inputs:a_token") db_value = database.inputs.a_token expected_value = "helloToken" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:unsigned:a_uchar")) attribute = test_node.get_attribute("inputs:unsigned:a_uchar") db_value = database.inputs.unsigned_a_uchar expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:unsigned:a_uint")) attribute = test_node.get_attribute("inputs:unsigned:a_uint") db_value = database.inputs.unsigned_a_uint expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:unsigned:a_uint64")) attribute = test_node.get_attribute("inputs:unsigned:a_uint64") db_value = database.inputs.unsigned_a_uint64 expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:a_bool")) attribute = test_node.get_attribute("outputs:a_bool") db_value = database.outputs.a_bool self.assertTrue(test_node.get_attribute_exists("outputs:a_double")) attribute = test_node.get_attribute("outputs:a_double") db_value = database.outputs.a_double self.assertTrue(test_node.get_attribute_exists("outputs:a_float")) attribute = test_node.get_attribute("outputs:a_float") db_value = database.outputs.a_float self.assertTrue(test_node.get_attribute_exists("outputs:a_half")) attribute = test_node.get_attribute("outputs:a_half") db_value = database.outputs.a_half self.assertTrue(test_node.get_attribute_exists("outputs:a_int")) attribute = test_node.get_attribute("outputs:a_int") db_value = database.outputs.a_int self.assertTrue(test_node.get_attribute_exists("outputs:a_int64")) attribute = test_node.get_attribute("outputs:a_int64") db_value = database.outputs.a_int64 self.assertTrue(test_node.get_attribute_exists("outputs:a_objectId")) attribute = test_node.get_attribute("outputs:a_objectId") db_value = database.outputs.a_objectId self.assertTrue(test_node.get_attribute_exists("outputs:a_path")) attribute = test_node.get_attribute("outputs:a_path") db_value = database.outputs.a_path self.assertTrue(test_node.get_attribute_exists("outputs:a_string")) attribute = test_node.get_attribute("outputs:a_string") db_value = database.outputs.a_string self.assertTrue(test_node.get_attribute_exists("outputs:a_token")) attribute = test_node.get_attribute("outputs:a_token") db_value = database.outputs.a_token self.assertTrue(test_node.get_attribute_exists("outputs:unsigned:a_uchar")) attribute = test_node.get_attribute("outputs:unsigned:a_uchar") db_value = database.outputs.unsigned_a_uchar self.assertTrue(test_node.get_attribute_exists("outputs:unsigned:a_uint")) attribute = test_node.get_attribute("outputs:unsigned:a_uint") db_value = database.outputs.unsigned_a_uint self.assertTrue(test_node.get_attribute_exists("outputs:unsigned:a_uint64")) attribute = test_node.get_attribute("outputs:unsigned:a_uint64") db_value = database.outputs.unsigned_a_uint64
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundleData.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundleDataDatabase import OgnTutorialBundleDataDatabase test_file_name = "OgnTutorialBundleDataTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleData") database = OgnTutorialBundleDataDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:bundle")) attribute = test_node.get_attribute("inputs:bundle") db_value = database.inputs.bundle self.assertTrue(test_node.get_attribute_exists("outputs_bundle")) attribute = test_node.get_attribute("outputs_bundle") db_value = database.outputs.bundle
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialStatePy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:overrideValue', 5, False], ['inputs:override', True, False], ], 'outputs': [ ['outputs:monotonic', 5, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_StatePy", "omni.graph.tutorials.StatePy", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.StatePy User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_StatePy","omni.graph.tutorials.StatePy", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.StatePy User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialStatePyDatabase import OgnTutorialStatePyDatabase test_file_name = "OgnTutorialStatePyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_StatePy") database = OgnTutorialStatePyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:override")) attribute = test_node.get_attribute("inputs:override") db_value = database.inputs.override expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:overrideValue")) attribute = test_node.get_attribute("inputs:overrideValue") db_value = database.inputs.overrideValue expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:monotonic")) attribute = test_node.get_attribute("outputs:monotonic") db_value = database.outputs.monotonic
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialOverrideType.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:data', [1.0, 2.0, 3.0], False], ], 'outputs': [ ['outputs:data', [2.0, 3.0, 1.0], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_OverrideType", "omni.graph.tutorials.OverrideType", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.OverrideType User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_OverrideType","omni.graph.tutorials.OverrideType", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.OverrideType User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_OverrideType", "omni.graph.tutorials.OverrideType", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.OverrideType User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialOverrideTypeDatabase import OgnTutorialOverrideTypeDatabase test_file_name = "OgnTutorialOverrideTypeTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_OverrideType") database = OgnTutorialOverrideTypeDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:data")) attribute = test_node.get_attribute("inputs:data") db_value = database.inputs.data expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:typedData")) attribute = test_node.get_attribute("inputs:typedData") db_value = database.inputs.typedData expected_value = [0.0, 0.0, 0.0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:data")) attribute = test_node.get_attribute("outputs:data") db_value = database.outputs.data self.assertTrue(test_node.get_attribute_exists("outputs:typedData")) attribute = test_node.get_attribute("outputs:typedData") db_value = database.outputs.typedData
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundleAddAttributesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundleAddAttributesPyDatabase import OgnTutorialBundleAddAttributesPyDatabase test_file_name = "OgnTutorialBundleAddAttributesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleAddAttributesPy") database = OgnTutorialBundleAddAttributesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:addedAttributeNames")) attribute = test_node.get_attribute("inputs:addedAttributeNames") db_value = database.inputs.addedAttributeNames expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:removedAttributeNames")) attribute = test_node.get_attribute("inputs:removedAttributeNames") db_value = database.inputs.removedAttributeNames expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:typesToAdd")) attribute = test_node.get_attribute("inputs:typesToAdd") db_value = database.inputs.typesToAdd expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:useBatchedAPI")) attribute = test_node.get_attribute("inputs:useBatchedAPI") db_value = database.inputs.useBatchedAPI expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs_bundle")) attribute = test_node.get_attribute("outputs_bundle") db_value = database.outputs.bundle
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialTupleArrays.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a', [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]], False], ['inputs:b', [[10.0, 5.0, 1.0], [1.0, 5.0, 10.0]], False], ], 'outputs': [ ['outputs:result', [23.0, 57.0], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TupleArrays", "omni.graph.tutorials.TupleArrays", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TupleArrays User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TupleArrays","omni.graph.tutorials.TupleArrays", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TupleArrays User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_tutorials_TupleArrays", "omni.graph.tutorials.TupleArrays", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.tutorials.TupleArrays User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialTupleArraysDatabase import OgnTutorialTupleArraysDatabase test_file_name = "OgnTutorialTupleArraysTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_TupleArrays") database = OgnTutorialTupleArraysDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a")) attribute = test_node.get_attribute("inputs:a") db_value = database.inputs.a expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:b")) attribute = test_node.get_attribute("inputs:b") db_value = database.inputs.b expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialABI.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:namespace:a_bool', True, False], ], 'outputs': [ ['outputs:namespace:a_bool', False, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Abi", "omni.graph.tutorials.Abi", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Abi User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_Abi","omni.graph.tutorials.Abi", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Abi User test case #{i+1}", 16) async def test_data_access(self): test_file_name = "OgnTutorialABITemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_Abi") self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:namespace:a_bool")) attribute = test_node.get_attribute("inputs:namespace:a_bool") expected_value = True actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) self.assertTrue(test_node.get_attribute_exists("outputs:namespace:a_bool")) attribute = test_node.get_attribute("outputs:namespace:a_bool")
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialVectorizedPassthrough.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:value', 1, False], ], 'outputs': [ ['outputs:value', 1, False], ], }, { 'inputs': [ ['inputs:value', 2, False], ], 'outputs': [ ['outputs:value', 2, False], ], }, { 'inputs': [ ['inputs:value', 3, False], ], 'outputs': [ ['outputs:value', 3, False], ], }, { 'inputs': [ ['inputs:value', 4, False], ], 'outputs': [ ['outputs:value', 4, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TutorialVectorizedPassThrough", "omni.graph.tutorials.TutorialVectorizedPassThrough", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TutorialVectorizedPassThrough User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_tutorials_TutorialVectorizedPassThrough","omni.graph.tutorials.TutorialVectorizedPassThrough", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.TutorialVectorizedPassThrough User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialVectorizedPassthroughDatabase import OgnTutorialVectorizedPassthroughDatabase test_file_name = "OgnTutorialVectorizedPassthroughTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_TutorialVectorizedPassThrough") database = OgnTutorialVectorizedPassthroughDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:value")) attribute = test_node.get_attribute("inputs:value") db_value = database.inputs.value expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:value")) attribute = test_node.get_attribute("outputs:value") db_value = database.outputs.value
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialExtendedTypes.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialExtendedTypesDatabase import OgnTutorialExtendedTypesDatabase test_file_name = "OgnTutorialExtendedTypesTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_ExtendedTypes") database = OgnTutorialExtendedTypesDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialExtendedTypesPy.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialExtendedTypesPyDatabase import OgnTutorialExtendedTypesPyDatabase test_file_name = "OgnTutorialExtendedTypesPyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_ExtendedTypesPy") database = OgnTutorialExtendedTypesPyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialBundles.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialBundlesDatabase import OgnTutorialBundlesDatabase test_file_name = "OgnTutorialBundlesTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_tutorials_BundleManipulation") database = OgnTutorialBundlesDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:filteredBundle")) attribute = test_node.get_attribute("inputs:filteredBundle") db_value = database.inputs.filteredBundle self.assertTrue(test_node.get_attribute_exists("inputs:filters")) attribute = test_node.get_attribute("inputs:filters") db_value = database.inputs.filters expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:fullBundle")) attribute = test_node.get_attribute("inputs:fullBundle") db_value = database.inputs.fullBundle self.assertTrue(test_node.get_attribute_exists("outputs_combinedBundle")) attribute = test_node.get_attribute("outputs_combinedBundle") db_value = database.outputs.combinedBundle