file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial11/OgnTutorialComplexDataPy.py
""" Implementation of a node handling complex attribute data """ # This class exercises access to the DataModel through the generated database class for a representative set of # complex data types, including tuples, arrays, arrays of tuples, and role-based attributes. More details on # individual type definitions can be found in the earlier C++ tutorial nodes where each of those types are # explored in detail. # Any Python node with array attributes will receive its data wrapped in a numpy array for efficiency. # Unlike C++ includes, a Python import is not transitive so this has to be explicitly imported here. import numpy import omni.graph.core as og class OgnTutorialComplexDataPy: """Exercise a sample of complex data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """ Multiply a float array by a float[3] to yield a float[3] array, using the point3f role. Practically speaking the data in the role-based attributes is no different than the underlying raw data types. The role only helps you understand what the intention behind the data is, e.g. to differentiate surface normals and colours, both of which might have float[3] types. """ # Verify that the output array was correctly set up to have a "point" role assert db.role.outputs.a_productArray == og.AttributeRole.POSITION multiplier = db.inputs.a_vectorMultiplier input_array = db.inputs.a_inputArray input_array_size = len(db.inputs.a_inputArray) # The output array should have the same number of elements as the input array. # Setting the size informs fabric that when it retrieves the data it should allocate this much space. db.outputs.a_productArray_size = input_array_size # The assertions illustrate the type of data that should have been received for inputs and set for outputs assert isinstance(multiplier, numpy.ndarray) # numpy.ndarray is the underlying type of tuples assert multiplier.shape == (3,) assert isinstance(input_array, numpy.ndarray) # numpy.ndarray is the underlying type of simple arrays assert input_array.shape == (input_array_size,) # If the input array is empty then the output is empty and does not need any computing if input_array.shape[0] == 0: db.outputs.a_productArray = [] assert db.outputs.a_productArray.shape == (0, 3) return True # numpy has a nice little method for replicating the multiplier vector the number of times required # by the size of the input array. # e.g. numpy.tile( [1, 2], (3, 1) ) yields [[1, 2], [1, 2], [1, 2]] product = numpy.tile(multiplier, (input_array_size, 1)) # Multiply each of the tiled vectors by the corresponding constant in the input array for i in range(0, product.shape[0]): product[i] = product[i] * input_array[i] db.outputs.a_productArray = product # Make sure the correct type of array was produced assert db.outputs.a_productArray.shape == (input_array_size, 3) # Create the output token array by copying the input array with the elements changed to strings db.outputs.a_tokenArray = numpy.array([str(x) for x in input_array]) # Note that at the time of this writing you are not able to assign token arrays element-by-element as you # might do for other types of arrays. So this coding method, usable for other types of arrays such as float[], # would issue a warning and then fail to set the values on the output: # db.outputs.a_tokenArray_size = input_array_size # for index, element in enumerate(input_array): # db.outputs.a_tokenArray[index] = str(element) return True
3,862
Python
51.202702
118
0.690316
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial12/OgnTutorialABIPy.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 OgnTutorialABI.cpp """ import colorsys from contextlib import suppress import carb import omni.graph.core as og class OgnTutorialABIPy: """Illustrate overrides of the various ABI functions available to a Python OmniGraph node""" @staticmethod def compute(context, node) -> bool: """ Convert a color into components using the raw ABI function without the nice Database interface. Rarely Overridden: Usually you will implement the much more friendly and Pythonic compute(OgnTutorialABIDatabasePy) method so that you can have easier access to your data. """ # Manually acquire the data on the known attributes input_color_attr = node.get_attribute("inputs:color") # Extract the input value from the controller input_color = og.Controller.get(input_color_attr) output_hue_attr = node.get_attribute("outputs:h") output_saturation_attr = node.get_attribute("outputs:s") output_value_attr = node.get_attribute("outputs:v") (h, s, v) = colorsys.rgb_to_hsv(*input_color) # This exception is triggered if you accidentally reverse the parameters to set_attr_value. # The error isn't recovered, to prevent proliferation of inconsistent calls. The exception is # thrown to help with debugging. (As this is an example the exception is caught and ignored here.) with suppress(og.OmniGraphError): og.Controller.set(h, output_hue_attr) og.Controller.set(output_hue_attr, h) og.Controller.set(output_saturation_attr, s) og.Controller.set(output_value_attr, v) # # For comparison, here is the same algorithm implemented using "compute(db)" # # def compute(db) -> bool: # (db.outputs.h, db.outputs.s, db.outputs.v) = colorsys.rgb_to_hsv(*db.inputs.color) return True # ---------------------------------------------------------------------- @staticmethod def get_node_type() -> str: """ Rarely overridden This should almost never be overridden as the auto-generated code will handle the name """ carb.log_info("Python ABI override of get_node_type") return "omni.graph.tutorials.AbiPy" # ---------------------------------------------------------------------- @staticmethod def initialize(graph_context, node): """ Occasionally overridden This method might be overridden to set up initial conditions when a node of this type is created. Note that overridding this puts the onus on the node writer to set up initial conditions such as attribute default values and metadata. When a node is created this will be called """ carb.log_info("Python ABI override of initialize") # There is no default behaviour on initialize so nothing else is needed for this tutorial to function # ---------------------------------------------------------------------- @staticmethod def initialize_type(node_type) -> bool: """ Rarely overridden This method might be overridden to set up initial conditions when a node type is registered. Note that overriding this puts the onus on the node writer to initialize the attributes and metadata. By returning "True" the function is requesting that the attributes and metadata be initialized upon return, otherwise the caller will assume that this override has already done that. """ carb.log_info("Python ABI override of initialize_type") return True # ---------------------------------------------------------------------- @staticmethod def release(node): """ Occasionally overridden After a node is removed it will get a release call where anything set up in initialize() can be torn down """ carb.log_info("Python ABI override of release") # There is no default behaviour on release so nothing else is needed for this tutorial to function # ---------------------------------------------------------------------- @staticmethod def update_node_version(graph_context, node, old_version: int, new_version: int): """ Occasionally overridden This is something you do want to override when you have more than version of your node. In it you would translate attribute information from older versions into the current one. """ carb.log_info(f"Python ABI override of update_node_version from {old_version} to {new_version}") # There is no default behaviour on update_node_version so nothing else is needed for this tutorial to function return old_version < new_version # ---------------------------------------------------------------------- @staticmethod def on_connection_type_resolve(node): """ Occasionally overridden When there is a connection change to this node which results in an extended type attribute being automatically resolved, this callback gives the node a change to resolve other extended type attributes. For example a generic 'Increment' node can resolve its output to an int only after its input has been resolved to an int. Attribute types are resolved using omni.graph.attribute.set_resolved_type(), or the utility functions such as og.resolve_fully_coupled(). """ carb.log_info("Python ABI override of on_connection_type_resolve") # There is no default behaviour for on_connection_type_resolve so nothing else is needed for this # tutorial to function
5,945
Python
43.373134
120
0.632296
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial12/tutorial12.rst
.. _ogn_tutorial_abi_py: Tutorial 12 - Python ABI Override Node ====================================== Although the .ogn format creates an easy-to-use interface to the ABI of the OmniGraph node and the associated data model, there may be cases where you want to override the ABI to perform special processing. OgnTutorialABIPy.ogn -------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.AbiPy", in its first version, with a simple description. .. literalinclude:: OgnTutorialABIPy.ogn :linenos: :language: json OgnTutorialABIPy.py ------------------- The *py* file contains the implementation of the node class with every possible ABI method replaced with customized processing. The node still functions the same as any other node, although it is forced to write a lot of extra boilerplate code to do so. .. literalinclude:: OgnTutorialABIPy.py :linenos: :language: python Metadata Attached To Attributes ------------------------------- This file introduces the *metadata* keyword to attributes, whose value is a dictionary of key/value pairs associated with the attribute in which it appears that may be extracted using the ABI metadata functions. These are not persisted in any files and so must be set either in the .ogn file or in an override of the **initialize()** method in the node definition.
1,368
reStructuredText
39.264705
118
0.720029
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial4/tutorial4.rst
.. _ogn_tutorial_tupleData: Tutorial 4 - Tuple Data Node ============================ Tuple data, also referred to as fixed array data, consists of multiple elements of a simple type. For example *float[3]* or *double[4]*. This node creates one input attribute and one output attribute of each of the simple data types with an element count greater than 1. OgnTutorialTupleData.ogn ------------------------ The *ogn* file shows the implementation of a node named "omni.tutorials.TupleData", which has one input and one matching output attribute of each simple type with element counts greater than one. .. literalinclude:: OgnTutorialTupleData.ogn :linenos: :language: json :emphasize-lines: 2,12 New Concept - Tags ------------------ Often it is helpful to group nodes with common functionality together in some way in the UI. To help with this you can specific values for the **tags** keyword. The values can either be a comma-separated string, or a list, that will be rendered into a comma-separated string when added to the metadata. New Concept - Namespaced Node Type Name --------------------------------------- The standard naming convention uses a simple ``CamelCase`` name, with the extension of origin prepended onto the name to ensure uniqueness. Sometimes you may wish to manage your own namespace, e.g. when you anticipate moving nodes between extensions so the extension name will not be consistent. All you have to do to override the default behaviour is to specify a namespace for the node type name (i.e. include a `.` separator in it). .. warning:: Once you have overridden the node type name with such an absolute value you are now responsible for ensuring uniqueness so be sure you have some scheme that will help you with that. The prefix **omni.** is reserved for NVIDIA nodes. Everything else is legal, so long as the entire name itself is legal. OgnTutorialTupleData.cpp ------------------------ The *cpp* 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:: OgnTutorialTupleData.cpp :linenos: :language: c++ Note how by default some of the attribute value types are USD types and some are generic *ogn::tuple* types. See :ref:`ogn_attribute_types` for the full set of type definitions. Tuple 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 tuple member access. In practice you would use an *auto* declaration. The types are shown only for illustrative purposes. The data types for tuples that correspond to existing USD types use the ``pxr::gf`` versions of those types, so the database accessors in this node will return these types: +---------------------+----------------+ | Database Function | Returned Type | +=====================+================+ | inputs.a_double2() | const GfVec2d& | +---------------------+----------------+ | inputs.a_float2() | const GfVec2f& | +---------------------+----------------+ | inputs.a_half2() | const GfVec2h& | +---------------------+----------------+ | inputs.a_int2() | const GfVec2i& | +---------------------+----------------+ | inputs.a_float3() | const GfVec3f& | +---------------------+----------------+ | outputs.a_double2() | GfVec2d& | +---------------------+----------------+ | outputs.a_float2() | GfVec2f& | +---------------------+----------------+ | outputs.a_half2() | GfVec2h& | +---------------------+----------------+ | outputs.a_int2() | GfVec2i& | +---------------------+----------------+ | outputs.a_float3() | GfVec3f& | +---------------------+----------------+ Tuple Data Compute Validation ----------------------------- As with simple data types the existence of the mandatory inputs is confirmed before proceeding to the compute method. Tuple Data Node Computation Tests --------------------------------- In the *"tests"* section of the .ogn file there are some simple tests exercising the basic functionality of the compute method. In practice it is a good idea to include more thorough tests which exercise different data values, especially potential edge cases.
4,326
reStructuredText
44.547368
121
0.631068
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial4/OgnTutorialTupleData.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 <OgnTutorialTupleDataDatabase.h> #include <algorithm> #include <iostream> // This class exercises access to the DataModel through the generated database class for supported data types // with element counts greater than 1. class OgnTutorialTupleData { public: static bool compute(OgnTutorialTupleDataDatabase& db) { // For each piece of data apply a transforming operation so that compute does something testable. // The transformation adds 1 to the input to compute the matching output. Notice how the recognized // USD types can make use of the built-in manipulation functions while the generic types have to // manually apply the algorithm. db.outputs.a_double2() = db.inputs.a_double2() + GfVec2d(1.0, 1.0); db.outputs.a_double3() = db.inputs.a_double3() + GfVec3d(1.0, 1.0, 1.0); db.outputs.a_float2() = db.inputs.a_float2() + GfVec2f(1.0f, 1.0f); db.outputs.a_half2() = db.inputs.a_half2() + GfVec2h(1.0, 1.0); db.outputs.a_int2() = db.inputs.a_int2() + GfVec2i(1, 1); // If you have your own data types which are memory-layout-compatible with the defaults provided // you can use a simple cast operation to force a specific data type. Be careful not to cast away // the "const" on inputs or your data could get out of sync. const carb::Float3& inFloat3 = reinterpret_cast<const carb::Float3&>(db.inputs.a_float3()); carb::Float3& outFloat3 = reinterpret_cast<carb::Float3&>(db.outputs.a_float3()); outFloat3.x = inFloat3.x + 1.0f; outFloat3.y = inFloat3.y + 1.0f; outFloat3.z = inFloat3.z + 1.0f; return true; } }; REGISTER_OGN_NODE()
2,152
C++
46.844443
109
0.697491
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial3/OgnTutorialABI.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 <OgnTutorialABIDatabase.h> using omni::graph::core::Token; #include <string> #include <unordered_map> // Set this value true to enable messages when the ABI overrides are called const bool debug_abi{ false }; #define DEBUG_ABI if (debug_abi) CARB_LOG_INFO // In most cases the generated compute method is all that a node will need to implement. If for // some reason the node wants to access the omni::graph::core::INodeType ABI directly and override // any of its behaviour it can. This set of functions shows how every method in the ABI might be // overridden. // // Note that certain ABI functions, though listed, are not implemented as a proper implementation would be more // complicated than warranted for this simple example. All are rarely overridden; in fact no known cases exist. class OgnTutorialABI { static std::unordered_map<std::string, std::string> s_metadata; // Alternative metadata implementation public: // ---------------------------------------------------------------------- // Almost always overridden indirectly // // ABI compute method takes the interface definitions of both the evaluation context and the node. // When using a .ogn generated class this function will be overridden by the generated code and the // node will implement the generated version of this method "bool compute(OgnTutorialABIDatabase&)". // Overriding this method directly, while possible, does not add any extra capabilities as the two // parameters are also available through the database (contextObj = db.abi_context(), nodeObj = db.abi_node()) static bool compute(const GraphContextObj& contextObj, const NodeObj& nodeObj) { DEBUG_ABI("Computing the ABI node"); // The computation still runs the same as for the standard compute method by using the more // complex ABI-based access patterns. First get the ABI-compliant structures needed. NodeContextHandle nodeHandle = nodeObj.nodeContextHandle; const INode* iNode = nodeObj.iNode; // Use the multiple-input template to access a pointer to the input boolean value auto inputValueAttr = getAttributesR<ConstAttributeDataHandle>( contextObj, nodeHandle, std::make_tuple(Token("inputs:namespace:a_bool")), kAccordingToContextIndex); const bool* inputValue{ nullptr }; std::tie(inputValue) = getDataR<bool*>(contextObj, inputValueAttr); // Use the single-output template to access a pointer to the output boolean value auto outputValueAttr = getAttributeW(contextObj, nodeHandle, Token("outputs:namespace:a_bool"), kAccordingToContextIndex); bool* outputValue = getDataW<bool>(contextObj, outputValueAttr); // Since the generated code isn't in control you are responsible for your own error checking if (!inputValue) { // Not having access to the generated database class with its error interface we have to resort // to using the native error logging. CARB_LOG_ERROR("Failed compute on %s: No input attribute", iNode->getPrimPath(nodeObj)); return false; } if (!outputValue) { CARB_LOG_ERROR("Failed compute on %s: No output attribute", iNode->getPrimPath(nodeObj)); return false; } // The actual computation of the node *outputValue = !*inputValue; return true; } // ---------------------------------------------------------------------- // Rarely overridden // // These will almost never be overridden, specifically because the low level implementation lives in // the omni.graph.core extension and is not exposed through the ABI so it would be very difficult // for a node to be able to do the right thing when this function is called. // static void addInput // static void addOutput // static void addState // ---------------------------------------------------------------------- // Rarely overridden // // This should almost never be overridden as the auto-generated code will handle the name. // This particular override is used to bypass the unique naming feature of the .ogn name, where only names // with a namespace separator (".") do not have the extension name added as a prefix to the unique name. // This should only done for backward compatibility, and only until the node type name versioning is available. // Note that when you do this you will still be able to create a node using the generated node type name, as // that is required in order for the automated testing to work. The name returned here can be thought of as an // alias for the underlying name. static const char* getNodeType() { DEBUG_ABI("ABI override of getNodeType"); static const char* _nodeType{ "OmniGraphABI" }; return _nodeType; } // ---------------------------------------------------------------------- // Occasionally overridden // // When a node is created this will be called static void initialize(const GraphContextObj&, const NodeObj&) { DEBUG_ABI("ABI override of initialize"); // There is no default behaviour on initialize so nothing else is needed for this tutorial to function } // ---------------------------------------------------------------------- // Rarely overridden // // This method might be overridden to set up initial conditions when a node type is registered, or // to replace initialization if the auto-generated version has some problem. static void initializeType(const NodeTypeObj& nodeType) { DEBUG_ABI("ABI override of initializeType"); // The generated initializeType will always be called so nothing needs to happen here } // ---------------------------------------------------------------------- // Occasionally overridden // // This is called while registering a node type. It is used to initialize tasks that can be used for // making compute more efficient by using Realm events. static void registerTasks() { DEBUG_ABI("ABI override of registerTasks"); } // ---------------------------------------------------------------------- // Occasionally overridden // // After a node is removed it will get a release call where anything set up in initialize() can be torn down static void release(const NodeObj&) { DEBUG_ABI("ABI override of release"); // There is no default behaviour on release so nothing else is needed for this tutorial to function } // ---------------------------------------------------------------------- // Occasionally overridden // // This is something you do want to override when you have more than version of your node. // In it you would translate attribute information from older versions into the current one. static bool updateNodeVersion(const GraphContextObj&, const NodeObj&, int oldVersion, int newVersion) { DEBUG_ABI("ABI override of updateNodeVersion from %d to %d", oldVersion, newVersion); // There is no default behaviour on updateNodeVersion so nothing else is needed for this tutorial to function return oldVersion < newVersion; } // ---------------------------------------------------------------------- // Occasionally overridden // // When there is a connection change to this node which results in an extended type attribute being automatically // resolved, this callback gives the node a change to resolve other extended type attributes. For example a generic // 'Increment' node can resolve its output to an int only after its input has been resolved to an int. Attribute // types are resolved using IAttribute::setResolvedType() or the utility functions such as // INode::resolvePartiallyCoupledAttributes() static void onConnectionTypeResolve(const NodeObj& nodeObj) { DEBUG_ABI("ABI override of onConnectionTypeResolve()"); // There is no default behaviour on onConnectionTypeResolve so nothing else is needed for this tutorial to // function } // ---------------------------------------------------------------------- // Rarely overridden // // You may want to provide an alternative method of metadata storage. // This method can be used to intercept requests for metadata to provide those alternatives. static size_t getAllMetadata(const NodeTypeObj& nodeType, const char** keyBuf, const char** valueBuf, size_t bufSize) { DEBUG_ABI("ABI override of getAllMetadata(%zu)", bufSize); if (s_metadata.size() > bufSize) { CARB_LOG_ERROR("Not enough space for metadata - needed %zu, got %zu", s_metadata.size(), bufSize); return 0; } size_t index = 0; for (auto& metadata : s_metadata) { keyBuf[index] = metadata.first.c_str(); valueBuf[index] = metadata.second.c_str(); ++index; } return s_metadata.size(); } // ---------------------------------------------------------------------- // Rarely overridden // // You may want to provide an alternative method of metadata storage. // This method can be used to intercept requests for metadata to provide those alternatives. static const char* getMetadata(const NodeTypeObj& nodeType, const char* key) { DEBUG_ABI("ABI override of getMetadata('%s')", key); auto found = s_metadata.find(std::string(key)); if (found != s_metadata.end()) { return (*found).second.c_str(); } return nullptr; } // ---------------------------------------------------------------------- // Rarely overridden // // You may want to provide an alternative method of metadata storage. // This method can be used to intercept requests for the number of metadata elements to provide those alternatives. static size_t getMetadataCount(const NodeTypeObj& nodeType) { DEBUG_ABI("ABI override of getMetadataCount()"); return s_metadata.size(); } // ---------------------------------------------------------------------- // Rarely overridden // // You may want to provide an alternative method of metadata storage. // This method can be used to intercept requests to set metadata and use those alternatives. static void setMetadata(const NodeTypeObj& nodeType, const char* key, const char* value) { DEBUG_ABI("ABI override of setMetadata('%s' = '%s')", key, value); s_metadata[std::string(key)] = std::string(value); } // ---------------------------------------------------------------------- // Rarely overridden // // Subnode types are used when a single node type is shared among a set of other nodes, e.g. the way that // PythonNode is the node type for all nodes implemented in Python, while the subNodeType is the actual node type. // Overriding these functions let you implement different methods of managing those relationships. // static void addSubNodeType(const NodeTypeObj& nodeType, const char* subNodeTypeName, const NodeTypeObj& subNodeType) { DEBUG_ABI("ABI override of addSubNodeType('%s')", subNodeTypeName); } // ---------------------------------------------------------------------- // Rarely overridden // // Subnode types are used when a single node type is shared among a set of other nodes, e.g. the way that // PythonNode is the node type for all nodes implemented in Python, while the subNodeType is the actual node type. // Overriding these functions let you implement different methods of managing those relationships. // static NodeTypeObj getSubNodeType(const NodeTypeObj& nodeType, const char* subNodeTypeName) { DEBUG_ABI("ABI override of getSubNodeType('%s')", subNodeTypeName); return NodeTypeObj{ nullptr, kInvalidNodeTypeHandle }; } // ---------------------------------------------------------------------- // Rarely overridden // // Subnode types are used when a single node type is shared among a set of other nodes, e.g. the way that // PythonNode is the node type for all nodes implemented in Python, while the subNodeType is the actual node type. // Overriding these functions let you implement different methods of managing those relationships. // static NodeTypeObj createNodeType(const char* nodeTypeName, int version) { DEBUG_ABI("ABI override of createNodeType('%s')", nodeTypeName); return NodeTypeObj{ nullptr, kInvalidNodeTypeHandle }; } }; std::unordered_map<std::string, std::string> OgnTutorialABI::s_metadata; // ============================================================ // The magic for recognizing and using the overridden ABI code is in here. The generated interface // is still available, as seen in the initializeType implementation, although it's not required. REGISTER_OGN_NODE()
13,602
C++
47.931655
121
0.63101
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial1/tutorial1.rst
.. _ogn_tutorial_empty: Tutorial 1 - Trivial Node ========================= The simplest possible node is one that implements only the mandatory fields in a node. These are the "version" and "description" fields. The existence of the file *OgnTutorialEmpty.svg* will automatically install this icon into the build directory and add its path to the node type's metadata. The installed file will be named after the node type, not the class type, so it will be installed at the path `$BUILD/exts/omni.graph.tutorials/ogn/icons/Empty.svg`. OgnTutorialEmpty.ogn -------------------- The *.ogn* file containing the implementation of a node named "omni.graph.tutorials.Empty", in its first version, with a simple description. .. literalinclude:: OgnTutorialEmpty.ogn :linenos: :language: json OgnTutorialEmpty.cpp -------------------- The *.cpp* file contains the minimum necessary implementation of the node class, which contains only the empty compute method. It contains a detailed description of the necessary code components. .. literalinclude:: OgnTutorialEmpty.cpp :linenos: :language: c++
1,113
reStructuredText
36.133332
115
0.730458
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial1/OgnTutorialEmpty.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. // // ============================================================ // Note the name of the generated include file, taken from the name of the file with "Database.h" appended. // The build system should have added the include path that picks this file up directly. #include <OgnTutorialEmptyDatabase.h> // ============================================================ // The class name should match the file name to avoid confusion as the file name will be used // as a base for the names in the generated interface. // class OgnTutorialEmpty { public: // ------------------------------------------------------------ // Note the name of the generated computation database, the same as the name of the include file, // auto-generated by appending "Database" to the file name. // static bool compute(OgnTutorialEmptyDatabase&) { // This node correctly does nothing, but it must return true to indicate a successful compute. // return true; } }; // ============================================================ // Now that the node has been defined it can be registered for use. This registration takes care of // automatic registration of the node when the extension loads and deregistration when it unloads. REGISTER_OGN_NODE()
1,711
C++
44.05263
107
0.638223
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial24/OgnTutorialOverrideType.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 <OgnTutorialOverrideTypeDatabase.h> // The include files required by the type definition override is in the database definition so it does not have to // be directly included here. namespace omni { namespace graph { namespace core { namespace tutorial { class OgnTutorialOverrideType { public: static bool compute(OgnTutorialOverrideTypeDatabase& db) { // Usually you would use an "auto" declaration. The type is explicit here to show how the override has // changed the generated type. const carb::Float3& inputTypedData = db.inputs.typedData(); carb::Float3& outputTypedData = db.outputs.typedData(); const pxr::GfVec3d& inputStandardData = db.inputs.data(); pxr::GfVec3d& outputStandardData = db.outputs.data(); // Rearrange the components as a simple way to verify that compute happened outputTypedData.x = inputTypedData.y; outputTypedData.y = inputTypedData.z; outputTypedData.z = inputTypedData.x; outputStandardData.Set(inputStandardData[1], inputStandardData[2], inputStandardData[0]); return true; } }; // namespaces are closed after the registration macro, to ensure the correct class is registered REGISTER_OGN_NODE() } // namespace tutorial } // namespace core } // namespace graph } // namespace omni
1,776
C++
31.907407
114
0.73536
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial24/tutorial24.rst
.. _ogn_tutorial_overrideTypes: Tutorial 24 - Overridden Types ============================== By default the code generator will provide POD types for simple data, and USD types for tuple data (e.g. ``float`` and ``pxr::GfVec3f``). Sometimes you may have your own favourite math library and want to use its data types directly rather than constantly using a _reinterpret_cast_ on the attribute values. To facilitate this, JSON data which contains type overrides for one or more of the attribute types may be provided so that the generated code will use those types directly. OgnTutorialOverrideType.ogn --------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.OverrideType", which has one input and one output attribute that use an overridden type for ``float[3]``. .. literalinclude:: OgnTutorialOverrideType.ogn :linenos: :language: json OgnTutorialOverrideType.cpp --------------------------- The *cpp* file contains the implementation of the compute method. The default type implementation would have a return type of ``pxr::GfVec3f`` but this one uses the override type of ``carb::Float3`` .. literalinclude:: OgnTutorialOverrideType.cpp :linenos: :language: c++
1,240
reStructuredText
40.366665
118
0.720161
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial15/OgnTutorialBundlesPy.py
""" Implementation of the Python node accessing attributes through the bundle in which they are contained. """ 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 OgnTutorialBundlesPy: """Exercise the bundled data types through a Python OmniGraph node""" @staticmethod def compute(db) -> bool: """Implements the same algorithm as the C++ node OgnTutorialBundles.cpp""" full_bundle = db.inputs.fullBundle filtered_bundle = db.inputs.filteredBundle filters = db.inputs.filters output_bundle = db.outputs.combinedBundle # This does a copy of the full bundle contents from the input bundle to the output bundle output_bundle.bundle = full_bundle # Extract the filter flags from the contents of the filters array filter_big_arrays = "big" in filters filter_type_int = "int" in filters filter_name_x = "x" in filters # 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 filtered_bundle.attributes: # The two main accessors for the bundled attribute provide the name and type information name = bundled_attribute.name attribute_type = bundled_attribute.type # Check each of the filters to see which attributes are to be skipped if filter_type_int and attribute_type.base_type in _INTEGER_TYPES: continue if filter_name_x and name.find("x") >= 0: continue # A method on the bundled attribute provides access to array size (non-arrays are size 1) if filter_big_arrays and bundled_attribute.size > 10: continue # All filters have been passed so the attribute is eligible to be copied onto the output. output_bundle.insert(bundled_attribute) return True
2,203
Python
39.814814
113
0.671811
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial15/OgnTutorialBundles.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 <OgnTutorialBundlesDatabase.h> using omni::graph::core::BaseDataType; using omni::graph::core::NameToken; using omni::graph::core::Type; namespace { // Tokens to use for checking filter names static NameToken s_filterBigArrays; static NameToken s_filterNameX; static NameToken s_filterTypeInt; } class OgnTutorialBundles { public: // Overriding the initialize method allows caching of the name tokens which will avoid string comparisons // at evaluation time. static void initialize(const GraphContextObj& contextObj, const NodeObj&) { s_filterBigArrays = contextObj.iToken->getHandle("big"); s_filterNameX = contextObj.iToken->getHandle("x"); s_filterTypeInt = contextObj.iToken->getHandle("int"); } static bool compute(OgnTutorialBundlesDatabase& db) { // Bundle attributes are extracted from the database in the same way as any other attribute. // The only difference is that a different interface is provided, suited to bundle manipulation. const auto& fullBundle = db.inputs.fullBundle(); const auto& filteredBundle = db.inputs.filteredBundle(); const auto& filters = db.inputs.filters(); auto& outputBundle = db.outputs.combinedBundle(); // The first thing this node does is to copy the contents of the fullBundle to the output bundle. // operator=() has been defined on bundles to make this a one-step operation. Note that this completely // replaces any previous bundle contents. If you wish to append another bundle then you would use: // outputBundle.insertBundle(fullBundle); outputBundle = fullBundle; // Set some booleans that determine which filters to apply bool filterBigArrays{ false }; bool filterNameX{ false }; bool filterTypeInt{ false }; for (const auto& filterToken : filters) { if (filterToken == s_filterBigArrays) { filterBigArrays = true; } else if (filterToken == s_filterNameX) { filterNameX = true; } else if (filterToken == s_filterTypeInt) { filterTypeInt = true; } else { db.logWarning("Unrecognized filter name '%s'", db.tokenToString(filterToken)); } } // The bundle object has an iterator for looping over the attributes within in for (const auto& bundledAttribute : filteredBundle) { // The two main accessors for the bundled attribute provide the name and type information NameToken name = bundledAttribute.name(); Type type = bundledAttribute.type(); // Check each of the filters to see which attributes are to be skipped if (filterTypeInt) { if ((type.baseType == BaseDataType::eInt) || (type.baseType == BaseDataType::eUInt) || (type.baseType == BaseDataType::eInt64) || (type.baseType == BaseDataType::eUInt64)) { continue; } } if (filterNameX) { std::string nameString(db.tokenToString(name)); if (nameString.find('x') != std::string::npos) { continue; } } if (filterBigArrays) { // A simple utility method on the bundled attribute provides access to array size if (bundledAttribute.size() > 10) { continue; } } // All filters have been passed so the attribute is eligible to be copied onto the output. outputBundle.insertAttribute(bundledAttribute); } return true; } }; REGISTER_OGN_NODE()
4,380
C++
37.095652
111
0.611416
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial15/tutorial15.rst
.. _ogn_tutorial_bundle_manipulation: Tutorial 15 - Bundle Manipulation ================================= Attribute bundles are a construct that packages up groups of attributes into a single entity that can be passed around the graph. Some advantages of a bundle are that they greatly simplify graph connections, only requiring a single connection between nodes rather than dozens or even hundreds, and they do not require static definition of the data they contain so it can change as the evaluation of the nodes dictate. The only disadvantage is that the node writer is responsible for analyzing the contents of the bundle and deciding what to do with them. OgnTutorialBundles.ogn ---------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.BundleManipulation", which has some bundles as inputs and outputs. It's called "manipulation" as the focus of this tutorial node is on operations applied directly to the bundle itself, as opposed to on the data on the attributes contained within the bundles. See future tutorials for information on how to deal with that. .. literalinclude:: OgnTutorialBundles.ogn :linenos: :language: json OgnTutorialBundles.cpp ---------------------- The *cpp* file contains the implementation of the compute method. It exercises each of the available bundle manipulation functions. .. literalinclude:: OgnTutorialBundles.cpp :linenos: :language: c++ OgnTutorialBundlesPy.py ----------------------- The *py* file duplicates the functionality in the *cpp* file, except that it is implemented in Python. .. literalinclude:: OgnTutorialBundlesPy.py :linenos: :language: python Bundle Notes ------------ Bundles are implemented in USD as "virtual primitives". That is, while regular attributes appear in a USD file as attributes on a primitive, a bundle appears as a nested primitive with no members. Naming Convention ----------------- Attributes can and do contain namespaces to make them easier to work with. For example, ``outputs:operations`` is the namespaced name for the output attribute ``operations``. However as USD does not allow colons in the names of the primitives used for implementing attriute bundles they will be replaced by underscores, vis ``outputs_operations``. Bundled Attribute Manipulation Methods -------------------------------------- There are a few methods for manipulating the bundle contents, independent of the actual data inside. The actual implementation of these methods may change over time however the usage should remain the same. The Bundle As A Whole +++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 2,5,8,11 // The bundle attribute is extracted from the database in exactly the same way as any other attribute. const auto& inputBundle = db.inputs.myBundle(); // Output and state bundles are the same, except not const auto& outputBundle = db.outputs.myBundle(); // The size of a bundle is the number of attributes it contains auto bundleAttributeCount = inputBundle.size(); // Full bundles can be copied using the assignment operator outputBundle = inputBundle; Accessing Attributes By Name ++++++++++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 2,8-9 // The attribute names should be cached somewhere as a token for fast access. static const NameToken normalsName = db.stringToToken("normals"); // Then it's a call into the bundle to find an attribute with matching name. // Names are unique so there is at most one match, and bundled attributes do not have the usual attribute // namespace prefixes "inputs:", "outputs:", or "state:" const auto& inputBundle = db.inputs.myBundle(); auto normals = inputBundle.attributeByName(normalsName); if (normals.isValid()) { // If the attribute is not found in the bundle then isValid() will return false. } Putting An Attribute Into A Bundle ++++++++++++++++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 8,10 // Once an attribute has been extracted from a bundle a copy of it can be added to a writable bundle. const auto& inputBundle = db.inputs.myBundle(); auto& outputBundle = db.outputs.myBundle(); auto normals = inputBundle.attributeByName(normalsToken); if (normals.isValid()) { // Clear the contents of stale data first since it will not be reused here. outputBundle.clear(); // The attribute wrapper knows how to insert a copy into a bundle outputBundle.insertAttribute(normals); } Iterating Over Attributes +++++++++++++++++++++++++ .. code-block:: cpp :emphasize-lines: 3,7 // The range-based for loop provides a method for iterating over the bundle contents. const auto& inputBundle = db.inputs.myBundle(); for (const auto& bundledAttribute : inputBundle) { // Type information is available from a bundled attribute, consisting of a structure defined in // include/omni/graph/core/Type.h auto type = bundledAttribute.type(); // The type has four pieces, the first is the basic data type... assert( type.baseType == BaseDataType::eFloat ); // .. the second is the role, if any assert( type.role == AttributeRole::eNormal ); // .. the third is the number of tuple components (e.g. 3 for float[3] types) assert( type.componentCount == 3 ); // .. the last is the array depth, either 0 or 1 assert( type.arrayDepth == 0 ); }
5,532
reStructuredText
40.601503
124
0.696855
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/conversionTutorial/node_conversion.rst
.. _ogn_node_conversion: Tutorial - OmniGraph .ogn Conversion ==================================== This is a walkthrough of the conversion of an OmniGraph node written under the original DataModel and ABI architectures to the .ogn format, which uses the new DataModel architecture. .. note:: If you do not have build support for .ogn files yet, refer first to the :ref:`ogn_build_conversion` document. The test node used will be the **Time** node, in the `omni.graph.core` extension. In order to fully convert the file a series of steps must be followed. .. note:: bash/gitbash commands are used to illustrate actions where required. Any other equivalent method is fine. For the commands the current directory is assumed to be ``source/extensions/omni.graph.core/``. .. note:: This tutorial is focussed on conversion of C++ nodes. Other types will be handled in separate tutorials. Before the node can be converted the build has to first be set up to .. contents:: Node Conversion Steps Identify attribute names ------------------------ Before modifying any code the .ogn file should be created, in the location described by :ref:`ogn_build_conversion`. The key components of that file are the node type name, description, version, and the list of attributes, their types, descriptions, and defaults. The node type name for most existing nodes is found in the ``getNodeType()`` method. By looking at the ``initializeType()`` method in the current node it's easy to determine the name of all of the attributes. .. code-block:: c++ :linenos: :emphasize-lines: 5,11-15 struct TimeComputeNode { static const char* getNodeType() { return "Time"; } static void initializeType(const NodeTypeObj& nodeTypeObj) { const INodeType* iNodeType = nodeTypeObj.iNodeType; iNodeType->addOutput(nodeTypeObj, "output:time", "double", true, nullptr, nullptr); iNodeType->addOutput(nodeTypeObj, "output:frame", "double", true, nullptr, nullptr); iNodeType->addOutput(nodeTypeObj, "output:fps", "double", true, nullptr, nullptr); iNodeType->addOutput(nodeTypeObj, "output:elapsedTime", "double", true, nullptr, nullptr); iNodeType->addOutput(nodeTypeObj, "output:timeSinceStart", "double", true, nullptr, nullptr); } From this little bit of information the skeleton of the file ``OgnTime.ogn`` can be put in place. In this case we see that all of the attributes are outputs of type `double` so that dictates the basic contents. It's a bit of an unusual node in that almost every node will have both inputs and outputs. For the purposes of conversion the principles are the same, you just put the attributes into the `inputs` subsection instead of `outputs`. .. note:: Not all attributes might be added to the node in the above way, relying on USD contents to set up the missing attributes. You can find any missing attributes by examining the USD file, which will contain the attribute's type and any non-standard default values. .. code-block:: json { "Time" : { "version" : 1, "description" : [""], "outputs" : { "time": { "description": [""], "type": "double" }, "frame": { "description": [""], "type": "double" }, "fps": { "description": [""], "type": "double" }, "elapsedTime": { "description": [""], "type": "double" }, "timeSinceStart": { "description": [""], "type": "double" } } } } A key point to note here is that attributes generated from a .ogn file are automatically namespaced; **inputs:** for input attributes and **outputs:** for output attributes, so existing USD files or scripts that use the above attribute names may have to be changed. Also, in order to keep node names unique, the name of the extension is prepended to the name of the node. So for all scripts and USD files you will need to perform this renaming: +----------------+------------------------+ | Old Name | New Name | +================+========================+ | Time | omni.graph.core.Time | +----------------+------------------------+ | time | outputs:time | +----------------+------------------------+ | frame | outputs:frame | +----------------+------------------------+ | fps | outputs:fps | +----------------+------------------------+ | elapsedTime | outputs:elapsedTime | +----------------+------------------------+ | timeSinceStart | outputs:timeSinceStart | +----------------+------------------------+ The descriptions of the attributes and the node may be found in the node's comments, or may just be understood by the node writer. They can be filled in directly. .. code-block:: c++ :linenos: :emphasize-lines: 5-9 static bool compute(const GraphContextObj& contextObj, const NodeObj& node) { const GraphContext::Globals globals = contextObj.context->getGlobals(); setAttributeValue(contextObj, nodeObj, "output:time", (double)globals.currentTime); setAttributeValue(contextObj, nodeObj, "output:frame", (double)globals.frameTime); setAttributeValue(contextObj, nodeObj, "output:fps", (double)globals.fps); setAttributeValue(contextObj, nodeObj, "output:elapsedTime", (double)globals.elapsedTime); setAttributeValue(contextObj, nodeObj, "output:timeSinceStart", (double)globals.timeSinceStart); return true; } Details of the C++ types available and their corresponding .ogn types can be found in :ref:`ogn_attribute_types`, which we can use to deduce the types of this node's attributes. (Certain types are modified due to them being different between the previous and current implementations of the DataModel; they should be relatively obvious on inspection of the .ogn types document.) Potential default values can also be deduced from the node algorithm. In this case zero values for every attribute seems reasonable. When no default values are specified in the .ogn file zeroes are assumed so they do not need to be explicitly added. On inspection it seems like some of the attributes can have a minimum value set. In particular, `fps`, `elapsedTime`, and `timeSinceStart` don't seem like they could be negative values so a minimum of 0.0 is appropriate. Although the .ogn file will not yet enforce limits at runtime that is the intention in the future so these limits should be recorded. This is all the information required to complete the .ogn file: .. code-block:: json { "Time" : { "version" : 1, "description" : ["System built-in node to return various time information from kit."], "outputs" : { "time": { "description": ["Current global time, in seconds"], "type": "double" }, "frame": { "description": ["Current global frame time, in seconds"], "type": "double" }, "fps": { "description": ["Current evaluation rate, in frames per second"], "type": "double", "minimum": 0.0 }, "elapsedTime": { "description": ["Elapsed time in the current evaluation, in seconds"], "type": "double", "minimum": 0.0 }, "timeSinceStart": { "description": ["Elapsed time since the start of the session, in seconds"], "type": "double", "minimum": 0.0 } } } } Paring down the includes ------------------------ The generated OGN header file will include everything it needs in order to access the DataModel so the redundant includes can be removed from the source file **OgnTime.cpp**. The simplest approach is to remove all but the one necessary inclusion of the database file and add back in any that are missing. In this case only one more file is necessary, to access the global time information. .. code-block:: c++ :linenos: :emphasize-lines: 1 #include <OgnTimeDatabase.h> #include "GraphContext.h" Set Up Node Type ---------------- For consistency the class should be named the same as the file, and can be an actual *class* type since there are no direct ties to the C ABI to it. The node type is set up by the generated code so this starting clause: .. code-block:: c++ struct TimeComputeNode { static const char* getNodeType() { return "Time"; } can be replaced with the single declaration: .. code-block:: c++ class OgnTime { public: Remove Unnecessary ABI Setup ---------------------------- The generated code handles interfacing with the OmniGraph ABI so the function to get that interface can be deleted: .. code-block:: c++ :linenos: :emphasize-lines: 1-11 INodeType getNodeInterfaceTime() { INodeType iface = {}; iface.getNodeType = TimeComputeNode::getNodeType; iface.compute = TimeComputeNode::compute; iface.initialize = TimeComputeNode::initialize; iface.release = TimeComputeNode::release; return iface; } It also handles the registration and deregistration of the node type interfaces so that code can be deleted, shown in the file *omni.graph.core/plugins/PluginInterface.cpp* here: .. code-block:: c++ :linenos: :emphasize-lines: 1-4,10-21,26-33 namespace { std::vector<const NodeTypeRegistration*> pluginNodeTypeRegistrations; } const IToken* Token::iToken = nullptr; CARB_EXPORT void carbOnPluginStartup() { auto iComputeGraph = carb::getFramework()->acquireInterface<IGraphRegistry>(); if (!iComputeGraph) { CARB_LOG_ERROR("omni.graph.expression failed to register nodes due to missing interface"); return; } std::for_each(pluginNodeTypeRegistrations.begin(), pluginNodeTypeRegistrations.end(), [&iComputeGraph](const NodeTypeRegistration* nodeTypeRegistration) { iComputeGraph->registerNodeType( nodeTypeRegistration->nodeTypeInterface(), nodeTypeRegistration->nodeTypeVersion()); }); } CARB_EXPORT void carbOnPluginShutdown() { auto iComputeGraph = carb::getFramework()->acquireInterface<IGraphRegistry>(); if (!iComputeGraph) return; std::for_each(pluginNodeTypeRegistrations.begin(), pluginNodeTypeRegistrations.end(), [&iComputeGraph](const NodeTypeRegistration* nodeTypeRegistration) { iComputeGraph->unregisterNodeType(nodeTypeRegistration->nodeTypeInterface().getNodeType()); }); } The extension must also create the OGN node registration support so that all of its nodes are registered and deregistered at the proper times. To do so, inclusion of the file *omni/graph/core/OgnHelpers.h* must be added, and the two relevant macros it defines must be inserted. *DECLARE_OGN_NODES()* appears at file-static level, which is easiest after the *CARB_PLUGIN* macros, *INITIALIZE_OGN_NODES()* is added in the *carbOnPluginStartup()* method, and *RELEASE_OGN_NODES()* is added in the *carbOnPluginShutdown()* method. .. code-block:: c++ :linenos: :emphasize-lines: 1,28,38,43 #include <omni/graph/core/OgnHelpers.h> #include <omni/graph/core/iComputeGraph.h> const struct carb::PluginImplDesc kPluginImpl = { "omni.graph.core.plugin", "OmnIGraph Core", "NVIDIA", carb::PluginHotReload::eEnabled, "dev" }; CARB_PLUGIN_IMPL(kPluginImpl, omni::graph::core::ComputeGraph, omni::graph::core::IAttribute, omni::graph::core::IAttributeData, omni::graph::core::IAttributeType, omni::graph::core::IBundle, omni::graph::core::IGraph, omni::graph::core::IGraphContext, omni::graph::core::IGraphRegistry, omni::graph::core::INode, omni::graph::core::IScheduleNode, omni::graph::core::IDataStealingPrototype, omni::graph::core::IGatherPrototype) CARB_PLUGIN_IMPL_DEPS(carb::flatcache::FlatCache, carb::flatcache::IPath, carb::flatcache::IToken, carb::graphics::Graphics, carb::filesystem::IFileSystem, omni::gpucompute::GpuCompute, carb::settings::ISettings) DECLARE_OGN_NODES() // carbonite interface for this plugin (may contain multiple compute nodes) void fillInterface(omni::kit::ITime& iface) { iface = {}; } CARB_EXPORT void carbOnPluginStartup() { INITIALIZE_OGN_NODES() } CARB_EXPORT void carbOnPluginShutdown() { RELEASE_OGN_NODES() } .. note:: The functions *carbOnPluginStartup()* and *carbOnPluginShutdown()* are required by the extension manager, even if they are empty. Modify Compute Signature ------------------------ The *compute* method required by the generated code has a different signature than the ABI. It is passed a single parameter, which is a reference to the node's database interface object. Any access required to the former ABI parameters for other reasons can be accomplished by going through the database object, hence this: .. code-block:: c++ static bool compute(const GraphContextObj& contextObj, const NodeObj& nodeObj) { const IGraphContext* const iContext = contextObj.iContext; const INode* const iNode = nodeObj.iNode; becomes this: .. code-block:: c++ static bool compute(OgnTimeDatabase& db) { Refactor Input Attribute Value access ------------------------------------- Nodes are currently using direct access to the DataModel, either old or new, to get the values of their input attributes. This is the primary function provided by the generated database class so that access must be refactored to make use of it. Often what you'll see in your compute method, when it contains input attributes, are calls like this: .. code-block:: c++ float noiseRatio, frequency; noiseRatio = getDataR<float>(contextObj, iNode->getAttribute(nodeObj, "noiseRatio")); frequency = getDataR<float>(contextObj, iNode->getAttribute(nodeObj, "frequency")); Although it's not necessary, it can help improve clarity if the values extracted from the database are placed into local variables for more natural access. You can look up the exact data types returned for a given attribute type in :ref:`ogn_user_guide`, though for most simple situations you can just use the *auto* declaration. The highlighted comments are not included in the final code, they are just there for explanation: .. code-block:: c++ :linenos: :emphasize-lines: 1-2,4-7 // Inputs always appear in the db.inputs nested structure, and are named for the name of the attribute // as it appears in the .ogn file. (Any colons used for subnamespaces are converted to underscore for the name.) const auto& noiseRatio = db.inputs.noiseRatio(); // Actual data type of the above is "const float&" but it's easiest to use plain "const auto&". It also maintains // consistency with more complex types. // The original variable names are preserved here but it's a good idea to use the attribute name as the // variable name, for consistency. (e.g. use "noiseFrequency" instead of "frequency") const auto& frequency = db.inputs.noiseFrequency(); Refactor Setting Output Attribute Values ---------------------------------------- This snippet of code shows a similar conversion for the time node's setting of output values, whose original code was seen above: .. code-block:: c++ :linenos: const GraphContext::Globals globals = db.abi_context().context->getGlobals(); db.outputs.time() = (double)globals.currentTime; db.outputs.frame() = (double)globals.frameTime; db.outputs.fps() = (double)globals.fps; db.outputs.elapsedTime() = (double)globals.elapsedTime; db.outputs.timeSinceStart() = (double)globals.timeSinceStart; Adjust The Algorithm Data Types If Necessary -------------------------------------------- Most existing nodes are using the USD data types as that is what the old DataModel supported (e.g. GfVec3f). If you've already examined :ref:`ogn_user_guide` you'll note that the new DataModel uses these types by default. If you are using anything else you would have to cast the values being returns as in :ref:`ogn_tutorial_tupleData`, or modify the type definitions used by a file as in :ref:`ogn_type_definition_overrides`. Add Tests --------- This particular node uses global data and so is not suitable for adding localized test data for the automatically generated tests. See :ref:`ogn_test_data` for more information on how to add tests of this nature. For this node we would want to add scripted tests that do things like confirm that elapsedTime increases during evaluation, and that the time values are changing during an animation playback. Modify Attribute Names In Scripts Or USD Files ---------------------------------------------- Previously, attribute names had no well-defined structure and so there may be existing scripts or USD files (.usda in particular) that reference those names which, under OGN rules may have changed. In extreme cases when content is in USD binary format or in customer's hands where it can't be changed you may have to implemented the node's *updateNodeVersion()* method to handle the renaming. Here's an example of how this node looks in a USD file before conversion: .. code-block:: usda def ComputeNode "timeNode" { custom token node:type = "Time" custom int node:typeVersion = 1 double output:time } To fix this we rename the existing attributes and node type, and add in the missing ones for completeness: .. code-block:: usda :linenos: :emphasize-lines: 3,5-9 def ComputeNode "timeNode" { custom token node:type = "omni.graph.core.Time" custom int node:typeVersion = 1 double outputs:time double outputs:frame double outputs:fps double outputs:elapsedTime double outputs:timeSinceStart } And this is a place where attributes were being accessed by a test script: .. code-block:: python time_node = graph.get_node("/defaultPrim/timeNode") time_attr = time_node.get_attribute("output:time") which is also corrected with a simple renaming: .. code-block:: python :linenos: :emphasize-lines: 2 time_node = graph.get_node("/defaultPrim/timeNode") time_attr = time_node.get_attribute("outputs:time") Final Result - The Converted Node --------------------------------- If all has gone well that should be all you need to do to fully convert your node to the .ogn format. Adding the macro call ``REGISTER_OGN_NODE()`` at the end of the file ensures the node is properly registered when the extension loads. Note the position of the namespaces. Here is the final version of the Time node: .. code-block:: c++ :linenos: // Copyright (c) 2018-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 <OgnTimeDatabase.h> #include "GraphContext.h" namespace omni { namespace graph { namespace core { class OgnTime { public: static bool compute(OgnTimeDatabase& db) { const GraphContext::Globals globals = db.abi_context().context->getGlobals(); db.outputs.time() = (double)globals.currentTime; db.outputs.frame() = (double)globals.frameTime; db.outputs.fps() = (double)globals.fps; db.outputs.elapsedTime() = (double)globals.elapsedTime; db.outputs.timeSinceStart() = (double)globals.timeSinceStart; return true; } }; REGISTER_OGN_NODE() } // namespace core } // namespace graph } // namespace omni
21,359
reStructuredText
37.978102
121
0.635329
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/conversionTutorial/build_conversion.rst
.. _ogn_build_conversion: Tutorial - OmniGraph Build Environment Conversion ================================================= These steps will set up the extension to enable building the .ogn file generation and access the generated tests, include file, and Python file. This only has to be done once per extension, after which any newly converted or created nodes will be automatically picked up by the build. Once the build has been set up any existing nodes can be converted to the .ogn format using the steps described in :ref:`ogn_node_conversion`. .. note:: If you are building outside Kit you will have to add access to the OGN processing tools in your main premake5.lua file. See :ref:`ogn_building_outside_kit` for more details. .. contents:: Build Conversion Steps Step 1 : File Structure ----------------------- These are a set of guidelines for file locations and contents that make things consistent, which in turn makes the lives of developers easier when looking at different sections of code. See :ref:`ogn_recommended_directory_structure` for more information on why the directory is structured this way. Here is the file structure of the extension containing the jiggle node before conversion: .. code-block:: text omni.anim.jiggle/ ├── bindings/ | └── BindingsPython.cpp ├── config/ | └── extension.toml ├── plugins/ | ├── Deformer.cpp | ├── IJiggleDeformer.h | └── JiggleDeformer.cpp ├── premake5.lua └── python/ ├── __init__.py └── scripts/ ├── commands.py ├── extension.py ├── jiggleDeformer.py ├── kit_utils.py ├── menu.py └── test.py Python Scripts ++++++++++++++ First thing to note is that we'd like to keep the utility scripts in the ``python`` subdirectory separate from any tests. The directories can be rearranged with a simple git command: .. code-block:: bash git mv python/scripts/tests.py python/tests That leaves the python directory with this structure: .. code-block:: text python/ ├── __init__.py └── scripts/ ├── commands.py ├── extension.py ├── jiggleDeformer.py ├── kit_utils.py └── menu.py └── tests/ └── test.py .. note:: The reason that ``scripts/`` is a separate subdirectory is to allow the Python code to be linked as a whole in the build rather than copied. That way you can drop any file into the ``scripts/`` directory in your source tree, edit it in place, and have the extension system hot-reload it so that the new script is immediately available while the app is running. Nodes +++++ There is no restriction on how many nodes an extension can support though in this example there is only one. Each node will have two files; one with the suffix ``.ogn``, containing the node description, and one with the suffix ``.cpp``, containing the node class. It is helpful to keep the node naming and location consistent. The convention established is to use **Ogn** as a prefix to the class name, and to put the node files in a ``nodes/`` directory, parallel to ``plugins/``. In the example here the means creating a new directory and renaming the node as follows: .. code-block:: bash mkdir nodes git mv plugins/JiggleDeformer.cpp nodes/OgnJiggleDeformer.cpp touch nodes/OgnJiggleDeformer.ogn The last command creates a placeholder for the file to be populated later. At this point all of the files are in their final location and the directory structure changes look like this: .. code:: text omni.anim.jiggle/ omni.anim.jiggle/ ├── bindings/ ├── bindings/ | └── BindingsPython.cpp | └── BindingsPython.cpp ├── config/ ├── config/ | └── extension.toml | └── extension.toml ├── nodes/ ├── plugins/ | ├── OgnJiggleDeformer.cpp | ├── JiggleDeformer.cpp | └── OgnJiggleDeformer.ogn | | ├── plugins/ | | | ├── Deformer.cpp | ├── Deformer.cpp | └── IJiggleDeformer.h | └── IJiggleDeformer.h ├── premake5.lua ├── premake5.lua └── python/ └── python/ ├── __init__.py ├── __init__.py ├── scripts/ └─── scripts/ | ├── commands.py ├── commands.py | ├── extension.py ├── extensions.py | ├── jiggleDeformer.py ├── jiggleDeformer.py | ├── kit_utils.py ├── kit_utils.py | ├── menu.py ├── menu.py └── tests/ | └── test.py └── test.py Step 2 : Fix Python Imports --------------------------- Since the python files have move the python import directives have to be updated to point to the new locations. Most of them are okay as they are relative, only those whose relative position will change need to be adjusted such as the import of the bindings from ``extension.py``. In addition, the generated ``ogn/`` subdirectory must also be imported if you have any nodes implemented in Python. .. code-block:: python :linenos: :emphasize-lines: 2,6-7 import omni.ext from .bindings._anim_jiggle import * from .menu import DeformerMenu from .commands import * from .test import * class Extension(omni.ext.IExt): def on_startup(self): self._ext = acquire_interface() self._menu = DeformerMenu(self._ext) def on_shutdown(self): release_interface(self._ext) self._menu.on_shutdown() self._menu = None The bindings will now be at the same relative level so the first highlighted line changes to: .. code-block:: python from .bindings._anim_jiggle import * and the tests will be automatically detected via a mechanism to be added later, :ref:`ogn_test_detection`, so the second highlighted line will be deleted. Also, due to the changing locations, the import of ``extension.py`` in the file ``__init__.py`` changes from this: .. code-block:: python from .scripts.extension import * to this .. code-block:: python from .extension import * Step 3 : Add Build Support -------------------------- The OmniGraph nodes, and the .ogn files in particular, require some build support in order to be processed correctly. .. note:: This process assumes you are using the `*extension 2.0* <https://drive.google.com/file/d/1R35g67nzD8tS-NUI0wiAFNyDWoCiklZk/view>`_ plugin interface Here are the original contents of the Jiggle extension's ``premake5.lua`` file, with the areas that will be modified highlighted: .. code-block:: lua :linenos: :emphasize-lines: 3-8,11,14,17-23,25,36,40,42-45,47-65 local ext = get_current_extension_info() -- change name of plugins here local namespace = "omni/anim/jiggle" -- lines below can be copied for other plugins local python_source_path = "python" local plugin_source_path = "plugins" ext.group = "animation" project_ext(ext) project_ext_plugin(ext, "omni.anim.jiggle.plugin") add_files("impl", "plugins") add_files("iface", "%{root}/include/"..namespace) exceptionhandling "On" rtti "On" removeflags { "NoPCH" } -- to speed up USD includes compiling filter {} includedirs { "%{target_deps}/nv_usd/%{config}/include", "%{target_deps}/rtx_plugins/include", "%{target_deps}/cuda/include" } filter { "system:linux" } removeflags { "FatalCompileWarnings", "UndefinedIdentifiers" } includedirs { "%{target_deps}/python/include/python3.7m" } filter { "system:windows" } libdirs { "%{target_deps}/tbb/lib/intel64/vc14" } filter {} libdirs { "%{target_deps}/nv_usd/%{config}/lib" } links {"ar","vt", "gf", "pcp", "sdf", "arch", "usd", "tf", "usdUtils", "usdGeom", "usdSkel", "omni.usd"} filter {} project_ext_bindings { ext = ext, project_name = "omni.anim.jiggle.python", module = "_anim_jiggle", src = "bindings", target_subdir = namespace.."/bindings" } vpaths { ['bindings'] = "bindings/*.*", ['python'] = python_source_path.."/*.py", ['python/scripts'] = python_source_path.."/scripts/*.py" } files { python_source_path.."/*.py", python_source_path.."/scripts/*.py" } includedirs { plugin_source_path } repo_build.prebuild_link { { "python/scripts", ext.target_dir.."/"..namespace.."/scripts" }, } repo_build.prebuild_copy { { "python/*.py", ext.target_dir.."/"..namespace }, } Set up Helper Variables With Paths ++++++++++++++++++++++++++++++++++ The first change is to add a few helper variables containing directories of interest (fixing the generic copy/pasted comments while we are in there). Similar to the *get_current_extension_info()* helper function there is *get_ogn_project_information()* that defines a table of useful information for OGN projects, assuming a common layout. See below for details on what it returns. .. code-block:: lua :linenos: :emphasize-lines: 3-6,9 local ext = get_current_extension_info() -- Helper variable containing standard configuration information for projects containing OGN files local ogn = get_ogn_project_information(ext, "omni/anim/jiggle") -- Grouping also tells the name of the premake file that calls this one - $TOP/premake5-{ext.group}.lua ext.group = "animation" -- Set up common project variables project_ext( ext ) The usage of the ogn table will be illuminated below, as will the function definition that was loaded from omni.graph.tools. This is extracted from the documentation of the *get_ogn_project_information()* function: .. code-block:: lua -- These are the generated table contents: -- Source Paths -- bindings_path : Subdirectory containing the C++ implementing Python bindings -- docs_path : Subdirectory containing the documentation to publish -- nodes_path : Subdirectory containing the C++ OmniGraph nodes -- plugin_path : Subdirectory containing the C++ implementing the plugin -- python_path : Subdirectory containing the Python code -- Target Paths -- python_target_path : Path to the Python import directory of the extension -- python_tests_target_path : Path to the Python tests import directory of the extension -- bindings_module : Name of the Python bindings module for the extension -- bindings_target_path : Pyton bindings module import path, relative to root of the extension's Python tree -- Project Information -- import_path : Subdirectory for both Python and C++ import/include -- namespace : Prefix for project names (import_path with "/" replace by ".") -- plugin_project : Name of the project that builds the C++ code -- ogn_project : Name of the project that processes the .ogn files -- python_project : Name of the project that processes the Python code Add the .ogn files to the project +++++++++++++++++++++++++++++++++ Although this project doesn't use the .ogn files directly it's useful to have them available in the project file. Comments are also added while in here to make it clear what each section is doing. .. code-block:: lua :linenos: :emphasize-lines: 1-3,6 -- ---------------------------------------------------------------------- -- Define the project containing the C++ code project_ext_plugin(ext, ogn.plugin_project) add_files("impl", ogn.plugin_path) add_files("ogn", ogn.nodes_path) The reference to the iface section was removed as it didn't contain any files and under extension 2.0 that is an error. Add the generated code to the include path ++++++++++++++++++++++++++++++++++++++++++ The generated files must be accessible to the project so a helper function *add_ogn_dependencies()* was added to make this common set of dependencies easy to implement. It handles *includedirs*, *libdirs*, *links*, and *dependson* relationships needed by the OGN component of the project, as well as common project compiler configuration. Thanks to those definitions the rest of the project is pared down to this: .. code-block:: lua :linenos: :emphasize-lines: 1-2 -- Add the standard dependencies all OGN projects have add_ogn_dependencies(ogn) includedirs { "%{target_deps}/rtx_plugins/include", "%{target_deps}/cuda/include" } filter { "system:linux" } removeflags { "FatalCompileWarnings", "UndefinedIdentifiers" } includedirs { "%{target_deps}/python/include/python3.7m" } filter { "system:windows" } libdirs { "%{target_deps}/tbb/lib/intel64/vc14" } filter {} links {"ar", "vt", "gf", "pcp", "sdf", "arch", "usd", "tf", "usdUtils", "usdGeom", "usdSkel", "omni.usd"} Insert .ogn project +++++++++++++++++++ The .ogn processing must precede the compiling of files including the generated headers so it must always happen first. Unfortunately the current build system doesn't allow for individual file dependencies like that so instead a secondary project must be set up that will process your .ogn files. The easiest place to insert it is just before the Python project definition: .. code-block:: lua :linenos: :emphasize-lines: 1-3 -- ---------------------------------------------------------------------- -- Breaking this out as a separate project ensures the .ogn files are processed before their results are needed project_ext_ogn( ext, ogn ) Notice the *ogn* table defined earlier being passed in to the project definition function. Update extension definition +++++++++++++++++++++++++++ In some cases this may not be necessary but our example extension uses the old extension definition for its Python files as follows: .. code-block:: lua :linenos: :emphasize-lines: 8-16 project_ext_bindings { ext = ext, project_name = namespace..".python", module = "_anim_jiggle", src = "bindings", target_subdir = import_path.."/bindings" } vpaths { ['bindings'] = "bindings/*.*", ['python'] = python_source_path.."/*.py", ['python/scripts'] = python_source_path.."/scripts/*.py" } files { python_source_path.."/*.py", python_source_path.."/scripts/*.py" } This combination of **vpaths** and **files** definitions is replaced under **extension 2.0** with the following, also adding the new ``python/tests`` directory to the definition: .. code-block:: lua :linenos: :emphasize-lines: 3,9-12 project_ext_bindings { ext = ext, project_name = python_project, module = "_anim_jiggle", src = "bindings", target_subdir = import_path.."/bindings" } -- All Python script and documentation files are part of this project add_files("bindings", "bindings/*.*") add_files("python", "python/*.py") add_files("python/scripts", "python/scripts/**.py") add_files("python/tests", "python/tests/**.py") The parameters to the project can be replaced with the ones defined in the *ogn* table: .. code-block:: lua :linenos: :emphasize-lines: 1-2,5-8 -- ---------------------------------------------------------------------- -- Python support and scripts for the Jiggle deformer project_ext_bindings { ext = ext, project_name = ogn.python_project, module = ogn.bindings_module, src = ogn.bindings_path, target_subdir = ogn.bindings_target_path } Set up OGN Dependencies for Python Nodes ++++++++++++++++++++++++++++++++++++++++ Python nodes will function best if they have hot reloading capability (i.e. a change you make to the source file will be immediately reflected in the running application). The function that sets up project dependencies for OGN, **add_ogn_dependencies** has an extra parameter that is a table of directories in which Python OGN nodes live. This is the directory where your OGN node files are named *OgnMyNode.py*. While it's helpful to have the .ogn file in the same directory it's not necessary for this particular purpose. By adding the relative path to all directories containing these nodes the extension configuration will automatically pick them up and register the nodes with OmniGraph, as well as automatically updating them at runtime if the source files change. Any future nodes added to the named directories will work with no further change to the build file. The directory is linked in the build, not copied, so it picks up all subdirectories as well. The only time you need to modify this table is if a new directory containing Python nodes is created that is a sibling to the currently named directories. As the registration looks for the node file name pattern of **Ogn.*.py** you can put other files in the directory without causing any registration problems. You could even include your top level **python/** directory to ensure all Python nodes are picked up. .. code-block:: lua :linenos: :emphasize-lines: 1-2 -- Add the standard dependencies all OGN projects have, and link directories with Python nodes add_ogn_dependencies(ogn, {"python/nodes"}) Step 4 : Add Extension Support ------------------------------ The build system handles the compile-time support for the nodes, the extension support will add the link-time support. For **extension 2.0** this exists in the form of the file ``config/extension.toml``. It must be taught about the python test modules and the extension dependencies. .. code-block:: lua :linenos: :emphasize-lines: 4,8-15,17,20,22-24 [package] title = "Omniverse Jiggle Deformer" # Main module of the python interface [[python.module]] name = "omni.anim.jiggle" # Additional python module used to make .ogn test files auto-discoverable [[python.module]] name = "omni.anim.jiggle.ogn.tests" # Watch the .ogn files for hot reloading (only for Python files) [fswatcher.patterns] include = ["*.ogn", "*.py"] exclude = ["Ogn*Database.py"] # Other extensions that must be loaded before this one [dependencies] "omni.graph" = {} "omni.graph.tools" = {} "omni.kit.usd_undo" = {} # The generated tests will make use of these modules "omni.usd" = {} "omni.kit.async_engine" = {} [[native.plugin]] path = "bin/${platform}/${config}/*.plugin" recursive = false .. _ogn_test_detection: Step 5 : Add Python Initialization ---------------------------------- Even nodes written entirely in C++ will have Pythonic interfaces, and possibly Python test scripts. It's best if you initialize the OGN code on startup in order to take advantage of it rather than trying to do it manually later. So long as you have an `ogn/` subdirectory in your Python import path this will all be taken care of automatically for your; both registration and deregistration of your nodes when the extension loads and unloads respectively. Step 6 : Set up automatic test detection (optional) --------------------------------------------------- While you could set up test inclusion manually, you would have to add every new test file you create as well. A mechanism was created to automatically scan a directory for test files and add them to the list testrunner uses for regression tests. This operates in a similar manner to how the build looks for test files, but at runtime rather than build time. To enable this test detection, create ``python/tests/__init__.py`` with the content below. (Other content is fine if you need it for other tests, this code can appear anywhere in that file.) .. 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 Now that the build can handle the .ogn files, existing nodes can be converted to the .ogn format using the steps described in :ref:`ogn_node_conversion`. Final Result - The Converted Build Script ----------------------------------------- As reference, here is the final version of the file ``omni.anim.jiggle/premake5.lua`` with all new lines highlighted: .. code-block:: lua :linenos: :emphasize-lines: 4,7,14,17,20,23,39,46-49,58,63-66 local ext = get_current_extension_info() -- Helper variable containing standard configuration information for projects containing OGN files local ogn = get_ogn_project_information(ext, "omni/anim/jiggle") -- Grouping also tells the name of the premake file that calls this one - $TOP/premake5-{ext.group}.lua ext.group = "animation" -- Set up common project variables project_ext( ext ) -- ---------------------------------------------------------------------- -- Define the project containing the C++ code project_ext_plugin(ext, ogn.plugin_project) add_files("impl", ogn.plugin_path) add_files("ogn", ogn.nodes_path) -- Add the standard dependencies all OGN projects have add_ogn_dependencies(ogn) includedirs { "%{target_deps}/rtx_plugins/include", "%{target_deps}/cuda/include" } filter { "system:linux" } removeflags { "FatalCompileWarnings", "UndefinedIdentifiers" } includedirs { "%{target_deps}/python/include/python3.7m" } filter { "system:windows" } libdirs { "%{target_deps}/tbb/lib/intel64/vc14" } filter {} links {"ar", "vt", "gf", "pcp", "sdf", "arch", "usd", "tf", "usdUtils", "usdGeom", "usdSkel", "omni.usd"} -- ---------------------------------------------------------------------- -- Breaking this out as a separate project ensures the .ogn files are processed before their results are needed project_ext_ogn( ext, ogn ) -- ---------------------------------------------------------------------- -- Python support and scripts for the Jiggle deformer project_ext_bindings { ext = ext, project_name = ogn.python_project, module = ogn.bindings_module, src = ogn.bindings_path, target_subdir = ogn.bindings_target_path } -- All Python script and documentation files are part of this project add_files("bindings", "bindings/*.*") add_files("python", "python/*.py") add_files("python/tests", "python/tests/**.py") -- Add the standard dependencies all OGN projects have, and link directories with Python nodes add_ogn_dependencies(ogn, {"python/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/scripts", ogn.python_target_path.."/scripts" }, { "python/tests", ogn.python_tests_target_path }, }
23,996
reStructuredText
37.580386
121
0.626563
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/conversionTutorial/building_outside_kit.rst
.. _ogn_building_outside_kit: Tutorial - Building OmniGraph Outside Kit ========================================= Every effort was made to make OmniGraph just work when you build using the Kit SDK, however there is still one piece of configuration that must be done manually. As the initial implementation of Kit does not use C++20, a helper package was installed to enable some advanced features that the OGN generated code requires. To pick this package up you only have to add it to the filter in your `deps/target-deps.packman.xml` file where Kit is referenced. .. code-block:: xml :linenos: :emphasize-lines: 5 <!-- Import Kit SDk target-deps xml file to steal some deps from it: --> <import path="../_build/kit_release/deps/target-deps.packman.xml"> <filter include="pybind11" /> <filter include="fmt" /> <filter include="gsl" /> </import> That's all that is required to allow any extension in your build to access the .ogn file processing. In order to convert a specific extension to handle .ogn files see the more detailed document on :ref:`ogn_build_conversion`.
1,116
reStructuredText
41.961537
131
0.706989
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial6/tutorial6.rst
.. _ogn_tutorial_tupleArrays: Tutorial 6 - Array of Tuples ============================ Arrays and tuples can be combined to create common attribute types such as **float[3][]**, and array of 3 floats. This node takes two arrays of float[3]s and generates an output array consisting of the element-wise dot products. The *ogn* file shows the implementation of a node named "omni.graph.tutorials.TupleArrays", which has two tuple-array inputs and a simple array output. OgnTutorialTupleArrays.ogn -------------------------- .. literalinclude:: OgnTutorialTupleArrays.ogn :linenos: :language: json OgnTutorialTupleArrays.cpp -------------------------- The *cpp* file contains the implementation of the compute method, which computes the dot products. .. literalinclude:: OgnTutorialTupleArrays.cpp :linenos: :language: c++ There are typedefs set up for USD-compatible types, e.g. for *float[3]* you get *GfVec3f*. Other types, for whom there is no USD equivalent, are implemented as *ogn::tuple<TYPE, N>*. See the complete table of data types in :ref:`ogn_attribute_types`. +-------------------+----------------------------------+ | Database Function | Returned Type | +===================+==================================+ | inputs.a() | const ogn::const_array<GfVec3f>& | +-------------------+----------------------------------+ | inputs.b() | const ogn::const_array<GfVec3f>& | +-------------------+----------------------------------+ | outputs.result() | ogn::array<GfVec3f>& | +-------------------+----------------------------------+ Note that the tuple array access is identical to the simple data array access, except that the types are now the compound tuple types.
1,745
reStructuredText
39.60465
112
0.573639
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()
1,501
C++
35.634145
110
0.664224
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()
2,812
C++
46.677965
120
0.664296
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(); };
2,957
reStructuredText
43.149253
120
0.637809
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
3,995
C++
36
119
0.580225
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
1,652
Python
40.324999
108
0.621065
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])
4,930
reStructuredText
41.878261
136
0.722718
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
1,558
reStructuredText
44.85294
116
0.749679
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()
3,784
C++
44.059523
119
0.68129
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()
2,547
C++
32.526315
95
0.708677
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
1,656
reStructuredText
40.424999
125
0.733092
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
1,529
Python
41.499999
116
0.689993
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()
3,786
C++
42.03409
142
0.637612
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.
6,896
reStructuredText
44.375
120
0.571491
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()
3,142
C++
49.693548
114
0.614895
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
3,475
Python
52.476922
118
0.671655
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.
8,133
reStructuredText
44.188889
120
0.628673
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
3,600
Python
46.381578
119
0.709167
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
1,017
reStructuredText
35.357142
120
0.725664
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")])
8,136
Python
55.506944
120
0.599435
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()
17,881
C++
49.230337
144
0.523125
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
2,868
reStructuredText
38.301369
122
0.702232
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
1,752
reStructuredText
42.824999
120
0.726027
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
4,959
C++
40.333333
125
0.647308
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)
2,925
Python
46.193548
120
0.666667
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
3,273
Python
45.771428
120
0.651085
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
4,825
C++
41.333333
152
0.602487
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
2,106
reStructuredText
43.829786
127
0.728395
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
2,702
Python
48.145454
113
0.663583
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
5,639
reStructuredText
45.229508
125
0.700656
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()
6,228
C++
40.251655
121
0.657354
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()
3,302
C++
50.609374
115
0.694428
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);
6,658
reStructuredText
53.138211
124
0.499549
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
3,391
Python
50.393939
120
0.699204
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()
2,216
C++
47.195651
124
0.686823
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
1,811
reStructuredText
35.979591
117
0.70127
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()
2,795
C++
31.511628
104
0.589982
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
10,947
reStructuredText
36.365188
136
0.698273
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())
2,843
Python
52.660376
118
0.65459
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()
1,507
C++
34.904761
77
0.642999
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]]
2,381
reStructuredText
34.029411
118
0.524989
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)) )
3,448
Python
37.322222
120
0.633991
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
1,393
reStructuredText
36.675675
130
0.703518
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
8,539
Python
48.364162
187
0.65031
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
13,304
Python
47.915441
186
0.63402
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialRoleData.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_color3d', [1.0, 2.0, 3.0], False], ['inputs:a_color3f', [11.0, 12.0, 13.0], False], ['inputs:a_color3h', [21.0, 22.0, 23.0], False], ['inputs:a_color4d', [1.0, 2.0, 3.0, 4.0], False], ['inputs:a_color4f', [11.0, 12.0, 13.0, 14.0], False], ['inputs:a_color4h', [21.0, 22.0, 23.0, 24.0], False], ['inputs:a_frame', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0], False], ['inputs:a_matrix2d', [1.0, 2.0, 3.0, 4.0], False], ['inputs:a_matrix3d', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], False], ['inputs:a_matrix4d', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0], False], ['inputs:a_normal3d', [1.0, 2.0, 3.0], False], ['inputs:a_normal3f', [11.0, 12.0, 13.0], False], ['inputs:a_normal3h', [21.0, 22.0, 23.0], False], ['inputs:a_point3d', [1.0, 2.0, 3.0], False], ['inputs:a_point3f', [11.0, 12.0, 13.0], False], ['inputs:a_point3h', [21.0, 22.0, 23.0], False], ['inputs:a_quatd', [1.0, 2.0, 3.0, 4.0], False], ['inputs:a_quatf', [11.0, 12.0, 13.0, 14.0], False], ['inputs:a_quath', [21.0, 22.0, 23.0, 24.0], False], ['inputs:a_texcoord2d', [1.0, 2.0], False], ['inputs:a_texcoord2f', [11.0, 12.0], False], ['inputs:a_texcoord2h', [21.0, 22.0], False], ['inputs:a_texcoord3d', [1.0, 2.0, 3.0], False], ['inputs:a_texcoord3f', [11.0, 12.0, 13.0], False], ['inputs:a_texcoord3h', [21.0, 22.0, 23.0], False], ['inputs:a_timecode', 10.0, False], ['inputs:a_vector3d', [1.0, 2.0, 3.0], False], ['inputs:a_vector3f', [11.0, 12.0, 13.0], False], ['inputs:a_vector3h', [21.0, 22.0, 23.0], False], ], 'outputs': [ ['outputs:a_color3d', [2.0, 3.0, 4.0], False], ['outputs:a_color3f', [12.0, 13.0, 14.0], False], ['outputs:a_color3h', [22.0, 23.0, 24.0], False], ['outputs:a_color4d', [2.0, 3.0, 4.0, 5.0], False], ['outputs:a_color4f', [12.0, 13.0, 14.0, 15.0], False], ['outputs:a_color4h', [22.0, 23.0, 24.0, 25.0], False], ['outputs:a_frame', [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0], False], ['outputs:a_matrix2d', [2.0, 3.0, 4.0, 5.0], False], ['outputs:a_matrix3d', [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], False], ['outputs:a_matrix4d', [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0], False], ['outputs:a_normal3d', [2.0, 3.0, 4.0], False], ['outputs:a_normal3f', [12.0, 13.0, 14.0], False], ['outputs:a_normal3h', [22.0, 23.0, 24.0], False], ['outputs:a_point3d', [2.0, 3.0, 4.0], False], ['outputs:a_point3f', [12.0, 13.0, 14.0], False], ['outputs:a_point3h', [22.0, 23.0, 24.0], False], ['outputs:a_quatd', [2.0, 3.0, 4.0, 5.0], False], ['outputs:a_quatf', [12.0, 13.0, 14.0, 15.0], False], ['outputs:a_quath', [22.0, 23.0, 24.0, 25.0], False], ['outputs:a_texcoord2d', [2.0, 3.0], False], ['outputs:a_texcoord2f', [12.0, 13.0], False], ['outputs:a_texcoord2h', [22.0, 23.0], False], ['outputs:a_texcoord3d', [2.0, 3.0, 4.0], False], ['outputs:a_texcoord3f', [12.0, 13.0, 14.0], False], ['outputs:a_texcoord3h', [22.0, 23.0, 24.0], False], ['outputs:a_timecode', 11.0, False], ['outputs:a_vector3d', [2.0, 3.0, 4.0], False], ['outputs:a_vector3f', [12.0, 13.0, 14.0], False], ['outputs:a_vector3h', [22.0, 23.0, 24.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_RoleData", "omni.graph.tutorials.RoleData", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.RoleData 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_RoleData","omni.graph.tutorials.RoleData", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.RoleData 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_RoleData", "omni.graph.tutorials.RoleData", 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.RoleData User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialRoleDataDatabase import OgnTutorialRoleDataDatabase test_file_name = "OgnTutorialRoleDataTemplate.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_RoleData") database = OgnTutorialRoleDataDatabase(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_color3d")) attribute = test_node.get_attribute("inputs:a_color3d") db_value = database.inputs.a_color3d 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:a_color3f")) attribute = test_node.get_attribute("inputs:a_color3f") db_value = database.inputs.a_color3f 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:a_color3h")) attribute = test_node.get_attribute("inputs:a_color3h") db_value = database.inputs.a_color3h 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:a_color4d")) attribute = test_node.get_attribute("inputs:a_color4d") db_value = database.inputs.a_color4d expected_value = [0.0, 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:a_color4f")) attribute = test_node.get_attribute("inputs:a_color4f") db_value = database.inputs.a_color4f expected_value = [0.0, 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:a_color4h")) attribute = test_node.get_attribute("inputs:a_color4h") db_value = database.inputs.a_color4h expected_value = [0.0, 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:a_frame")) attribute = test_node.get_attribute("inputs:a_frame") db_value = database.inputs.a_frame 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)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_matrix2d")) attribute = test_node.get_attribute("inputs:a_matrix2d") db_value = database.inputs.a_matrix2d expected_value = [[1.0, 0.0], [0.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:a_matrix3d")) attribute = test_node.get_attribute("inputs:a_matrix3d") db_value = database.inputs.a_matrix3d expected_value = [[1.0, 0.0, 0.0], [0.0, 1.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)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_matrix4d")) attribute = test_node.get_attribute("inputs:a_matrix4d") db_value = database.inputs.a_matrix4d 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)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:a_normal3d")) attribute = test_node.get_attribute("inputs:a_normal3d") db_value = database.inputs.a_normal3d 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:a_normal3f")) attribute = test_node.get_attribute("inputs:a_normal3f") db_value = database.inputs.a_normal3f 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:a_normal3h")) attribute = test_node.get_attribute("inputs:a_normal3h") db_value = database.inputs.a_normal3h 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:a_point3d")) attribute = test_node.get_attribute("inputs:a_point3d") db_value = database.inputs.a_point3d 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:a_point3f")) attribute = test_node.get_attribute("inputs:a_point3f") db_value = database.inputs.a_point3f 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:a_point3h")) attribute = test_node.get_attribute("inputs:a_point3h") db_value = database.inputs.a_point3h 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:a_quatd")) attribute = test_node.get_attribute("inputs:a_quatd") db_value = database.inputs.a_quatd expected_value = [0.0, 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:a_quatf")) attribute = test_node.get_attribute("inputs:a_quatf") db_value = database.inputs.a_quatf expected_value = [0.0, 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:a_quath")) attribute = test_node.get_attribute("inputs:a_quath") db_value = database.inputs.a_quath expected_value = [0.0, 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:a_texcoord2d")) attribute = test_node.get_attribute("inputs:a_texcoord2d") db_value = database.inputs.a_texcoord2d expected_value = [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:a_texcoord2f")) attribute = test_node.get_attribute("inputs:a_texcoord2f") db_value = database.inputs.a_texcoord2f expected_value = [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:a_texcoord2h")) attribute = test_node.get_attribute("inputs:a_texcoord2h") db_value = database.inputs.a_texcoord2h expected_value = [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:a_texcoord3d")) attribute = test_node.get_attribute("inputs:a_texcoord3d") db_value = database.inputs.a_texcoord3d 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:a_texcoord3f")) attribute = test_node.get_attribute("inputs:a_texcoord3f") db_value = database.inputs.a_texcoord3f 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:a_texcoord3h")) attribute = test_node.get_attribute("inputs:a_texcoord3h") db_value = database.inputs.a_texcoord3h 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:a_timecode")) attribute = test_node.get_attribute("inputs:a_timecode") db_value = database.inputs.a_timecode 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:a_vector3d")) attribute = test_node.get_attribute("inputs:a_vector3d") db_value = database.inputs.a_vector3d 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:a_vector3f")) attribute = test_node.get_attribute("inputs:a_vector3f") db_value = database.inputs.a_vector3f 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:a_vector3h")) attribute = test_node.get_attribute("inputs:a_vector3h") db_value = database.inputs.a_vector3h 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:a_color3d")) attribute = test_node.get_attribute("outputs:a_color3d") db_value = database.outputs.a_color3d self.assertTrue(test_node.get_attribute_exists("outputs:a_color3f")) attribute = test_node.get_attribute("outputs:a_color3f") db_value = database.outputs.a_color3f self.assertTrue(test_node.get_attribute_exists("outputs:a_color3h")) attribute = test_node.get_attribute("outputs:a_color3h") db_value = database.outputs.a_color3h self.assertTrue(test_node.get_attribute_exists("outputs:a_color4d")) attribute = test_node.get_attribute("outputs:a_color4d") db_value = database.outputs.a_color4d self.assertTrue(test_node.get_attribute_exists("outputs:a_color4f")) attribute = test_node.get_attribute("outputs:a_color4f") db_value = database.outputs.a_color4f self.assertTrue(test_node.get_attribute_exists("outputs:a_color4h")) attribute = test_node.get_attribute("outputs:a_color4h") db_value = database.outputs.a_color4h self.assertTrue(test_node.get_attribute_exists("outputs:a_frame")) attribute = test_node.get_attribute("outputs:a_frame") db_value = database.outputs.a_frame self.assertTrue(test_node.get_attribute_exists("outputs:a_matrix2d")) attribute = test_node.get_attribute("outputs:a_matrix2d") db_value = database.outputs.a_matrix2d self.assertTrue(test_node.get_attribute_exists("outputs:a_matrix3d")) attribute = test_node.get_attribute("outputs:a_matrix3d") db_value = database.outputs.a_matrix3d self.assertTrue(test_node.get_attribute_exists("outputs:a_matrix4d")) attribute = test_node.get_attribute("outputs:a_matrix4d") db_value = database.outputs.a_matrix4d self.assertTrue(test_node.get_attribute_exists("outputs:a_normal3d")) attribute = test_node.get_attribute("outputs:a_normal3d") db_value = database.outputs.a_normal3d self.assertTrue(test_node.get_attribute_exists("outputs:a_normal3f")) attribute = test_node.get_attribute("outputs:a_normal3f") db_value = database.outputs.a_normal3f self.assertTrue(test_node.get_attribute_exists("outputs:a_normal3h")) attribute = test_node.get_attribute("outputs:a_normal3h") db_value = database.outputs.a_normal3h self.assertTrue(test_node.get_attribute_exists("outputs:a_point3d")) attribute = test_node.get_attribute("outputs:a_point3d") db_value = database.outputs.a_point3d self.assertTrue(test_node.get_attribute_exists("outputs:a_point3f")) attribute = test_node.get_attribute("outputs:a_point3f") db_value = database.outputs.a_point3f self.assertTrue(test_node.get_attribute_exists("outputs:a_point3h")) attribute = test_node.get_attribute("outputs:a_point3h") db_value = database.outputs.a_point3h self.assertTrue(test_node.get_attribute_exists("outputs:a_quatd")) attribute = test_node.get_attribute("outputs:a_quatd") db_value = database.outputs.a_quatd self.assertTrue(test_node.get_attribute_exists("outputs:a_quatf")) attribute = test_node.get_attribute("outputs:a_quatf") db_value = database.outputs.a_quatf self.assertTrue(test_node.get_attribute_exists("outputs:a_quath")) attribute = test_node.get_attribute("outputs:a_quath") db_value = database.outputs.a_quath self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord2d")) attribute = test_node.get_attribute("outputs:a_texcoord2d") db_value = database.outputs.a_texcoord2d self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord2f")) attribute = test_node.get_attribute("outputs:a_texcoord2f") db_value = database.outputs.a_texcoord2f self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord2h")) attribute = test_node.get_attribute("outputs:a_texcoord2h") db_value = database.outputs.a_texcoord2h self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord3d")) attribute = test_node.get_attribute("outputs:a_texcoord3d") db_value = database.outputs.a_texcoord3d self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord3f")) attribute = test_node.get_attribute("outputs:a_texcoord3f") db_value = database.outputs.a_texcoord3f self.assertTrue(test_node.get_attribute_exists("outputs:a_texcoord3h")) attribute = test_node.get_attribute("outputs:a_texcoord3h") db_value = database.outputs.a_texcoord3h self.assertTrue(test_node.get_attribute_exists("outputs:a_timecode")) attribute = test_node.get_attribute("outputs:a_timecode") db_value = database.outputs.a_timecode self.assertTrue(test_node.get_attribute_exists("outputs:a_vector3d")) attribute = test_node.get_attribute("outputs:a_vector3d") db_value = database.outputs.a_vector3d self.assertTrue(test_node.get_attribute_exists("outputs:a_vector3f")) attribute = test_node.get_attribute("outputs:a_vector3f") db_value = database.outputs.a_vector3f self.assertTrue(test_node.get_attribute_exists("outputs:a_vector3h")) attribute = test_node.get_attribute("outputs:a_vector3h") db_value = database.outputs.a_vector3h
25,764
Python
52.123711
197
0.662669
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tests/TestOgnTutorialDefaults.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_bool', False, False], ['outputs:a_double', 0.0, False], ['outputs:a_float', 0.0, False], ['outputs:a_half', 0.0, False], ['outputs:a_int', 0, False], ['outputs:a_int64', 0, False], ['outputs:a_string', "", False], ['outputs:a_token', "", False], ['outputs:a_uchar', 0, False], ['outputs:a_uint', 0, False], ['outputs:a_uint64', 0, False], ['outputs:a_int2', [0, 0], False], ['outputs:a_matrix', [1.0, 0.0, 0.0, 1.0], False], ['outputs:a_array', [], 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_Defaults", "omni.graph.tutorials.Defaults", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Defaults 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_Defaults","omni.graph.tutorials.Defaults", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.tutorials.Defaults 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_Defaults", "omni.graph.tutorials.Defaults", 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.Defaults User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.tutorials.ogn.OgnTutorialDefaultsDatabase import OgnTutorialDefaultsDatabase test_file_name = "OgnTutorialDefaultsTemplate.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_Defaults") database = OgnTutorialDefaultsDatabase(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_array")) attribute = test_node.get_attribute("inputs:a_array") db_value = database.inputs.a_array 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_bool")) attribute = test_node.get_attribute("inputs:a_bool") db_value = database.inputs.a_bool 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:a_double")) attribute = test_node.get_attribute("inputs:a_double") db_value = database.inputs.a_double 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_float")) attribute = test_node.get_attribute("inputs:a_float") db_value = database.inputs.a_float 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_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_int2")) attribute = test_node.get_attribute("inputs:a_int2") db_value = database.inputs.a_int2 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_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_matrix")) attribute = test_node.get_attribute("inputs:a_matrix") db_value = database.inputs.a_matrix expected_value = [[1.0, 0.0], [0.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:a_string")) attribute = test_node.get_attribute("inputs:a_string") db_value = database.inputs.a_string 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_token")) attribute = test_node.get_attribute("inputs:a_token") db_value = database.inputs.a_token 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_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_array")) attribute = test_node.get_attribute("outputs:a_array") db_value = database.outputs.a_array 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_int2")) attribute = test_node.get_attribute("outputs:a_int2") db_value = database.outputs.a_int2 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_matrix")) attribute = test_node.get_attribute("outputs:a_matrix") db_value = database.outputs.a_matrix 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
12,650
Python
47.84556
197
0.686087
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_omnigraph_python_interface.py
"""Basic tests of the Python interface to C++ nodes generated from a .ogn file""" import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.tutorials.ogn.OgnTutorialSimpleDataDatabase import OgnTutorialSimpleDataDatabase # ====================================================================== class TestOmniGraphPythonInterface(ogts.OmniGraphTestCase): """Run a simple unit test that exercises generated Python interface functionality""" # ---------------------------------------------------------------------- async def test_setting_in_ogn_python_api(self): """Test ability to set inputs on a node and retrieve them""" (_, [simple_node], _, _) = og.Controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: ("PyTest_SimpleNode", "omni.graph.tutorials.SimpleData"), }, ) await og.Controller.evaluate() interface = OgnTutorialSimpleDataDatabase(simple_node) # Set input values through the database interface interface.inputs.a_bool = False interface.inputs.a_half = 2.0 interface.inputs.a_int = 3 interface.inputs.a_int64 = 4 interface.inputs.a_float = 5.0 interface.inputs.a_double = 6.0 # interface.inputs.a_token = "hello" interface.inputs.unsigned_a_uchar = 7 interface.inputs.unsigned_a_uint = 8 interface.inputs.unsigned_a_uint64 = 9 # Run the node's compute method await og.Controller.evaluate() # Retrieve output values from the database interface and verify against expected values self.assertEqual(interface.outputs.a_bool, True) self.assertAlmostEqual(interface.outputs.a_half, 3.0) self.assertEqual(interface.outputs.a_int, 4) self.assertEqual(interface.outputs.a_int64, 5) self.assertAlmostEqual(interface.outputs.a_float, 6.0) self.assertAlmostEqual(interface.outputs.a_double, 7.0) # self.assertEqual(interface.outputs.a_token, "world") self.assertEqual(interface.outputs.unsigned_a_uchar, 8) self.assertEqual(interface.outputs.unsigned_a_uint, 9) self.assertEqual(interface.outputs.unsigned_a_uint64, 10) # ---------------------------------------------------------------------- async def test_check_has_state(self): """Test ability to correctly determine if a node has marked itself as having internal state""" stateless_node_type = og.get_node_type("omni.graph.tutorials.SimpleData") stateful_node_type = og.get_node_type("omni.graph.tutorials.StatePy") self.assertFalse(stateless_node_type.has_state()) self.assertTrue(stateful_node_type.has_state())
2,753
Python
46.482758
106
0.625499
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.tutorials as ogtu from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphTutorialsApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests"] async def test_api(self): _check_module_api_consistency(ogtu, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(ogtu.tests, is_test_module=True) # noqa: PLW0212 async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents(ogtu, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212 _check_public_api_contents(ogtu.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
936
Python
48.315787
108
0.65812
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_tutorial_extended_types.py
""" Tests for the omni.graph.tutorials.ExtendedTypes and omni.graph.tutorials.ExtendedTypesPy nodes """ import omni.graph.core as og import omni.graph.core.tests as ogts class TestTutorialExtendedTypes(ogts.OmniGraphTestCase): """Extended attribute type tests require multiple nodes, not supported in the .ogn test framework""" # ---------------------------------------------------------------------- async def _test_tutorial_extended_attributes_node(self, test_node_type_name: str): """Test basic operation of the tutorial node containing extended attributes""" # Set up a graph that creates full type resolution for simple and array types of the extended attribute node # # SimpleIn ----=> Extended1 ----=> SimpleOut # \ / \ / # X X # / \ / \ # ArrayIn ----=> Extended2 ----=> ArrayOut # keys = og.Controller.Keys (_, [simple_node, _, extended_node_1, extended_node_2, array_node, _], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("SimpleIn", "omni.graph.tutorials.SimpleData"), ("SimpleOut", "omni.graph.tutorials.SimpleData"), ("Extended1", test_node_type_name), ("Extended2", test_node_type_name), ("ArrayIn", "omni.graph.tutorials.ArrayData"), ("ArrayOut", "omni.graph.tutorials.ArrayData"), ], keys.CONNECT: [ ("SimpleIn.outputs:a_float", "Extended1.inputs:floatOrToken"), ("Extended1.outputs:doubledResult", "SimpleOut.inputs:a_float"), ("ArrayIn.outputs:result", "Extended1.inputs:toNegate"), ("Extended1.outputs:negatedResult", "ArrayOut.inputs:original"), ("SimpleIn.outputs:a_token", "Extended2.inputs:floatOrToken"), ("Extended2.outputs:doubledResult", "SimpleOut.inputs:a_token"), ("ArrayIn.outputs:negativeValues", "Extended2.inputs:toNegate"), ("Extended2.outputs:negatedResult", "ArrayOut.inputs:gates"), ], keys.SET_VALUES: [ ("SimpleIn.inputs:a_float", 5.0), ("SimpleIn.inputs:a_token", "hello"), ("ArrayIn.inputs:multiplier", 2.0), ("ArrayIn.inputs:original", [5.0, -6.0]), ("ArrayIn.inputs:gates", [False, True]), ], }, ) await og.Controller.evaluate() # Check that the inputs into the extended type nodes are correct self.assertEqual(6.0, og.Controller.get(("outputs:a_float", simple_node))) self.assertEqual("world", og.Controller.get(("outputs:a_token", simple_node))) self.assertCountEqual([5.0, -12.0], og.Controller.get(("outputs:result", array_node))) self.assertCountEqual([False, True], og.Controller.get(("outputs:negativeValues", array_node))) # Check the extended simple value outputs self.assertEqual(12.0, og.Controller.get(("outputs:doubledResult", extended_node_1))) self.assertEqual("worldworld", og.Controller.get(("outputs:doubledResult", extended_node_2))) # Check the extended array value outputs self.assertCountEqual([-5.0, 12.0], og.Controller.get(("outputs:negatedResult", extended_node_1))) self.assertCountEqual([True, False], og.Controller.get(("outputs:negatedResult", extended_node_2))) # ---------------------------------------------------------------------- async def test_tutorial_extended_attributes_node_cpp(self): """Test basic operation of the C++ tutorial node containing extended attributes.""" await self._test_tutorial_extended_attributes_node("omni.graph.tutorials.ExtendedTypes") # ---------------------------------------------------------------------- async def test_tutorial_extended_attributes_node_python(self): """Test basic operation of the Python tutorial node containing extended attributes.""" await self._test_tutorial_extended_attributes_node("omni.graph.tutorials.ExtendedTypesPy") # ---------------------------------------------------------------------- async def _test_tutorial_extended_attributes_tuples(self, test_node_type_name: str): """Test basic operation of the tutorial node containing extended attributes on its tuple-accepting attributes""" # Set up a graph that creates full type resolution for the tuple types of the extended attribute node with # two different resolved types. # keys = og.Controller.Keys ( _, [tuple_node, _, extended_node_1, extended_node_2, tuple_array_node, _, simple_node, _], _, _, ) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("TupleIn", "omni.tutorials.TupleData"), ("TupleOut", "omni.tutorials.TupleData"), ("Extended1", test_node_type_name), ("Extended2", test_node_type_name), ("TupleArrayIn", "omni.graph.tutorials.TupleArrays"), ("TupleArrayOut", "omni.graph.tutorials.TupleArrays"), ("SimpleIn", "omni.graph.tutorials.SimpleData"), ("SimpleOut", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("TupleIn.outputs:a_int2", "Extended1.inputs:tuple"), ("Extended1.outputs:tuple", "TupleOut.inputs:a_int2"), ("TupleArrayIn.inputs:a", "Extended1.inputs:flexible"), ("Extended1.outputs:flexible", "TupleArrayOut.inputs:a"), ("TupleIn.outputs:a_float3", "Extended2.inputs:tuple"), ("Extended2.outputs:tuple", "TupleOut.inputs:a_float3"), ("SimpleIn.outputs:a_token", "Extended2.inputs:flexible"), ("Extended2.outputs:flexible", "SimpleOut.inputs:a_token"), ], keys.SET_VALUES: [ ("TupleIn.inputs:a_int2", [4, 2]), ("TupleIn.inputs:a_float3", (4.0, 10.0, 2.0)), ("TupleArrayIn.inputs:a", [[2.0, 3.0, 7.0], [21.0, 14.0, 6.0]]), ("TupleArrayIn.inputs:b", [[21.0, 14.0, 6.0], [2.0, 3.0, 7.0]]), ("SimpleIn.inputs:a_token", "hello"), ], }, ) await og.Controller.evaluate() # Check that the inputs into the extended type nodes are correct self.assertEqual("world", og.Controller.get(("outputs:a_token", simple_node))) self.assertCountEqual([5, 3], og.Controller.get(("outputs:a_int2", tuple_node))) self.assertCountEqual([5.0, 11.0, 3.0], og.Controller.get(("outputs:a_float3", tuple_node))) self.assertCountEqual([126.0, 126.0], og.Controller.get(("outputs:result", tuple_array_node))) # Check the resulting values from resolving the "any" type to tuples self.assertCountEqual([-5, -3], og.Controller.get(("outputs:tuple", extended_node_1))) self.assertCountEqual([-5.0, -11.0, -3.0], og.Controller.get(("outputs:tuple", extended_node_2))) # Check the resulting values from resolving the flexible type as both of its types self.assertEqual("dlrow", og.Controller.get(("outputs:flexible", extended_node_2))) list_expected = [[-2.0, -3.0, -7.0], [-21.0, -14.0, -6.0]] list_computed = og.Controller.get(("outputs:flexible", extended_node_1)) for expected, computed in zip(list_expected, list_computed): self.assertCountEqual(expected, computed) # ---------------------------------------------------------------------- async def test_tutorial_extended_attributes_tuples_cpp(self): """Test basic operation of the C++ tutorial node containing extended attributes.""" await self._test_tutorial_extended_attributes_tuples("omni.graph.tutorials.ExtendedTypes") # ---------------------------------------------------------------------- async def test_tutorial_extended_attributes_tuples_python(self): """Test basic operation of the Python tutorial node containing extended attributes.""" await self._test_tutorial_extended_attributes_tuples("omni.graph.tutorials.ExtendedTypesPy")
8,633
Python
55.431372
120
0.554269
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_omnigraph_deletion.py
"""OmniGraph deletion tests""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.usd class TestOmniGraphDeletion(ogts.OmniGraphTestCase): # In these tests, we test various aspects of deleting things from OG async def test_omnigraph_usd_deletion(self): # In this test we set up 2 very similar looking nodes: # /new_node and /new_node_01. We then delete /new_node # The idea is that this looks very similar to cases like # /parent/path/stuff/mynode where we delete /parent/path # In that case we want to delete mynode, but in our case # we do not want to delete /new_node_01 when /new_node is # deleted. keys = og.Controller.Keys (graph, [new_node, new_node_01], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("new_node", "omni.graph.tutorials.Empty"), ("new_node_01", "omni.graph.tutorials.Empty"), ] }, ) await og.Controller.evaluate() self.assertIsNotNone(new_node_01) self.assertTrue(new_node_01.is_valid()) self.assertIsNotNone(new_node) self.assertTrue(new_node.is_valid()) og.Controller.delete_node(new_node) new_node_01 = graph.get_node("/TestGraph/new_node_01") self.assertIsNotNone(new_node_01) self.assertTrue(new_node_01.is_valid()) new_node = graph.get_node("/TestGraph/new_node") self.assertTrue(not new_node.is_valid()) omni.kit.undo.undo() new_node_01 = graph.get_node("/TestGraph/new_node_01") self.assertIsNotNone(new_node_01) self.assertTrue(new_node_01.is_valid()) new_node = graph.get_node("/TestGraph/new_node") self.assertIsNotNone(new_node) self.assertTrue(new_node.is_valid()) # -------------------------------------------------------------------------------------------------------------- async def test_fabric_dangling_connections(self): # In this test we create two nodes, connect them together. The output of the first node drives the input # of the second node. When we break the connection, we need to verify that the output of the second node # now takes its input from its own value, rather than the connected value (ie. the connection is actually # broken in the fabric). keys = og.Controller.Keys (graph, [node_a, node_b], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("node_a", "omni.graph.tutorials.SimpleData"), ("node_b", "omni.graph.tutorials.SimpleData"), ] }, ) await og.Controller.evaluate() node_a = graph.get_node("/TestGraph/node_a") self.assertIsNotNone(node_a) self.assertTrue(node_a.is_valid()) node_b = graph.get_node("/TestGraph/node_b") self.assertIsNotNone(node_b) self.assertTrue(node_b.is_valid()) upstream_attr = node_a.get_attribute("outputs:a_int") downstream_attr = node_b.get_attribute("inputs:a_int") og.Controller.connect(upstream_attr, downstream_attr) await og.Controller.evaluate() # This node "omni.graph.tutorials.SimpleData" add 1 to the input. The default value of a_int is 0, so the output # of the first node is 1. When this is used as the input to the second node, we expect the value to be 2: value = og.Controller.get(node_b.get_attribute("outputs:a_int")) self.assertEqual(value, 2) og.Controller.disconnect(upstream_attr, downstream_attr) await og.Controller.evaluate() # Now that the connection is broken, the value should now be 1. However, if it didn't actually break the # connection in the fabric, the graph would still "think" it's connected and output 2. value = og.Controller.get(node_b.get_attribute("outputs:a_int")) self.assertEqual(value, 1)
4,140
Python
42.135416
120
0.602657
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_tutorial_state.py
""" Tests for the omnigraph.tutorial.state node """ import omni.graph.core as og import omni.graph.core.tests as ogts class TestTutorialState(ogts.OmniGraphTestCase): """.ogn tests only run once while state tests require multiple evaluations, handled here""" # ---------------------------------------------------------------------- async def test_tutorial_state_node(self): """Test basic operation of the tutorial node containing internal node state""" self.assertTrue(og.get_node_type("omni.graph.tutorials.State").has_state(), "Tutorial state node has state") # Create a set of state nodes, updating after each one so that the state information is properly initialized. # If that requirement weren't there this would just be done in one call. state_nodes = [] for index in range(5): (graph, new_nodes, _, _) = og.Controller.edit( "/StateGraph", { og.Controller.Keys.CREATE_NODES: [ (f"State{index}", "omni.graph.tutorials.State"), ] }, ) state_nodes.append(new_nodes[0]) await og.Controller.evaluate(graph) output_attrs = [state_node.get_attribute("outputs:monotonic") for state_node in state_nodes] output_values = [og.Controller(output_attr).get() for output_attr in output_attrs] for i in range(len(output_values) - 1): self.assertLess(output_values[i], output_values[i + 1], "Comparing state of other nodes") await og.Controller.evaluate(graph) new_values = [og.Controller(output_attr).get() for output_attr in output_attrs] for i in range(len(new_values) - 1): self.assertLess(new_values[i], new_values[i + 1], "Comparing second state of other nodes") for i, new_value in enumerate(new_values): self.assertLess(output_values[i], new_value, "Comparing node state updates")
1,998
Python
45.488371
117
0.605105
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_tutorial_state_attributes_py.py
""" Tests for the omnigraph.tutorial.stateAttributesPy node """ import omni.graph.core as og import omni.graph.core.tests as ogts class TestTutorialStateAttributesPy(ogts.OmniGraphTestCase): """.ogn tests only run once while state tests require multiple evaluations, handled here""" # ---------------------------------------------------------------------- async def test_tutorial_state_attributes_py_node(self): """Test basic operation of the Python tutorial node containing state attributes""" keys = og.Controller.Keys (_, [state_node], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: ("StateNode", "omni.graph.tutorials.StateAttributesPy"), keys.SET_VALUES: ("StateNode.state:reset", True), }, ) await og.Controller.evaluate() reset_attr = og.Controller.attribute("state:reset", state_node) monotonic_attr = og.Controller.attribute("state:monotonic", state_node) self.assertEqual(og.Controller.get(reset_attr), False, "Reset attribute set back to False") self.assertEqual(og.Controller.get(monotonic_attr), 0, "Monotonic attribute reset to start") await og.Controller.evaluate() self.assertEqual(og.Controller.get(reset_attr), False, "Reset attribute still False") self.assertEqual(og.Controller.get(monotonic_attr), 1, "Monotonic attribute incremented once") await og.Controller.evaluate() self.assertEqual(og.Controller.get(monotonic_attr), 2, "Monotonic attribute incremented twice") og.Controller.set(reset_attr, True) await og.Controller.evaluate() self.assertEqual(og.Controller.get(reset_attr), False, "Reset again set back to False") self.assertEqual(og.Controller.get(monotonic_attr), 0, "Monotonic attribute again reset to start")
1,890
Python
46.274999
106
0.655026
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_omnigraph_bundles.py
""" Tests for attribute bundles """ import unittest from contextlib import suppress from typing import Any, List, Tuple import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.nodes.tests as ognts import omni.graph.tools as ogt from omni.kit.test.teamcity import is_running_in_teamcity from pxr import Gf # ============================================================================================================== def multiply_elements(multiplier, original: Any) -> Any: """Take in a numeric value, tuple, list, tuple of tuples, etc. and multiply every element by a constant""" if isinstance(original, tuple): return tuple(multiply_elements(multiplier, element) for element in original) if isinstance(original, list): return tuple(multiply_elements(multiplier, element) for element in original) return multiplier * original # ============================================================================================================== def as_tuple(value: Any) -> Tuple: """Return the value, interpreted as a tuple (except simple values, which are returned as themselves)""" if isinstance(value, tuple): return value if isinstance(value, list): return tuple(value) if isinstance(value, (Gf.Quatd, Gf.Quatf, Gf.Quath)): return (*value.GetImaginary(), value.GetReal()) if isinstance(value, Gf.Matrix4d): return tuple(tuple(element for element in list(row)) for row in value) with suppress(TypeError): if len(value) > 1: return tuple(value) return value # ============================================================================================================== class TestOmniGraphBundles(ogts.OmniGraphTestCase): """Attribute bundles do not yet have the ability to log tests directly in a .ogn file so it's done here""" # -------------------------------------------------------------------------------------------------------------- def _compare_results(self, expected_raw: Any, actual_raw: Any, test_info: str): """Loose comparison of two types of compatible values Args: expected_raw: Expected results. Can be simple values, tuples, lists, or pxr.Gf types actual_raw: Actual results. Can be simple values, tuples, lists, or pxr.Gf types test_info: String to accompany error messages Returns: Error encountered when mismatched values found, None if everything matched """ expected = as_tuple(expected_raw) actual = as_tuple(actual_raw) self.assertEqual( type(expected), type(actual), f"{test_info} Mismatched types - expected {expected_raw}, got {actual_raw}" ) if isinstance(expected, tuple): for expected_element, actual_element in zip(expected, actual): self._compare_results(expected_element, actual_element, test_info) else: self.assertEqual(expected, actual, f"{test_info} Expected {expected}, got {actual}") # ---------------------------------------------------------------------- async def _test_bundle_contents(self, node_type_to_test: str): """Test access to bundle attribute manipulation for C++ and Python implementations""" keys = og.Controller.Keys (graph, [bundle_node, inspector_node, _, _], [_, filtered_prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("BundleManipulator", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: [ ("FullPrim", {"fullInt": ("int", 2), "floatArray": ("float[]", [3.0, 4.0, 5.0])}), ( "FilteredPrim", { "int_1": ("int", 6), "uint_1": ("uint", 7), "int64_x": ("int64", 8), "uint64_1": ("uint64", 9), "int_3": ("int[3]", (10, 11, 12)), "int_array": ("int[]", [13, 14, 15]), "float_1": ("float", 3.0), "double_x": ("double", 4.0), "big_int": ("int[]", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), }, ), ], keys.EXPOSE_PRIMS: [ (og.Controller.PrimExposureType.AS_BUNDLE, "/FullPrim", "FullPrimExtract"), (og.Controller.PrimExposureType.AS_BUNDLE, "/FilteredPrim", "FilteredPrimExtract"), ], keys.CONNECT: [ ("FullPrimExtract.outputs_primBundle", "BundleManipulator.inputs:fullBundle"), ("FilteredPrimExtract.outputs_primBundle", "BundleManipulator.inputs:filteredBundle"), ("BundleManipulator.outputs_combinedBundle", "Inspector.inputs:bundle"), ], }, ) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) await og.Controller.evaluate() expected_results = { "big_int": ("int", 1, 1, "none", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), "int_1": ("int", 1, 0, "none", 6), "uint_1": ("uint", 1, 0, "none", 7), "int64_x": ("int64", 1, 0, "none", 8), "uint64_1": ("uint64", 1, 0, "none", 9), "int_3": ("int", 3, 0, "none", (10, 11, 12)), "int_array": ("int", 1, 1, "none", [13, 14, 15]), "float_1": ("float", 1, 0, "none", 3.0), "double_x": ("double", 1, 0, "none", 4.0), "fullInt": ("int", 1, 0, "none", 2), "floatArray": ("float", 1, 1, "none", [3.0, 4.0, 5.0]), "sourcePrimPath": ("token", 1, 0, "none", str(filtered_prim.GetPrimPath())), "sourcePrimType": ("token", 1, 0, "none", str(filtered_prim.GetTypeName())), } def __result_subset(elements_removed: List[str]): """Return the set of results with the index list of elements removed""" return {key: value for key, value in expected_results.items() if key not in elements_removed} # Test data consists of a list of individual test configurations with the filters to set and the # expected contents of the output bundle using those filters. test_data = [ ([], expected_results), (["x"], __result_subset(["int64_x", "double_x"])), (["int"], __result_subset(["big_int", "int_1", "uint_1", "int64_x", "uint64_1", "int_3", "int_array"])), (["big"], __result_subset(["big_int"])), ( ["x", "big", "int"], __result_subset( ["big_int", "int_1", "uint_1", "int64_x", "uint64_1", "int_3", "int_array", "double_x"] ), ), ] for (filters, expected_results) in test_data: og.Controller.edit( graph, { keys.SET_VALUES: (("inputs:filters", bundle_node), filters), }, ) await og.Controller.evaluate() try: ognts.verify_bundles_are_equal( ognts.filter_bundle_inspector_results( ognts.bundle_inspector_results(inspector_node), [], filter_for_inclusion=False ), ognts.filter_bundle_inspector_results( (len(expected_results), expected_results), [], filter_for_inclusion=False ), ) except ValueError as error: self.assertTrue(False, error) # ---------------------------------------------------------------------- async def test_bundle_contents_cpp(self): """Test access to bundle attribute manipulation on the C++ implemented node""" await self._test_bundle_contents("omni.graph.tutorials.BundleManipulation") # ---------------------------------------------------------------------- async def test_bundle_contents_py(self): """Test bundle attribute manipulation on the Python implemented node""" await self._test_bundle_contents("omni.graph.tutorials.BundleManipulationPy") # ---------------------------------------------------------------------- async def _test_simple_bundled_data(self, node_type_to_test: str): """Test access to attributes with simple data types within bundles for both C++ and Python implementations""" controller = og.Controller() keys = og.Controller.Keys prim_definition = ognts.prim_with_everything_definition() (_, [_, inspector_node, _], _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("BundledDataModifier", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: ("TestPrim", prim_definition), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "TestPrim", "TestBundle"), keys.CONNECT: [ ("TestBundle.outputs_primBundle", "BundledDataModifier.inputs:bundle"), ("BundledDataModifier.outputs_bundle", "Inspector.inputs:bundle"), ], }, ) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) await controller.evaluate() (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) # Prim will not have the "sourcePrimXX" attributes so it is smaller by 2 self.assertEqual(len(prim_definition) + 2, bundled_count) for name, (ogn_type, array_depth, tuple_count, role, actual_output) in bundled_results.items(): if name in ["sourcePrimType", "sourcePrimPath"]: continue if not node_type_to_test.endswith("Py") and ogn_type not in ["int", "int64", "uint", "uint64"]: # The C++ node only handles integer types, in the interest of brevity continue test_info = "Bundled" if tuple_count > 1: test_info += f" tuple[{tuple_count}]" if array_depth > 0: test_info += " array" test_info += f" attribute {name} of type {ogn_type}" if role != "none": test_info += f" (role {role})" if ogn_type == "token" or role == "text": expected_output = prim_definition[name][1] if isinstance(expected_output, str): expected_output += expected_output else: expected_output = [f"{element}{element}" for element in expected_output] self._compare_results(expected_output, actual_output, test_info) else: if ogn_type in ["bool", "bool[]"]: expected_output = as_tuple(prim_definition[name][1]) else: expected_output = multiply_elements(2, as_tuple(prim_definition[name][1])) self._compare_results(expected_output, actual_output, test_info) # ---------------------------------------------------------------------- async def test_simple_bundled_data_cpp(self): """Test access to attributes with simple data types within bundles on the C++ implemented node""" await self._test_simple_bundled_data("omni.graph.tutorials.BundleData") # ---------------------------------------------------------------------- async def test_simple_bundled_data_py(self): """Test access to attributes with simple data types within bundles on the Python implemented node""" await self._test_simple_bundled_data("omni.graph.tutorials.BundleDataPy") # ---------------------------------------------------------------------- async def _test_add_attributes_to_bundle(self, node_type_to_test: str): """Test basic operation of the tutorial node that adds new attributes to a bundle""" keys = og.Controller.Keys (graph, [add_node, inspector_node], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("AddAttributes", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: ("AddAttributes.outputs_bundle", "Inspector.inputs:bundle"), }, ) await og.Controller.evaluate() types_attribute = og.Controller.attribute("inputs:typesToAdd", add_node) added_names_attribute = og.Controller.attribute("inputs:addedAttributeNames", add_node) removed_names_attribute = og.Controller.attribute("inputs:removedAttributeNames", add_node) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) # List of test data configurations to run. The individual test entries consist of: # - list of the types for the attributes to be added # - list of the base types corresponding to the main types # - list of names for the attributes to be added # - list of values expected for the new bundle as (count, roles, arrayDepths, tupleCounts, values) test_data = [ [ ["float", "double", "int", "int64", "uchar", "uint", "uint64", "bool", "token"], ["float", "double", "int", "int64", "uchar", "uint", "uint64", "bool", "token"], [f"output{n}" for n in range(9)], (9, ["none"] * 9, [0] * 9, [1] * 9, [0.0, 0.0, 0, 0, 0, 0, 0, False, ""]), ], [ ["float[]", "double[]", "int[]", "int64[]", "uchar[]", "uint[]", "uint64[]", "token[]"], ["float", "double", "int", "int64", "uchar", "uint", "uint64", "token"], [f"output{n}" for n in range(8)], (8, ["none"] * 8, [1] * 8, [1] * 8, [[], [], [], [], [], [], [], []]), ], [ ["float[3]", "double[2]", "int[4]"], ["float", "double", "int"], [f"output{n}" for n in range(3)], (3, ["none"] * 3, [0] * 3, [3, 2, 4], [[0.0, 0.0, 0.0], [0.0, 0.0], [0, 0, 0, 0]]), ], [ ["float[3][]", "double[2][]", "int[4][]"], ["float", "double", "int"], [f"output{n}" for n in range(3)], (3, ["none"] * 3, [1] * 3, [3, 2, 4], [[], [], []]), ], [ ["any"], ["token"], ["output0"], (1, ["none"], [0], [1], [""]), ], [ ["colord[3]", "colorf[4]", "colorh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["color"] * 3, [0] * 3, [3, 4, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["normald[3]", "normalf[3]", "normalh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["normal"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["pointd[3]", "pointf[3]", "pointh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["point"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["quatd[4]", "quatf[4]", "quath[4]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], ( 3, ["quat"] * 3, [0] * 3, [4, 4, 4], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], ), ], [ ["texcoordd[3]", "texcoordf[2]", "texcoordh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["texcoord"] * 3, [0] * 3, [3, 2, 3], [[0.0, 0.0, 0.0], [0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["vectord[3]", "vectorf[3]", "vectorh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["vector"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["timecode"], ["double"], ["output0"], (1, ["timecode"], [0], [1], [0.0]), ], ] for (types, base_types, names, results) in test_data: og.Controller.edit( graph, { keys.SET_VALUES: [ (types_attribute, types), (added_names_attribute, names), ] }, ) await og.Controller.evaluate() (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) self.assertEqual(bundled_count, results[0]) self.assertCountEqual(list(bundled_results.keys()), names) for index, name in enumerate(names): error = f"Checking {{}} for attribute {name}" named_results = bundled_results[name] self.assertEqual( named_results[ognts.BundleResultKeys.TYPE_IDX], base_types[index], error.format("type") ) self.assertEqual( named_results[ognts.BundleResultKeys.ARRAY_DEPTH_IDX], results[2][index], error.format("array depth"), ) self.assertEqual( named_results[ognts.BundleResultKeys.TUPLE_COUNT_IDX], results[3][index], error.format("tuple count"), ) self.assertEqual( named_results[ognts.BundleResultKeys.ROLE_IDX], results[1][index], error.format("role") ) # One final test run that also includes a remove of the 2nd, 4th, and 7th attributes in the first test list (types, base_types, names, results) = test_data[0] og.Controller.edit( graph, { keys.SET_VALUES: [ (types_attribute, types), (added_names_attribute, names), (removed_names_attribute, [names[2], names[4], names[7]]), ] }, ) await og.Controller.evaluate() def pruned_list(original: List) -> List: """Remove the elements 2, 4, 7 from the list and return the result""" return [item for index, item in enumerate(original) if index not in [2, 4, 7]] (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) # Modify the expected results to account for the removed attributes self.assertEqual(bundled_count, results[0] - 3) names_expected = pruned_list(names) base_types_expected = pruned_list(base_types) array_depths_expected = pruned_list(results[2]) tuple_counts_expected = pruned_list(results[3]) roles_expected = pruned_list(results[1]) self.assertCountEqual(list(bundled_results.keys()), names_expected) for index, name in enumerate(names_expected): error = f"Checking {{}} for attribute {name}" named_results = bundled_results[name] self.assertEqual( named_results[ognts.BundleResultKeys.TYPE_IDX], base_types_expected[index], error.format("type") ) self.assertEqual( named_results[ognts.BundleResultKeys.ARRAY_DEPTH_IDX], array_depths_expected[index], error.format("array depth"), ) self.assertEqual( named_results[ognts.BundleResultKeys.TUPLE_COUNT_IDX], tuple_counts_expected[index], error.format("tuple count"), ) self.assertEqual( named_results[ognts.BundleResultKeys.ROLE_IDX], roles_expected[index], error.format("role") ) # ---------------------------------------------------------------------- async def test_add_attributes_to_bundle_cpp(self): """Test adding attributes to bundles on the C++ implemented node""" await self._test_add_attributes_to_bundle("omni.graph.tutorials.BundleAddAttributes") # ---------------------------------------------------------------------- async def test_add_attributes_to_bundle_py(self): """Test adding attributes to bundles on the Python implemented node""" await self._test_add_attributes_to_bundle("omni.graph.tutorials.BundleAddAttributesPy") # ---------------------------------------------------------------------- async def _test_batched_add_attributes_to_bundle(self, node_type_to_test: str): """Test basic operation of the tutorial node that adds new attributes to a bundle""" keys = og.Controller.Keys (graph, [add_node, inspector_node], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("AddAttributes", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: ("AddAttributes.outputs_bundle", "Inspector.inputs:bundle"), }, ) await og.Controller.evaluate() types_attribute = og.Controller.attribute("inputs:typesToAdd", add_node) added_names_attribute = og.Controller.attribute("inputs:addedAttributeNames", add_node) removed_names_attribute = og.Controller.attribute("inputs:removedAttributeNames", add_node) batched_api_attribute = og.Controller.attribute("inputs:useBatchedAPI", add_node) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) # List of test data configurations to run. The individual test entries consist of: # - list of the types for the attributes to be added # - list of the base types corresponding to the main types # - list of names for the attributes to be added # - list of values expected for the new bundle as (count, roles, arrayDepths, tupleCounts, values) test_data = [ [ ["float", "double", "int", "int64", "uchar", "uint", "uint64", "bool", "token"], ["float", "double", "int", "int64", "uchar", "uint", "uint64", "bool", "token"], [f"output{n}" for n in range(9)], (9, ["none"] * 9, [0] * 9, [1] * 9, [0.0, 0.0, 0, 0, 0, 0, 0, False, ""]), ], [ ["float[]", "double[]", "int[]", "int64[]", "uchar[]", "uint[]", "uint64[]", "token[]"], ["float", "double", "int", "int64", "uchar", "uint", "uint64", "token"], [f"output{n}" for n in range(8)], (8, ["none"] * 8, [1] * 8, [1] * 8, [[], [], [], [], [], [], [], []]), ], [ ["float[3]", "double[2]", "int[4]"], ["float", "double", "int"], [f"output{n}" for n in range(3)], (3, ["none"] * 3, [0] * 3, [3, 2, 4], [[0.0, 0.0, 0.0], [0.0, 0.0], [0, 0, 0, 0]]), ], [ ["float[3][]", "double[2][]", "int[4][]"], ["float", "double", "int"], [f"output{n}" for n in range(3)], (3, ["none"] * 3, [1] * 3, [3, 2, 4], [[], [], []]), ], [ ["any"], ["token"], ["output0"], (1, ["none"], [0], [1], [""]), ], [ ["colord[3]", "colorf[4]", "colorh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["color"] * 3, [0] * 3, [3, 4, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["normald[3]", "normalf[3]", "normalh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["normal"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["pointd[3]", "pointf[3]", "pointh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["point"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["quatd[4]", "quatf[4]", "quath[4]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], ( 3, ["quat"] * 3, [0] * 3, [4, 4, 4], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], ), ], [ ["texcoordd[3]", "texcoordf[2]", "texcoordh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["texcoord"] * 3, [0] * 3, [3, 2, 3], [[0.0, 0.0, 0.0], [0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["vectord[3]", "vectorf[3]", "vectorh[3]"], ["double", "float", "half"], [f"output{n}" for n in range(3)], (3, ["vector"] * 3, [0] * 3, [3, 3, 3], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ], [ ["timecode"], ["double"], ["output0"], (1, ["timecode"], [0], [1], [0.0]), ], ] for (types, base_types, names, results) in test_data: og.Controller.edit( graph, { keys.SET_VALUES: [ (types_attribute, types), (added_names_attribute, names), (batched_api_attribute, True), ] }, ) await og.Controller.evaluate() (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) self.assertEqual(bundled_count, results[0]) self.assertCountEqual(list(bundled_results.keys()), names) for index, name in enumerate(names): error = f"Checking {{}} for attribute {name}" named_results = bundled_results[name] self.assertEqual( named_results[ognts.BundleResultKeys.TYPE_IDX], base_types[index], error.format("type") ) self.assertEqual( named_results[ognts.BundleResultKeys.ARRAY_DEPTH_IDX], results[2][index], error.format("array depth"), ) self.assertEqual( named_results[ognts.BundleResultKeys.TUPLE_COUNT_IDX], results[3][index], error.format("tuple count"), ) self.assertEqual( named_results[ognts.BundleResultKeys.ROLE_IDX], results[1][index], error.format("role") ) # One final test run that also includes a remove of the 2nd, 4th, and 7th attributes in the first test list (types, base_types, names, results) = test_data[0] og.Controller.edit( graph, { keys.SET_VALUES: [ (types_attribute, types), (added_names_attribute, names), (removed_names_attribute, [names[2], names[4], names[7]]), ] }, ) await og.Controller.evaluate() def pruned_list(original: List) -> List: """Remove the elements 2, 4, 7 from the list and return the result""" return [item for index, item in enumerate(original) if index not in [2, 4, 7]] await og.Controller.evaluate() (bundled_count, bundled_results) = ognts.bundle_inspector_results(inspector_node) self.assertEqual(bundled_count, results[0] - 3) # Modify the expected results to account for the removed attributes names_expected = pruned_list(names) base_types_expected = pruned_list(base_types) array_depths_expected = pruned_list(results[2]) tuple_counts_expected = pruned_list(results[3]) roles_expected = pruned_list(results[1]) self.assertCountEqual(list(bundled_results.keys()), names_expected) for index, name in enumerate(names_expected): error = f"Checking {{}} for attribute {name}" named_results = bundled_results[name] self.assertEqual( named_results[ognts.BundleResultKeys.TYPE_IDX], base_types_expected[index], error.format("type") ) self.assertEqual( named_results[ognts.BundleResultKeys.ARRAY_DEPTH_IDX], array_depths_expected[index], error.format("array depth"), ) self.assertEqual( named_results[ognts.BundleResultKeys.TUPLE_COUNT_IDX], tuple_counts_expected[index], error.format("tuple count"), ) self.assertEqual( named_results[ognts.BundleResultKeys.ROLE_IDX], roles_expected[index], error.format("role") ) # ---------------------------------------------------------------------- async def test_batched_add_attributes_to_bundle_cpp(self): """Test adding attributes to bundles on the C++ implemented node""" await self._test_batched_add_attributes_to_bundle("omni.graph.tutorials.BundleAddAttributes") # ---------------------------------------------------------------------- async def test_batched_add_attributes_to_bundle_py(self): """Test adding attributes to bundles on the Python implemented node""" await self._test_batched_add_attributes_to_bundle("omni.graph.tutorials.BundleAddAttributesPy") # ---------------------------------------------------------------------- async def _test_bundle_gpu(self, node_type_to_test: str): """Test basic operation of the tutorial node that accesses bundle data on the GPU""" controller = og.Controller() keys = og.Controller.Keys (graph, (bundle_node, inspector_node), _, _) = controller.edit( "/TestGraph", { keys.CREATE_PRIMS: [ ("Prim1", {"points": ("pointf[3][]", [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])}), ("Prim2", {"points": ("pointf[3][]", [[4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])}), ], keys.CREATE_NODES: [ ("GpuBundleNode", node_type_to_test), ("Inspector", "omni.graph.nodes.BundleInspector"), ], }, ) controller.edit( graph, { keys.EXPOSE_PRIMS: [ (og.GraphController.PrimExposureType.AS_BUNDLE, "Prim1", "Prim1Extract"), (og.GraphController.PrimExposureType.AS_BUNDLE, "Prim2", "Prim2Extract"), ], keys.CONNECT: [ ("Prim1Extract.outputs_primBundle", "GpuBundleNode.inputs:cpuBundle"), ("Prim2Extract.outputs_primBundle", "GpuBundleNode.inputs:gpuBundle"), ("GpuBundleNode.outputs_cpuGpuBundle", "Inspector.inputs:bundle"), ], }, ) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) await controller.evaluate(graph) for gpu in [False, True]: controller.attribute("inputs:gpu", bundle_node, graph).set(gpu) await controller.evaluate() (_, bundled_values) = ognts.bundle_inspector_results(inspector_node) self.assertEqual(bundled_values["dotProducts"][ognts.BundleResultKeys.VALUE_IDX], [32.0, 122.0]) # ---------------------------------------------------------------------- async def test_bundle_gpu_cpp(self): """Test access to bundle contents on GPU on the C++ implemented node""" await self._test_bundle_gpu("omni.graph.tutorials.CpuGpuBundles") # ---------------------------------------------------------------------- async def test_bundle_gpu_py(self): """Test bundle contents on GPU on the Python implemented node""" await self._test_bundle_gpu("omni.graph.tutorials.CpuGpuBundlesPy") # ---------------------------------------------------------------------- @unittest.skipIf(is_running_in_teamcity(), "This is a manual test so it only needs to run locally") async def test_cuda_pointers_py(self): """Run a simple test on a node that extracts CUDA pointers from the GPU. Inspect the output for information""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, inspector_node), _, _) = controller.edit( "/TestGraph", { keys.CREATE_PRIMS: [ ("Prim1", {"points": ("float[3][]", [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])}), ], keys.CREATE_NODES: [ ("GpuBundleNode", "omni.graph.tutorials.CudaCpuArraysPy"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], }, ) controller.edit( graph, { keys.EXPOSE_PRIMS: [ (og.GraphController.PrimExposureType.AS_ATTRIBUTES, "Prim1", "Prim1Extract"), ], }, ) _ = ogt.OGN_DEBUG and ognts.enable_debugging(inspector_node) await controller.evaluate(graph) controller.edit( graph, { keys.CONNECT: [ ("Prim1Extract.outputs:points", "GpuBundleNode.inputs:points"), ("GpuBundleNode.outputs_outBundle", "Inspector.inputs:bundle"), ], }, )
34,927
Python
45.632844
118
0.474361
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/tests/test_omnigraph_metadata.py
"""Basic tests of the metadata bindings found in OmniGraphBindingsPython.cpp""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools.ogn as ogn # ====================================================================== class TestOmniGraphMetadata(ogts.OmniGraphTestCase): """Encapsulate simple tests that exercise metadata access""" # ---------------------------------------------------------------------- def __node_type_metadata_test(self, node_type: og.NodeType): """Test a node type object for metadata access""" original_count = node_type.get_metadata_count() key = "_node_type_metadata" value = "_test_value" node_type.set_metadata(key, value) # The new metadata key should now have the new value self.assertEqual(value, node_type.get_metadata(key)) new_metadata = node_type.get_all_metadata() # The new key/value pair should now be part of the entire metadata listt self.assertTrue(key in new_metadata) self.assertEqual(value, new_metadata[key]) # Since a unique key was chosen there should be one extra metadata value self.assertEqual(original_count + 1, node_type.get_metadata_count()) # Setting a value to None should remove the metadata from the node type. # Do this last so that the test can run multiple times successfully. node_type.set_metadata(key, None) self.assertEqual(original_count, node_type.get_metadata_count()) # Test silent success of trying to set the metadata to illegal data node_type.set_metadata(None, value) # Verify the hardcoded metadata type names self.assertTrue(ogn.MetadataKeys.UI_NAME in new_metadata) self.assertTrue(ogn.MetadataKeys.TAGS in new_metadata) self.assertEqual("Tutorial Node: Tuple Attributes", new_metadata[ogn.MetadataKeys.UI_NAME]) self.assertEqual("tuple,tutorial,internal", new_metadata[ogn.MetadataKeys.TAGS]) # ---------------------------------------------------------------------- async def test_node_type_metadata(self): """Test metadata features in the NodeType class""" # The TupleData tutorial node happens to have special metadata types defined node_type = og.get_node_type("omni.tutorials.TupleData") self.assertIsNotNone(node_type, "Empty node type to be used for test was not registered") self.__node_type_metadata_test(node_type) # ---------------------------------------------------------------------- async def test_node_metadata(self): """Test metadata access through the node class""" # The TupleData tutorial node happens to have special metadata types defined (_, [test_node], _, _) = og.Controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: ("TupleNode", "omni.tutorials.TupleData"), }, ) await og.Controller.evaluate() self.__node_type_metadata_test(test_node.get_node_type()) # ---------------------------------------------------------------------- async def test_attribute_metadata(self): """Test metadata features in the NodeType class""" # Any node type will do for metadata tests so use a simple one (_, [test_node], _, _) = og.Controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: ("SimpleNode", "omni.graph.tutorials.SimpleData"), }, ) await og.Controller.evaluate() self.assertIsNotNone(test_node, "Simple data node type to be used for test was not registered") test_attribute = test_node.get_attribute("inputs:a_bool") self.assertIsNotNone(test_attribute, "Boolean input on simple data node type not found") original_count = test_attribute.get_metadata_count() key = "_test_attribute_metadata" value = "_test_value" test_attribute.set_metadata(key, value) # The new metadata key should now have the new value self.assertEqual(value, test_attribute.get_metadata(key)) new_metadata = test_attribute.get_all_metadata() # The new key/value pair should now be part of the entire metadata listt self.assertTrue(key in new_metadata) self.assertEqual(value, new_metadata[key]) # Since a unique key was chosen there should be one extra metadata value self.assertEqual(original_count + 1, test_attribute.get_metadata_count()) # Setting a value to None should remove the metadata from the node type. # Do this last so that the test can run multiple times successfully. test_attribute.set_metadata(key, None) self.assertEqual(original_count, test_attribute.get_metadata_count()) # Test silent success of trying to set the metadata to illegal data test_attribute.set_metadata(None, value) # ObjectId types get special metadata hardcoded for attribute_name in ["inputs:a_objectId", "outputs:a_objectId"]: object_id_attribute = test_node.get_attribute(attribute_name) self.assertIsNotNone(object_id_attribute, f"ObjectId {attribute_name} on simple data node type not found") object_id_metadata = object_id_attribute.get_all_metadata() self.assertTrue(ogn.MetadataKeys.OBJECT_ID in object_id_metadata) # Check on the constant attribute constant_attribute = test_node.get_attribute("inputs:a_constant_input") self.assertEqual("1", constant_attribute.get_metadata(ogn.MetadataKeys.OUTPUT_ONLY))
5,658
Python
49.079646
118
0.627253
omniverse-code/kit/exts/omni.graph.tutorials/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.3.3] - 2022-08-31 ### Fixed - Refactored out use of a deprecated class ## [1.3.2] - 2022-08-30 ### Fixed - Doc error referencing a Python node in a C++ node docs ## [1.3.1] - 2022-08-09 ### Fixed - Applied formatting to all of the Python files ## [1.3.0] - 2022-07-07 ### Changed - Refactored imports from omni.graph.tools to get the new locations ### Added - Test for public API consistency ## [1.2.0] - 2022-05-06 ### Changed - Updated the CPU to GPU test to show the actual pointer contents ## [1.1.3] - 2022-04-29 ### Changed - Made tests derive from OmniGraphTestCase ## [1.1.2] - 2022-03-07 ### Changed - Substituted old tutorial 1 node icons with new version ## [1.1.1] - 2022-03-01 ### Fixed - Made bundle tests use the Controller ## [1.0.0] - 2021-03-01 ### Initial Version - Started changelog with initial released version of the OmniGraph core
1,138
Markdown
23.760869
87
0.692443
omniverse-code/kit/exts/omni.graph.tutorials/docs/README.md
# OmniGraph Tutorials [omni.graph.tutorials] Sets of nodes that provide tutorials on the construction of OmniGraph nodes, with an emphasis on the use of the OmniGraph node description files (*.ogn).
200
Markdown
39.199992
107
0.795
omniverse-code/kit/exts/omni.graph.tutorials/docs/index.rst
.. _ogn_tutorial_nodes: OmniGraph Walkthrough Tutorials ############################### .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension**: omni.graph.tutorials,**Documentation Generated**: |today| .. toctree:: :maxdepth: 1 CHANGELOG In the source tree are several tutorials. Enclosed in these tutorial files are curated nodes that implement a representative portion of the available features in an OmniGraph Node interface. By working through these tutorials you can gradually build up a knowledge of the concepts used to effectively write OmniGraph Nodes. .. note:: In the tutorial files irrelevant details such as the copyright notice are omitted for clarity .. toctree:: :maxdepth: 1 :glob: ../tutorials/conversionTutorial/* ../tutorials/extensionTutorial/* ../tutorials/tutorial1/* ../tutorials/tutorial2/* ../tutorials/tutorial3/* ../tutorials/tutorial4/* ../tutorials/tutorial5/* ../tutorials/tutorial6/* ../tutorials/tutorial7/* ../tutorials/tutorial8/* ../tutorials/tutorial9/* ../tutorials/tutorial10/* ../tutorials/tutorial11/* ../tutorials/tutorial12/* ../tutorials/tutorial13/* ../tutorials/tutorial14/* ../tutorials/tutorial15/* ../tutorials/tutorial16/* ../tutorials/tutorial17/* ../tutorials/tutorial18/* ../tutorials/tutorial19/* ../tutorials/tutorial20/* ../tutorials/tutorial21/* ../tutorials/tutorial22/* ../tutorials/tutorial23/* ../tutorials/tutorial24/* ../tutorials/tutorial25/* ../tutorials/tutorial26/* ../tutorials/tutorial27/*
1,588
reStructuredText
26.396551
115
0.684509
omniverse-code/kit/exts/omni.audiorecorder/config/extension.toml
[package] title = "Kit Audio Recorder" category = "Audio" feature = true version = "0.1.0" description = "An audio recorder API which is available from python and C++" detailedDescription = """This is a simple interface that can be used to record audio to file or send recorded audio to a callback for generic audio recording tasks. This recorder can achieve a relatively low latency (e.g. 20ms). This API is available in python and C++. See omni.kit.window.audiorecorder for an example use of this API. """ authors = ["NVIDIA"] keywords = ["audio", "capture", "recording"] [dependencies] "carb.audio" = {} "omni.usd.libs" = {} "omni.usd.schema.semantics" = {} "omni.usd.schema.audio" = {} "omni.kit.audiodeviceenum" = {} [[native.plugin]] path = "bin/*.plugin" [[python.module]] name = "omni.audiorecorder" [[test]] args = [ "--/audio/deviceBackend=null" ] dependencies = [ "omni.usd", "omni.kit.test_helpers_gfx", ] stdoutFailPatterns.exclude = [ "*failed to create an encoder state*", "*failed to initialize the output stream*", "*recording is already in progress*", "*no supported conversion path from ePcmFloat (4) to eRaw (10)*", ] # uncomment and re-open OM-50069 if it breaks again #pythonTests.unreliable = [ # "*test_callback_recording", # OM-50069 #]
1,302
TOML
23.584905
78
0.690476
omniverse-code/kit/exts/omni.audiorecorder/omni/audiorecorder/__init__.py
""" This module contains bindings to the C++ omni::audio::IAudioRecorder interface. This provides functionality for simple audio recording to file or using a callback. Recording can be done in 16 bit, 32 bit or float PCM if a callback is required. Recording can be done in any format when only recording to a file. Recording to a file while simultaneously receiving data callbacks is also possible. """ # recorder bindings depend on some types from carb.audio import carb.audio from ._audiorecorder import *
550
Python
41.384612
91
0.732727
omniverse-code/kit/exts/omni.audiorecorder/omni/audiorecorder/tests/__init__.py
from .test_audio_recorder import * # pragma: no cover
56
Python
17.999994
54
0.714286
omniverse-code/kit/exts/omni.audiorecorder/omni/audiorecorder/tests/test_audio_recorder.py
import pathlib import time import os import math from PIL import Image import omni.kit.test_helpers_gfx.compare_utils import carb.tokens import carb.audio import omni.audiorecorder import omni.usd.audio import omni.kit.audiodeviceenum import omni.kit.test import omni.log OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path()) # boilerplate to work around python lacking references class IntReference: # pragma: no cover def __init__(self, v): self._v = v; def _get_value(self): return self._v def _set_value(self, v): self._v = v value = property(_get_value, _set_value) def wait_for_data(received: IntReference, ms: int, expected_data: int): # pragma: no cover for i in range(ms): if received.value > expected_data: # log this so we can see timing margins on teamcity omni.log.warn("finished waiting after " + str(i / 1000.0) + " seconds") break if i > 0 and i % 1000 == 0: omni.log.warn("waited " + str(i // 1000) + " seconds") if i == ms - 1: self.assertTrue(not "timeout of " + str(ms) + "ms waiting for " + str(expected_data) + " frames") time.sleep(0.001) class TestAudioRecorder(omni.kit.test.AsyncTestCase): # pragma: no cover def setUp(self): self._recorder = omni.audiorecorder.create_audio_recorder() self.assertIsNotNone(self._recorder) extension_path = carb.tokens.get_tokens_interface().resolve("${omni.audiorecorder}") self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute() self._golden_path = self._test_path.joinpath("golden") def tearDown(self): self._recorder = None def test_callback_recording(self): valid = [] for i in range(1, 16): valid.append(4800 * i) received = IntReference(0) def read_validation(data): nonlocal received received.value += len(data) self.assertTrue(len(data) in valid) def float_read_callback(data): read_validation(data) self.assertTrue(isinstance(data[0], float)) def int_read_callback(data): read_validation(data) self.assertTrue(isinstance(data[0], int)) # if there are no devices, this won't work if omni.kit.audiodeviceenum.acquire_audio_device_enum_interface().get_device_count(omni.kit.audiodeviceenum.Direction.CAPTURE) == 0: self.assertFalse(self._recorder.begin_recording_float( callback = float_read_callback, )) return # not open => should be some valid default format fmt = self._recorder.get_format() self.assertIsNotNone(fmt) self.assertGreaterEqual(fmt.channels, carb.audio.MIN_CHANNELS) self.assertLessEqual(fmt.channels, carb.audio.MAX_CHANNELS) self.assertGreaterEqual(fmt.frame_rate, carb.audio.MIN_FRAMERATE) self.assertLessEqual(fmt.frame_rate, carb.audio.MAX_FRAMERATE) self.assertTrue(self._recorder.begin_recording_float( callback = float_read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES, channels = 1 )) # try again and it will fail because a recording is already in progress self.assertFalse(self._recorder.begin_recording_float( callback = float_read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES, channels = 1 )) # not much we can test here aside from it being valid fmt = self._recorder.get_format() self.assertIsNotNone(fmt) self.assertEqual(fmt.channels, 1) self.assertGreaterEqual(fmt.frame_rate, carb.audio.MIN_FRAMERATE) self.assertLessEqual(fmt.frame_rate, carb.audio.MAX_FRAMERATE) self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM_FLOAT) # this timeout seems absurd, but anything's possible with teamcity's timing wait_for_data(received, 8000, 4800) self._recorder.stop_recording() # try again with int16 received.value = 0 self.assertTrue(self._recorder.begin_recording_int16( callback = int_read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES, channels = 1 )) # not much we can test here aside from it being valid fmt = self._recorder.get_format() self.assertIsNotNone(fmt) self.assertEqual(fmt.channels, 1) self.assertGreaterEqual(fmt.frame_rate, carb.audio.MIN_FRAMERATE) self.assertLessEqual(fmt.frame_rate, carb.audio.MAX_FRAMERATE) self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM16) wait_for_data(received, 8000, 4800) self._recorder.stop_recording() # try again with int32 received.value = 0 self.assertTrue(self._recorder.begin_recording_int32( callback = int_read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES, channels = 1 )) # not much we can test here aside from it being valid fmt = self._recorder.get_format() self.assertIsNotNone(fmt) self.assertEqual(fmt.channels, 1) self.assertGreaterEqual(fmt.frame_rate, carb.audio.MIN_FRAMERATE) self.assertLessEqual(fmt.frame_rate, carb.audio.MAX_FRAMERATE) self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM32) wait_for_data(received, 8000, 4800) self._recorder.stop_recording() # test that the format is set as specified self.assertTrue(self._recorder.begin_recording_float( callback = float_read_callback, channels = 1, # 1 channel because that's all we can guarantee # when we upgrade IAudioCapture, this should no longer # be an issue frame_rate = 43217, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, length_type = carb.audio.UnitType.FRAMES )) fmt = self._recorder.get_format() self.assertEqual(fmt.channels, 1) self.assertEqual(fmt.frame_rate, 43217) self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM_FLOAT) self._recorder.stop_recording() def _validate_sound(self, path): # to validate that this is a working sound, load it into a sound prim # and check if the sound asset loaded successfully context = omni.usd.get_context() self.assertIsNotNone(context) context.new_stage() stage = context.get_stage() self.assertIsNotNone(stage) prim = stage.DefinePrim("/sound", "OmniSound") self.assertIsNotNone(prim) prim.GetAttribute("filePath").Set(path) audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(audio) i = 0 while audio.get_sound_asset_status(prim) == omni.usd.audio.AssetLoadStatus.IN_PROGRESS: time.sleep(0.001) if i > 5000: raise Exception("asset load timed out") i += 1 self.assertEqual(audio.get_sound_asset_status(prim), omni.usd.audio.AssetLoadStatus.DONE) def test_recording_to_file(self): received = IntReference(0) def read_callback(data): nonlocal received received.value += len(data) if omni.kit.audiodeviceenum.acquire_audio_device_enum_interface().get_device_count(omni.kit.audiodeviceenum.Direction.CAPTURE) == 0: self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, filename = str(OUTPUTS_DIR.joinpath("test.oga")) )) self.assertFalse(self._recorder.begin_recording_to_file( filename = str(OUTPUTS_DIR.joinpath("test.oga")) )) return self.assertTrue(self._recorder.begin_recording_float( callback = read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, channels = 1, frame_rate = 48000, length_type = carb.audio.UnitType.FRAMES, output_format = carb.audio.SampleFormat.OPUS, filename = str(OUTPUTS_DIR.joinpath("test.opus.oga")) )) wait_for_data(received, 8000, 4800) self._recorder.stop_recording() self._validate_sound(str(OUTPUTS_DIR.joinpath("test.opus.oga"))) # try again with a default output format self.assertTrue(self._recorder.begin_recording_float( callback = read_callback, buffer_length = 4800 * 16, # enormous buffer for test reliability period = 4800, channels = 1, frame_rate = 48000, length_type = carb.audio.UnitType.FRAMES, filename = str(OUTPUTS_DIR.joinpath("test.default.0.wav")) )) wait_for_data(received, 8000, 4800) self._recorder.stop_recording() self._validate_sound(str(OUTPUTS_DIR.joinpath("test.default.0.wav"))) self.assertTrue(self._recorder.begin_recording_to_file( frame_rate = 73172, channels = 1, filename = str(OUTPUTS_DIR.joinpath("test.vorbis.oga")), output_format = carb.audio.SampleFormat.VORBIS )) time.sleep(2.0) self._recorder.stop_recording() self._validate_sound(str(OUTPUTS_DIR.joinpath("test.vorbis.oga"))) # try again with a default output format self.assertTrue(self._recorder.begin_recording_to_file( frame_rate = 73172, channels = 1, filename = str(OUTPUTS_DIR.joinpath("test.default.1.wav")), )) time.sleep(2.0) self._recorder.stop_recording() self._validate_sound(str(OUTPUTS_DIR.joinpath("test.default.1.wav"))) def test_bad_parameters(self): def read_callback(data): pass # MP3 is not supported self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, output_format = carb.audio.SampleFormat.MP3, filename = str(OUTPUTS_DIR.joinpath("test.mp3")) )) # bad format self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, output_format = carb.audio.SampleFormat.RAW, filename = str(OUTPUTS_DIR.joinpath("test.mp3")) )) # bad file name self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, output_format = carb.audio.SampleFormat.OPUS, filename = "a/b/c/d/e/f/g/h/i/j.oga" )) self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, channels = carb.audio.MAX_CHANNELS + 1 )) self.assertFalse(self._recorder.begin_recording_float( callback = read_callback, frame_rate = carb.audio.MAX_FRAMERATE + 1 )) def test_draw_waveform(self): # toggle in case you want to regenerate waveforms GENERATE_GOLDEN_IMAGES = False samples_int16 = [] samples_int32 = [] samples_float = [] for i in range(4800): samples_float.append(math.sin(i / 48.0)) samples_int16.append(int(samples_float[-1] * (2 ** 15 - 1))) samples_int32.append(int(samples_float[-1] * (2 ** 31 - 1))) W = 256 H = 256 raw = omni.audiorecorder.draw_waveform_from_blob_float(samples_float, 1, W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath("waveform.float.png"))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath("waveform.float.png"), self._golden_path.joinpath("waveform.png"), pathlib.Path(OUTPUTS_DIR).joinpath("waveform.float.png.diff.png")), 0.1) raw = omni.audiorecorder.draw_waveform_from_blob_int32(samples_int32, 1, W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int32.png"))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int32.png"), self._golden_path.joinpath("waveform.png"), pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int32.png.diff.png")), 0.1) raw = omni.audiorecorder.draw_waveform_from_blob_int16(samples_int16, 1, W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int16.png"))) if not GENERATE_GOLDEN_IMAGES: # 1 pixel of difference was 756.0 difference self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int16.png"), self._golden_path.joinpath("waveform.png"), pathlib.Path(OUTPUTS_DIR).joinpath("waveform.int16.png.diff.png")), 1024.0)
14,313
Python
36.276042
140
0.604066
omniverse-code/kit/exts/omni.graph.tools/config/extension.toml
[package] title = "OmniGraph Tools" # Note that for this extension the semantic versioning is interpreted slightly differently as it has to be concerned # with the public Python API, the content of the generated code, and the .ogn format. Ordinarily the versioning of the # generated code would be handled by a dependency on a particular version of omni.graph/omni.graph.core, however as # this extension cannot see them the dependency has to be managed manually. # # MAJOR VERSION: Changes are made to the generated code, OGN format, or the public API that are not backward compatible. # i.e. the user has to change some of their code to make it work with the new version # # MINOR VERSION: 1. A change is made to the Python API that is backward compatible with no user changes # 2. A change is made to the .ogn format that is backward compatible with no user changes # 3. A change is made that would require regeneration of the Python node database at runtime in order # to ensure backward compatibility, but with no user changes required to the .ogn or node files. # e.g. extra runtime information is added to the database # # PATCH VERSION: 1. A change is made to the implementation of the Python API that does not change functionality # 2. A change is made to the .ogn parsing that does not change the generated code # version = "1.17.2" category = "Graph" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" description = "Contains the implementation of the Omniverse Graph node generator scripts." repository = "" keywords = ["kit", "omnigraph", "tools"] authors = ["NVIDIA"] # The tools are used for the build and so have no dependencies [dependencies] "omni.usd.libs" = {} "omni.kit.pip_archive" = {} # For AutoNode - to be removed after the deprecation support is removed from omni.graph.tools/python/_impl/v1_2_0/autograph [python.pipapi] requirements = [ "numpy", # SWIPAT filed under: http://nvbugs/3193231 "toml", # SWIPAT filed under: http://nvbugs/3060676 ] # Main python module this extension provides, it will be publicly available as "import omni.graph.tools". [[python.module]] name = "omni.graph.tools" [documentation] deps = [ ["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph.tutorial/etc refs until that workflow is moved ] pages = [ "docs/Overview.md", "docs/node_architects_guide.rst", "docs/ogn_user_guide.rst", "docs/ogn_reference_guide.rst", "docs/attribute_types.rst", "docs/ogn_code_samples_cpp.rst", "docs/ogn_code_samples_python.rst", "docs/ogn_generation_script.rst", "docs/CHANGELOG.md", ]
2,726
TOML
44.449999
123
0.70653
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/ensure_node_types_in_toml.py
""" Given a collection of node metadata, ensure that all nodes appear in the [omnigraph.node_types] section of the extension.toml used by the owning extension to register its information. Invoke this script by passing the location of the .json file containing the metadata for all node types and the location of the extension.toml file to which the metadata should be populated. python ensure_node_types_in_toml.py --nodeInfo $BUILD/exts/omni.my.extension/ogn/nodes.json --toml $SRC/extensions/omni.my.extension/config/extension.toml The extension.toml file will be modified to included a generated section with this format: # === GENERATED BY ensure_node_types_in_toml.py -- DO NOT MODIFY === [omnigraph.node_types] "omni.my.extension.MyNodeType" = 1 "omni.my.extension.MyOtherNodeType" = 1 # === END OF GENERATED CODE === or if the "--allData" flag is set then this more verbose format will be used: # === GENERATED BY ensure_node_types_in_toml.py -- DO NOT MODIFY === [omnigraph.node_types."omni.my.extension.MyNodeType"] version = 1 language = "C++" description = "This is my node" [omnigraph.node_types."omni.my.extension.MyOtherNodeType"] version = 1 language = "C++" description = "This is my other node" # === END OF GENERATED CODE === Note that this script explicitly does not handle the case of multiple versions of the same node type in the same extension as that is also not handled by OmniGraph proper. You might also want to use an intermediate directory, which will create an explicit tag when the .toml is regenerated so that you can safely handle the case of regeneration after a direct edit of the .toml file itself. This will ensure that a user cannot accidentally delete a node definition from the automatically generated section; python ensure_node_types_in_toml.py --nodeInfo $BUILD/exts/omni.my.extension/ogn/nodes.json --toml $SRC/extensions/omni.my.extension/config/extension.toml --intermediate $TOP/_build/intermediate Lastly, the support for the toml package is only available through repo_man in the build, not in the standard path. You can pass in the root directory of the repo_man module if it is needed to find the toml package. python ensure_node_types_in_toml.py --nodeInfo $BUILD/exts/omni.my.extension/ogn/nodes.json --toml $SRC/extensions/omni.my.extension/config/extension.toml --intermediate $TOP/_build/intermediate --repoMan $TOP/_repo/deps/repo_man """ import argparse import json import logging import os import sys from pathlib import Path from node_generator.utils import WritableDir # Create a logger and selectively turn on logging if the OGN debugging environment variable is set logger = logging.getLogger("add_nodes_to_toml") logging_handler = logging.StreamHandler(sys.stdout) logging_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s")) logger.addHandler(logging_handler) logger.setLevel(logging.INFO if os.getenv("OGN_PARSE_DEBUG") else logging.WARN) START_MARKER = "# === GENERATED BY ensure_node_types_in_toml.py -- DO NOT MODIFY ===" """Special marker text identifying the start of the generated node type identifier code""" SECTION_NAME = "omnigraph.node_types" """Name of the generated section of the .toml file""" END_MARKER = "# === END OF GENERATED CODE ===" """Special marker text identifying the end of the generated node type identifier code""" # ====================================================================== class TomlModifier: """Encapsulates the reading, modifying, and writing of the .toml file with the node information Attributes: changes_made: True iff processing the .toml file resulted in changes to it toml: The toml module root - a member of the class because it may need to be imported from an alternate location Internal Attributes: __all_data: If True then the .toml will include language and description in addition to type name and version __existing_types: Dictionary of node_type_name:version_number for node types found in the original .toml file __node_info: Dictionary of node_type_name:node_type_info generated by the build for this extension __node_info_path: Path pointing to the generated file containing the node type information for this extension __tag_path: Path pointing to a file to use to tag the operation as complete (so that edits to the .toml can trigger regeneration) __toml_path: Path pointing to the .toml file to be modified """ # -------------------------------------------------------------------------------------------------------------- def __init__(self): """Set up the information required for the operations - do nothing just yet""" # Construct the parsing information. Run the script with "--help" to see the usage. parser = argparse.ArgumentParser( description="Ensure that the supplied .toml file contains metadata for all of the nodes defined" " in the extension", formatter_class=argparse.RawTextHelpFormatter, ) parser.add_argument( "-a", "--allData", action="store_true", help="Dump all metadata to the .toml file instead of just the version and node type name", ) parser.add_argument( "-in", "--intermediate", action=WritableDir, const=None, type=Path, metavar="INTERMEDIATE_DIRECTORY", help="Directory into which temporary build information is stored", ) parser.add_argument( "-ni", "--nodeInfoFile", type=Path, metavar="NODE_INFO_FILE.json", help=".json file generated by the build that contains the registration information for all of the nodes", ) parser.add_argument( "-rm", "--repoMan", type=Path, metavar="REPO_MAN_DIR", help="Path to the repo_man support directory", ) parser.add_argument( "-t", "--tomlFile", type=Path, metavar="TOML_FILE", help=".toml file that will contain the node information", ) parser.add_argument("-v", "--verbose", action="store_true", help="Output the steps the script is performing") args = parser.parse_args() # If the script steps are to be echoed enable the logger and dump the script arguments as a first step if args.verbose: logger.setLevel(logging.DEBUG) logger.info("Processing the arguments") logger.info(" Args = %s", args) # Set up the internal attributes. All path files are resolved to absolute paths for convenience. self.__all_data = args.allData self.__toml_path = args.tomlFile.resolve() self.__node_info_path = args.nodeInfoFile.resolve() self.__tag_path = args.intermediate / "extension.toml.built" if args.intermediate is not None else None if self.__tag_path is not None: self.__tag_path = self.__tag_path.resolve() self.changes_made = False self.__in_team_city = False self.__existing_types = {} self.__node_info = {} # The toml package is installed as part of repo_man, not directly available in the build, so it may not be # available here and may have to be found through a location supplied by the script arguments. try: import toml self.toml = toml except ModuleNotFoundError: self.toml = None # There is some information to get from repoMan when running through a build so that we can successfully # determine when a failure is fatal and when it is just part of the normal generation process. if args.repoMan is not None: try: python_path = args.repoMan.resolve().as_posix() sys.path.append(python_path) import omni.repo.man if self.toml is None: toml = omni.repo.man.get_toml_module() self.toml = toml self.__in_team_city = omni.repo.man.is_running_in_teamcity() except (ModuleNotFoundError, AttributeError): # If repoMan is inaccessible then issue a warning but continue on to avoid spurious failures if self.toml is None: logger.warning( "toml module could not be found natively or at path '%s', parsing cannot happen", python_path ) else: logger.warning( "Not able to determine if running in TeamCity without module at '%s', assuming not.", python_path, ) logger.info(" Team City run = %s", self.__in_team_city) # -------------------------------------------------------------------------------------------------------------- @property def needs_generation(self) -> bool: """Returns True iff the extension.toml is older than either the generator script itself or the nodes.json file. This is done here after several unsuccessful attempts to get the build structure to recognize when the file needs rebuilding. At worst it means running this script when it isn't necessary, but then returning immediately after checking the file modification times so hopefully no big deal. """ # If the toml cannot be parsed no generation can happen if self.toml is None: return False this_file = Path(__file__) # If the nodes.json does not exist then no generation is needed because there are no nodes if not self.__node_info_path.exists(): logger.info("Skipping generation - no nodes.json file") return False # If the .toml file does not exist it definitely needs generation if not self.__toml_path.exists(): logger.info("Forcing generation - no .toml file") return True # If the tag file does not exist but should then generation has never been done so it needs to be done now if self.__tag_path is not None and not self.__tag_path.exists(): logger.info("Forcing generation - missing tag file") return True # All four files exist. Regeneration is only needed if the .tag file is not the newest one this_file_mtime = this_file.stat().st_mtime node_info_mtime = self.__node_info_path.stat().st_mtime toml_mtime = self.__toml_path.stat().st_mtime tag_mtime = self.__tag_path.stat().st_mtime if self.__tag_path is not None else 0 if tag_mtime < toml_mtime: logger.info("Forcing generation - .toml is newer %s than the tag file %s", toml_mtime, tag_mtime) return True if tag_mtime < node_info_mtime: logger.info("Forcing generation - tag file is older than nodes.json") return True if tag_mtime < this_file_mtime: logger.info("Forcing generation - tag file is older than the generation script") return True # No good reason was found to regenerate, so don't logger.info("Skipping generation - the .toml file is up to date") return False # -------------------------------------------------------------------------------------------------------------- def read_files(self): """Read in the contents of the .toml and .json files and parse them for modification""" logger.info("Reading the extension's .toml file") contents = self.toml.load(self.__toml_path) try: sections = SECTION_NAME.split(".") self.__existing_types = contents for section in sections: self.__existing_types = self.__existing_types[section] except KeyError: self.__existing_types = {} logger.info("Reading the extension's .json node information file") try: with open(self.__node_info_path, "r", encoding="utf-8") as json_fd: self.__node_info = json.load(json_fd)["nodes"] except (IOError, json.JSONDecodeError): self.__node_info = {} # -------------------------------------------------------------------------------------------------------------- def __existing_version_matches(self, node_type_name: str, version: int) -> bool: """Returns True iff the node type name has a version number in the .toml file matching the one passed in""" if node_type_name not in self.__existing_types: return False node_type_info = self.__existing_types[node_type_name] # If the abbreviated version of the metadata was used the version number is all there is if isinstance(node_type_info, int): return version == node_type_info # Otherwise extract the version number from the metadata dictionary try: return version == node_type_info["version"] except KeyError: return False # -------------------------------------------------------------------------------------------------------------- def add_nodes(self): """Ensure the nodes that were passed in are present in the .toml file""" logger.info("Ensuring the node types are in the file") for node_type_name, node_type_info in self.__node_info.items(): version = int(node_type_info["version"]) if not self.__existing_version_matches(node_type_name, version): self.changes_made = True if self.__all_data: new_item = { "version": version, "language": node_type_info["language"], "description": node_type_info["description"], } else: new_item = version logger.info(" Found an unregistered type - %s = %s", node_type_name, new_item) self.__existing_types[node_type_name] = new_item # -------------------------------------------------------------------------------------------------------------- def write_file(self): """Write the new contents of the .toml file back to the original location. The toml library dump() method cannot be used here as it would lose information like comments and formatting so instead it narrows its focus to the [[omnigraph]] section, surrounding it with fixed markers so that it can be easily identified and replaced using a text-based edit. """ logger.info("Writing the file") if self.__in_team_city: raise AttributeError( f"The file {self.__toml_path} was not up to date in the merge request. Rebuild and add it." ) with open(self.__toml_path, "r", encoding="utf-8") as toml_fd: raw_contents = toml_fd.readlines() raw_line_count = len(raw_contents) # Convert the node type list to a .toml format logger.info(" Inserting new section %s", self.__existing_types) # Build the structure from the bottom up to ensure the .toml has the correct nesting section_dict = self.__existing_types sections = SECTION_NAME.split(".") sections.reverse() for section in sections: section_dict = {section: dict(sorted(section_dict.items()))} inserted_section = self.toml.dumps(section_dict) # Scan the file to see if/where the generated section currently resides in_section = False section_start_index = -1 section_end_index = -1 for line_index, line in enumerate(raw_contents): if in_section and line.rstrip() == END_MARKER: in_section = False section_end_index = line_index if line.rstrip() == START_MARKER: in_section = True section_start_index = line_index logger.info(" Existing section location was %s, %s", section_start_index, section_end_index) if section_start_index >= 0 and section_end_index == -1: raise ValueError( f"The .toml file '{self.__toml_path}' was illegal - it had a start marker but no end marker" ) if section_start_index < 0: section_start_index = raw_line_count section_end_index = section_start_index # Write the modified contents with the new generated section try: with open(self.__toml_path, "w", encoding="utf-8") as toml_fd: toml_fd.writelines(raw_contents[0:section_start_index]) # If inserting at the end of the file then insert a blank line for readability if section_start_index == raw_line_count: toml_fd.write("\n") toml_fd.write(f"{START_MARKER}\n") toml_fd.write(inserted_section) toml_fd.write(f"{END_MARKER}\n") toml_fd.writelines(raw_contents[section_end_index + 1 : raw_line_count]) toml_fd.flush() # Required to ensure the mtime is earlier than the tag file's except IOError as error: raise IOError(f"Failed to write back the .toml file '{self.__toml_path}'") from error # -------------------------------------------------------------------------------------------------------------- def touch_tag_file(self): """Forces update of the tag file mtime.""" try: # Tag the conversion as being complete so that a build process can properly manage dependencies. # This has to happen last to avoid a false positive where the tag file is older than the .toml logger.info("Touching the tag file %s", self.__tag_path) if self.__tag_path is not None: with open(self.__tag_path, "w", newline="\n", encoding="utf-8") as tag_fd: tag_fd.write("This file tags the last time its .toml file was processed with node metadata") except IOError as error: raise IOError(f"Failed to write back the tag file '{self.__tag_path}'") from error # ============================================================================================================== def main_update_extension_toml(): """Walk through the steps required to parse, modify, and write the .toml file.""" modifier = TomlModifier() if modifier.needs_generation: modifier.read_files() modifier.add_nodes() if modifier.changes_made: modifier.write_file() # The tag file needs updating even if changes were not made so that it doesn't repeatedly try and fail to # regenerate every time the script runs. modifier.touch_tag_file() # ============================================================================================================== if __name__ == "__main__": main_update_extension_toml()
19,319
Python
48.035533
120
0.591076
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/_internal.py
"""Imports for support code that will used internally by OmniGraph but should not be used elsewhere. These are all subject to change without supported deprecation paths. """ __all__ = [ "cache_location", "Compatibility", "ExtensionContentsBase", "ExtensionContentsStandalone", "ExtensionContentsV118", "ExtensionContentsV119", "ExtensionVersion_t", "extension_contents_factory", "FileType", "find_ogn_build_directory", "full_cache_path", "GENERATED_FILE_CONFIG_NAMES", "GenerationVersions", "get_generator_extension_version", "get_module_path", "get_ogn_file_name", "get_ogn_type_and_node", "get_target_extension_version", "import_tests_in_directory", "load_module_from_file", "LOG", "NodeTypeDefinition", "OmniGraphExtensionError", "set_registration_logging", "Settings", "TemporaryCacheLocation", "TemporaryLogLocation", "VersionProperties", "walk_with_excludes", ] from ._impl.internal.cache_utils import TemporaryCacheLocation, cache_location, full_cache_path from ._impl.internal.extension_contents_1_18 import ExtensionContentsV118 from ._impl.internal.extension_contents_1_19 import ExtensionContentsV119 from ._impl.internal.extension_contents_base import ExtensionContentsBase from ._impl.internal.extension_contents_factory import extension_contents_factory from ._impl.internal.extension_contents_standalone import ExtensionContentsStandalone from ._impl.internal.file_utils import ( GENERATED_FILE_CONFIG_NAMES, FileType, find_ogn_build_directory, get_module_path, get_ogn_file_name, get_ogn_type_and_node, load_module_from_file, walk_with_excludes, ) from ._impl.internal.logging_utils import LOG, OmniGraphExtensionError, TemporaryLogLocation, set_registration_logging from ._impl.internal.node_type_definition import NodeTypeDefinition from ._impl.internal.versions import ( Compatibility, ExtensionVersion_t, GenerationVersions, VersionProperties, get_generator_extension_version, get_target_extension_version, ) from ._impl.node_generator.generate_test_imports import import_tests_in_directory from ._impl.node_generator.utils import Settings
2,234
Python
33.384615
118
0.744405
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/__init__.py
"""Tools that support all of OmniGraph in general, and the .ogn format in particular. General tools can be imported directly with the top level import: .. code-block:: python import omni.graph.tools as ogt help(ogt.deprecated_function) This module also supports a submodule just for the .ogn handling. .. code-block:: python # Support for the parsing and creation of the .ogn format import omni.graph.tools.ogn as ogn """ from . import ogn from ._impl.debugging import destroy_property, function_trace from ._impl.deprecate import ( DeprecatedClass, DeprecatedDictConstant, DeprecatedImport, DeprecatedStringConstant, DeprecateMessage, DeprecationError, DeprecationLevel, RenamedClass, deprecated_constant_object, deprecated_function, ) from ._impl.extension import _PublicExtension # noqa: F401 from ._impl.node_generator.utils import IndentedOutput, shorten_string_lines_to # ============================================================================================================== __all__ = [ "dbg_gc", "dbg_ui", "dbg", "deprecated_constant_object", "deprecated_function", "DeprecatedClass", "DeprecatedDictConstant", "DeprecatedImport", "DeprecatedStringConstant", "DeprecateMessage", "DeprecationError", "DeprecationLevel", "destroy_property", "function_trace", "import_tests_in_directory", "IndentedOutput", "OGN_DEBUG", "RenamedClass", "shorten_string_lines_to", "supported_attribute_type_names", ] # ============================================================================================================== # Soft-deprecated imports. Kept around for backward compatibility for one version. # _____ ______ _____ _____ ______ _____ _______ ______ _____ # | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ # | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | # | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | # | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | # |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ # from ._impl.debugging import OGN_DEBUG, dbg, dbg_gc, dbg_ui from ._impl.node_generator.attributes.management import supported_attribute_type_names as _moved_to_ogn from ._impl.node_generator.generate_test_imports import import_tests_in_directory @deprecated_function("supported_attribute_type_names() has moved to omni.graph.tools.ogn") def supported_attribute_type_names(*args, **kwargs): return _moved_to_ogn(*args, **kwargs)
2,683
Python
34.315789
112
0.530004
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/_1_11.py
"""Backward compatible module for omni.graph.tools version 1.11 and earlier. This module contains everything that was formerly visible by default but will no longer be part of the Python API for omni.graph.tools. If there is something here you rely on contact the OmniGraph team and let them know. Currently the module is in pre-deprecation, meaning you can still access everything here from the main module with .. code-block:: python import omni.graph.tools as ogt ogt.pre_deprecated_but_still_visible() Once the soft deprecation is enabled you will only be able to access the deprecated function with an explicit import: .. code-block:: python import omni.graph.tools as ogt import omni.graph.tools._1_11 as ogt1_11 if i_want_v1_11: ogt1_11.soft_deprecated_but_still_accessible() else: ogt.current_function() When hard deprecation is in place all functionality will be removed and import of this module will fail: .. code-block:: python import omni.graph.tools._1_11 as ot1_11 # Raises DeprecationError """ from ._impl.debugging import OGN_DEBUG, OGN_EVAL_DEBUG, OGN_GC_DEBUG, OGN_UI_DEBUG, dbg, dbg_eval, dbg_gc, dbg_ui from ._impl.node_generator.attributes.management import ATTRIBUTE_MANAGERS from ._impl.node_generator.attributes.parsing import sdf_type_name from ._impl.node_generator.generate_test_imports import import_tests_in_directory # Code that should be retired from ._impl.node_generator.keys import GraphSetupKeys_V1 from ._impl.node_generator.type_definitions import apply_type_definitions # Code that should be refactored and moved to an appropriate location from ._impl.node_generator.utils import ( OGN_PARSE_DEBUG, OGN_REG_DEBUG, Settings, dbg_parse, dbg_reg, is_unwritable, shorten_string_lines_to, ) # Code that is entirely internal to the node description editor and should be made local from ._impl.ogn_types import _OGN_TO_SDF_BASE_NAME as OGN_TO_SDF_BASE_NAME from ._impl.ogn_types import _SDF_BASE_NAME_TO_OGN as SDF_BASE_NAME_TO_OGN from ._impl.ogn_types import _SDF_TO_OGN as SDF_TO_OGN __all__ = [ "apply_type_definitions", "ATTRIBUTE_MANAGERS", "dbg_eval", "dbg_gc", "dbg_parse", "dbg_reg", "dbg_ui", "dbg", "GraphSetupKeys_V1", "import_tests_in_directory", "is_unwritable", "OGN_DEBUG", "OGN_EVAL_DEBUG", "OGN_GC_DEBUG", "OGN_PARSE_DEBUG", "OGN_REG_DEBUG", "OGN_TO_SDF_BASE_NAME", "OGN_UI_DEBUG", "SDF_BASE_NAME_TO_OGN", "SDF_TO_OGN", "sdf_type_name", "Settings", "shorten_string_lines_to", ]
2,611
Python
30.853658
117
0.711605
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/generate_node.py
"""Command line script to run the node generator scripts Mainly a separate script to create a package for the node generator scripts so that the files can use shorter names and relative imports. See node_generator/README.md for the usage information. """ from _impl.node_generator import main main.main()
307
Python
33.222219
115
0.791531
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/ogn.py
"""Tools that support interacting with the .ogn format, including parsing and creation. General tools can be imported directly with the top level import: .. code-block:: python import omni.graph.tools.ogn as ogn help(ogn) """ from ._impl.node_generator.attributes.AttributeManager import AttributeManager from ._impl.node_generator.attributes.management import ( ALL_ATTRIBUTE_TYPES, ATTRIBUTE_UNION_GROUPS, expand_attribute_union_groups, get_attribute_manager, get_attribute_manager_type, split_attribute_type_name, supported_attribute_type_names, ) from ._impl.node_generator.code_generation import code_generation from ._impl.node_generator.generate_cpp import generate_cpp from ._impl.node_generator.generate_documentation import generate_documentation from ._impl.node_generator.generate_python import generate_python from ._impl.node_generator.generate_template import generate_template from ._impl.node_generator.generate_test_imports import generate_test_imports from ._impl.node_generator.generate_tests import generate_tests from ._impl.node_generator.generate_usd import generate_usd from ._impl.node_generator.keys import ( AttributeKeys, CategoryTypeValues, CudaPointerValues, ExclusionTypeValues, GraphSetupKeys, IconKeys, LanguageTypeValues, MemoryTypeValues, MetadataKeys, NodeTypeKeys, TestKeys, ) from ._impl.node_generator.nodes import NodeGenerationError from ._impl.node_generator.parse_scheduling import SchedulingHints from ._impl.node_generator.utils import ( CarbLogError, DebugError, ParseError, UnimplementedError, to_cpp_comment, to_python_comment, to_usd_comment, to_usd_docs, ) from ._impl.ogn_types import ogn_to_sdf, sdf_to_ogn __all__ = [ "ALL_ATTRIBUTE_TYPES", "ATTRIBUTE_UNION_GROUPS", "AttributeKeys", "AttributeManager", "CarbLogError", "CategoryTypeValues", "code_generation", "CudaPointerValues", "DebugError", "ExclusionTypeValues", "expand_attribute_union_groups", "generate_cpp", "generate_documentation", "generate_python", "generate_template", "generate_test_imports", "generate_tests", "generate_usd", "get_attribute_manager_type", "get_attribute_manager", "GraphSetupKeys", "IconKeys", "LanguageTypeValues", "MemoryTypeValues", "MetadataKeys", "NodeGenerationError", "NodeTypeKeys", "ogn_to_sdf", "ParseError", "SchedulingHints", "sdf_to_ogn", "split_attribute_type_name", "supported_attribute_type_names", "TestKeys", "to_cpp_comment", "to_python_comment", "to_usd_comment", "to_usd_docs", "UnimplementedError", ] # ============================================================================================================== # These are symbols that should technically be prefaced with an underscore because they are used internally but # not part of the public API but that would cause a lot of refactoring work so for now they are just added to the # module contents but not the module exports. # _ _ _____ _____ _____ ______ _ _ # | | | |_ _| __ \| __ \| ____| \ | | # | |__| | | | | | | | | | | |__ | \| | # | __ | | | | | | | | | | __| | . ` | # | | | |_| |_| |__| | |__| | |____| |\ | # |_| |_|_____|_____/|_____/|______|_| \_| # from ._impl.node_generator.attributes.management import validate_attribute_type_name # noqa: F401 from ._impl.node_generator.attributes.naming import ATTR_NAME_REQUIREMENT # noqa: F401 from ._impl.node_generator.attributes.naming import ATTR_UI_NAME_REQUIREMENT # noqa: F401 from ._impl.node_generator.attributes.naming import INPUT_GROUP # noqa: F401 from ._impl.node_generator.attributes.naming import INPUT_NS # noqa: F401 from ._impl.node_generator.attributes.naming import OUTPUT_GROUP # noqa: F401 from ._impl.node_generator.attributes.naming import OUTPUT_NS # noqa: F401 from ._impl.node_generator.attributes.naming import STATE_GROUP # noqa: F401 from ._impl.node_generator.attributes.naming import STATE_NS # noqa: F401 from ._impl.node_generator.attributes.naming import assemble_attribute_type_name # noqa: F401 from ._impl.node_generator.attributes.naming import attribute_name_as_python_property # noqa: F401 from ._impl.node_generator.attributes.naming import attribute_name_in_namespace # noqa: F401 from ._impl.node_generator.attributes.naming import attribute_name_without_port # noqa: F401 from ._impl.node_generator.attributes.naming import check_attribute_name # noqa: F401 from ._impl.node_generator.attributes.naming import check_attribute_ui_name # noqa: F401 from ._impl.node_generator.attributes.naming import is_input_name # noqa: F401 from ._impl.node_generator.attributes.naming import is_output_name # noqa: F401 from ._impl.node_generator.attributes.naming import is_state_name # noqa: F401 from ._impl.node_generator.attributes.naming import namespace_of_group # noqa: F401 from ._impl.node_generator.attributes.NumericAttributeManager import NumericAttributeManager # noqa: F401 from ._impl.node_generator.attributes.parsing import attributes_as_usd # noqa: F401 from ._impl.node_generator.attributes.parsing import separate_ogn_role_and_type # noqa: F401 from ._impl.node_generator.attributes.parsing import usd_type_name # noqa: F401 from ._impl.node_generator.generate_test_imports import import_file_contents # noqa: F401 from ._impl.node_generator.nodes import NODE_NAME_REQUIREMENT # noqa: F401 from ._impl.node_generator.nodes import NODE_UI_NAME_REQUIREMENT # noqa: F401 from ._impl.node_generator.nodes import NodeInterface # noqa: F401 from ._impl.node_generator.nodes import NodeInterfaceWrapper # noqa: F401 from ._impl.node_generator.nodes import check_node_language # noqa: F401 from ._impl.node_generator.nodes import check_node_name # noqa: F401 from ._impl.node_generator.nodes import check_node_ui_name # noqa: F401 from ._impl.node_generator.OmniGraphExtension import OmniGraphExtension # noqa: F401 from ._impl.node_generator.utils import _EXTENDED_TYPE_ANY as EXTENDED_TYPE_ANY # noqa: F401 from ._impl.node_generator.utils import _EXTENDED_TYPE_REGULAR as EXTENDED_TYPE_REGULAR # noqa: F401 from ._impl.node_generator.utils import _EXTENDED_TYPE_UNION as EXTENDED_TYPE_UNION # noqa: F401 from ._impl.node_generator.utils import OGN_PARSE_DEBUG # noqa: F401 from ._impl.node_generator.utils import GeneratorConfiguration # noqa: F401 from ._impl.node_generator.utils import check_memory_type # noqa: F401 # By placing this in an internal list and exporting the list the backward compatibility code can make use of it # to allow access to the now-internal objects in a way that looks like they are still published. _HIDDEN = [ "assemble_attribute_type_name", "ATTR_NAME_REQUIREMENT", "ATTR_UI_NAME_REQUIREMENT", "attribute_name_as_python_property", "attribute_name_in_namespace", "attribute_name_without_port", "attributes_as_usd", "check_attribute_name", "check_attribute_ui_name", "check_memory_type", "check_node_language", "check_node_name", "check_node_ui_name", "EXTENDED_TYPE_ANY", "EXTENDED_TYPE_REGULAR", "EXTENDED_TYPE_UNION", "GeneratorConfiguration", "import_file_contents", "INPUT_GROUP", "INPUT_NS", "is_input_name", "is_output_name", "is_state_name", "namespace_of_group", "NODE_NAME_REQUIREMENT", "NODE_UI_NAME_REQUIREMENT", "NodeInterface", "NodeInterfaceWrapper", "NumericAttributeManager", "OGN_PARSE_DEBUG", "OmniGraphExtension", "OUTPUT_GROUP", "OUTPUT_NS", "separate_ogn_role_and_type", "STATE_GROUP", "STATE_NS", "usd_type_name", "validate_attribute_type_name", ]
7,821
Python
40.386243
113
0.70234
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/make_docs_toc.py
""" Create a table of contents file in index.rst that references all of the OmniGraph node generated documentation files that live in that directory. This processing is highly tied to the formatting of the OGN generated documentation files so if they change this has to as well. The table of contents will be in two sections. A table consisting of columns with [node name, node version, link to node doc file, link to node appendix entry] An appendix with headers consisting of the node name and body consisting of the node's description """ from _impl.node_generator import main_docs main_docs.main_docs()
619
Python
37.749998
116
0.781906
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/parse_scheduling.py
from omni.graph.tools._impl.node_generator.parse_scheduling import * # noqa: F401,PLW0401,PLW0614
99
Python
48.999976
98
0.787879
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/generate_python.py
from omni.graph.tools._impl.node_generator.generate_python import * # noqa: F401,PLW0401,PLW0614
98
Python
48.499976
97
0.785714
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/main_docs.py
from omni.graph.tools._impl.node_generator.main_docs import * # noqa: F401,PLW0401,PLW0614
92
Python
45.499977
91
0.771739
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/generate_node_info.py
from omni.graph.tools._impl.node_generator.generate_node_info import * # noqa: F401,PLW0401,PLW0614
101
Python
49.999975
100
0.782178
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/main.py
from omni.graph.tools._impl.node_generator.main import * # noqa: F401,PLW0401,PLW0614
87
Python
42.999979
86
0.770115
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/generate_template.py
from omni.graph.tools._impl.node_generator.generate_template import * # noqa: F401,PLW0401,PLW0614
100
Python
49.499975
99
0.79
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/type_definitions.py
from omni.graph.tools._impl.node_generator.type_definitions import * # noqa: F401,PLW0401,PLW0614
99
Python
48.999976
98
0.787879
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/generate_test_imports.py
from omni.graph.tools._impl.node_generator.generate_test_imports import * # noqa: F401,PLW0401,PLW0614
104
Python
51.499974
103
0.788462
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/__init__.py
import traceback from carb import log_warn _trace = "".join(traceback.format_stack()) log_warn(f"The OmniGraph Node Generator has moved. Use 'import omni.graph.tools.ogn as ogn' to access it.\n{_trace}")
206
Python
28.571424
117
0.742718
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/generate_cpp.py
from omni.graph.tools._impl.node_generator.generate_cpp import * # noqa: F401,PLW0401,PLW0614
95
Python
46.999977
94
0.778947
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/register_ogn_nodes.py
from omni.graph.tools._impl.node_generator.register_ogn_nodes import * # noqa: F401,PLW0401,PLW0614
101
Python
49.999975
100
0.782178
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/generate_tests.py
from omni.graph.tools._impl.node_generator.generate_tests import * # noqa: F401,PLW0401,PLW0614
97
Python
47.999976
96
0.783505
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/generate_usd.py
from omni.graph.tools._impl.node_generator.generate_usd import * # noqa: F401,PLW0401,PLW0614
95
Python
46.999977
94
0.778947
omniverse-code/kit/exts/omni.graph.tools/omni/graph/tools/node_generator/utils.py
from omni.graph.tools._impl.node_generator.utils import * # noqa: F401,PLW0401,PLW0614
88
Python
43.499978
87
0.772727