file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialExtendedTypesPy.rst | .. _omni_graph_tutorials_ExtendedTypesPy_1:
.. _omni_graph_tutorials_ExtendedTypesPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Python Node: Extended Attribute Types
:keywords: lang-en omnigraph node tutorials tutorials extended-types-py
Tutorial Python Node: Extended Attribute Types
==============================================
.. <description>
This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types. It is identical to OgnTutorialExtendedTypes.ogn, except the language of implementation is selected to be python.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Flexible Values (*inputs:flexible*)", "``['float[3][]', 'token']``", "Flexible data type input", "None"
"Float Or Token (*inputs:floatOrToken*)", "``['float', 'token']``", "Attribute that can either be a float value or a token value", "None"
"To Negate (*inputs:toNegate*)", "``['bool[]', 'float[]']``", "Attribute that can either be an array of booleans or an array of floats", "None"
"Tuple Values (*inputs:tuple*)", "``any``", "Variable size/type tuple values", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Doubled Input Value (*outputs:doubledResult*)", "``any``", "If the input 'floatOrToken' is a float this is 2x the value. If it is a token this contains the input token repeated twice.", "None"
"Inverted Flexible Values (*outputs:flexible*)", "``['float[3][]', 'token']``", "Flexible data type output", "None"
"Negated Array Values (*outputs:negatedResult*)", "``['bool[]', 'float[]']``", "Result of negating the data from the 'toNegate' input", "None"
"Negative Tuple Values (*outputs:tuple*)", "``any``", "Negated values of the tuple input", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.ExtendedTypesPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.ExtendedTypesPy.svg"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Python Node: Extended Attribute Types"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialExtendedTypesPyDatabase"
"Python Module", "omni.graph.tutorials"
| 2,842 | reStructuredText | 36.906666 | 218 | 0.61893 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialStateAttributesPy.rst | .. _omni_graph_tutorials_StateAttributesPy_1:
.. _omni_graph_tutorials_StateAttributesPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Python Node: State Attributes
:keywords: lang-en omnigraph node tutorials tutorials state-attributes-py
Tutorial Python Node: State Attributes
======================================
.. <description>
This is a tutorial node. It exercises state attributes to remember data from on evaluation to the next.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:ignored", "``bool``", "Ignore me", "False"
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"state:monotonic", "``int``", "The monotonically increasing output value, reset to 0 when the reset value is true", "None"
"state:reset", "``bool``", "If true then the inputs are ignored and outputs are set to default values, then this flag is set to false for subsequent evaluations.", "True"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.StateAttributesPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.StateAttributesPy.svg"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Python Node: State Attributes"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialStateAttributesPyDatabase"
"Python Module", "omni.graph.tutorials"
| 2,003 | reStructuredText | 27.628571 | 174 | 0.606091 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialDefaults.rst | .. _omni_graph_tutorials_Defaults_1:
.. _omni_graph_tutorials_Defaults:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Defaults
:keywords: lang-en omnigraph node tutorials threadsafe tutorials defaults
Tutorial Node: Defaults
=======================
.. <description>
This is a tutorial node. It will move the values of inputs to corresponding outputs. Inputs all have unspecified, and therefore empty, default values.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:a_array", "``float[]``", "This is an attribute of type array of floats", "[]"
"inputs:a_bool", "``bool``", "This is an attribute of type boolean", "False"
"inputs:a_double", "``double``", "This is an attribute of type 64 bit floating point", "0.0"
"inputs:a_float", "``float``", "This is an attribute of type 32 bit floating point", "0.0"
"inputs:a_half", "``half``", "This is an attribute of type 16 bit floating point", "0.0"
"inputs:a_int", "``int``", "This is an attribute of type 32 bit integer", "0"
"inputs:a_int2", "``int[2]``", "This is an attribute of type 2-tuple of integers", "[0, 0]"
"inputs:a_int64", "``int64``", "This is an attribute of type 64 bit integer", "0"
"inputs:a_matrix", "``matrixd[2]``", "This is an attribute of type 2x2 matrix", "[[1.0, 0.0], [0.0, 1.0]]"
"inputs:a_string", "``string``", "This is an attribute of type string", ""
"inputs:a_token", "``token``", "This is an attribute of type interned string with fast comparison and hashing", ""
"inputs:a_uchar", "``uchar``", "This is an attribute of type unsigned 8 bit integer", "0"
"inputs:a_uint", "``uint``", "This is an attribute of type unsigned 32 bit integer", "0"
"inputs:a_uint64", "``uint64``", "This is an attribute of type unsigned 64 bit integer", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:a_array", "``float[]``", "This is a computed attribute of type array of floats", "None"
"outputs:a_bool", "``bool``", "This is a computed attribute of type boolean", "None"
"outputs:a_double", "``double``", "This is a computed attribute of type 64 bit floating point", "None"
"outputs:a_float", "``float``", "This is a computed attribute of type 32 bit floating point", "None"
"outputs:a_half", "``half``", "This is a computed attribute of type 16 bit floating point", "None"
"outputs:a_int", "``int``", "This is a computed attribute of type 32 bit integer", "None"
"outputs:a_int2", "``int[2]``", "This is a computed attribute of type 2-tuple of integers", "None"
"outputs:a_int64", "``int64``", "This is a computed attribute of type 64 bit integer", "None"
"outputs:a_matrix", "``matrixd[2]``", "This is a computed attribute of type 2x2 matrix", "None"
"outputs:a_string", "``string``", "This is a computed attribute of type string", "None"
"outputs:a_token", "``token``", "This is a computed attribute of type interned string with fast comparison and hashing", "None"
"outputs:a_uchar", "``uchar``", "This is a computed attribute of type unsigned 8 bit integer", "None"
"outputs:a_uint", "``uint``", "This is a computed attribute of type unsigned 32 bit integer", "None"
"outputs:a_uint64", "``uint64``", "This is a computed attribute of type unsigned 64 bit integer", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.Defaults"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.Defaults.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Defaults"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialDefaultsDatabase"
"Python Module", "omni.graph.tutorials"
| 4,347 | reStructuredText | 44.768421 | 150 | 0.619278 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialCudaData.rst | .. _omni_graph_tutorials_CudaData_1:
.. _omni_graph_tutorials_CudaData:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Attributes With CUDA Data
:keywords: lang-en omnigraph node tutorials threadsafe tutorials cuda-data
Tutorial Node: Attributes With CUDA Data
========================================
.. <description>
This is a tutorial node. It performs different functions on the GPU to illustrate different types of data access. The first adds inputs 'a' and 'b' to yield output 'sum', all of which are on the GPU. The second is a sample expansion deformation that multiplies every point on a set of input points, stored on the GPU, by a constant value, stored on the CPU, to yield a set of output points, also on the GPU. The third is an assortment of different data types illustrating how different data is passed to the GPU. This particular node uses CUDA for its GPU computations, as indicated in the memory type value. Normal use case for GPU compute is large amounts of data. For testing purposes this node only handles a very small amount but the principle is the same.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:a", "``float``", "First value to be added in algorithm 1", "0.0"
"inputs:b", "``float``", "Second value to be added in algorithm 1", "0.0"
"inputs:color", "``colord[3]``", "Input with three doubles as a color for algorithm 3", "[1.0, 0.5, 1.0]"
"inputs:half", "``half``", "Input of type half for algorithm 3", "1.0"
"inputs:matrix", "``matrixd[4]``", "Input with 16 doubles interpreted as a double-precision 4d matrix", "[[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]]"
"inputs:multiplier", "``float[3]``", "Amplitude of the expansion for the input points in algorithm 2", "[1.0, 1.0, 1.0]"
"inputs:points", "``float[3][]``", "Points to be moved by algorithm 2", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:color", "``colord[3]``", "Output with three doubles as a color for algorithm 3", "None"
"outputs:half", "``half``", "Output of type half for algorithm 3", "None"
"outputs:matrix", "``matrixd[4]``", "Output with 16 doubles interpreted as a double-precision 4d matrix", "None"
"outputs:points", "``float[3][]``", "Final positions of points from algorithm 2", "None"
"outputs:sum", "``float``", "Sum of the two inputs from algorithm 1", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.CudaData"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.CudaData.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cuda"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Attributes With CUDA Data"
"__memoryType", "cuda"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialCudaDataDatabase"
"Python Module", "omni.graph.tutorials"
| 3,513 | reStructuredText | 42.924999 | 761 | 0.625107 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialCudaDataCpuPy.rst | .. _omni_graph_tutorials_CudaCpuArraysPy_1:
.. _omni_graph_tutorials_CudaCpuArraysPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Python Tutorial Node: Attributes With CUDA Array Pointers In Cpu Memory
:keywords: lang-en omnigraph node tutorials tutorials cuda-cpu-arrays-py
Python Tutorial Node: Attributes With CUDA Array Pointers In Cpu Memory
=======================================================================
.. <description>
This is a tutorial node. It illustrates the alternative method of extracting pointers to GPU array data in which the pointer returned is a CPU pointer and can be dereferenced on the CPU side. Without the cudaPointers value set that pointer would be a GPU pointer to an array of GPU pointers and could only be dereferenced on the device. Both plain attribute and bundle attribute extraction are shown.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:multiplier", "``float[3]``", "Amplitude of the expansion for the input points", "[1.0, 1.0, 1.0]"
"inputs:points", "``float[3][]``", "Array of points to be moved", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:outBundle", "``bundle``", "Bundle containing a copy of the output points", "None"
"outputs:points", "``float[3][]``", "Final positions of points", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.CudaCpuArraysPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.CudaCpuArraysPy.svg"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cuda"
"Generated Code Exclusions", "None"
"__memoryType", "cuda"
"uiName", "Python Tutorial Node: Attributes With CUDA Array Pointers In Cpu Memory"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialCudaDataCpuPyDatabase"
"Python Module", "omni.graph.tutorials"
| 2,451 | reStructuredText | 33.055555 | 400 | 0.618115 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialBundleDataPy.rst | .. _omni_graph_tutorials_BundleDataPy_1:
.. _omni_graph_tutorials_BundleDataPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Python Node: Bundle Data
:keywords: lang-en omnigraph node tutorials tutorials bundle-data-py
Tutorial Python Node: Bundle Data
=================================
.. <description>
This is a tutorial node. It exercises functionality for access of data within bundle attributes. The configuration is the same as omni.graph.tutorials.BundleData except that the implementation language is Python
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Input Bundle (*inputs:bundle*)", "``bundle``", "Bundle whose contents are modified for passing to the output", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Output Bundle (*outputs:bundle*)", "``bundle``", "This is the bundle with values of known types doubled.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.BundleDataPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.BundleDataPy.svg"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Python Node: Bundle Data"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialBundleDataPyDatabase"
"Python Module", "omni.graph.tutorials"
| 1,951 | reStructuredText | 27.289855 | 211 | 0.606868 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialRoleData.rst | .. _omni_graph_tutorials_RoleData_1:
.. _omni_graph_tutorials_RoleData:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Role-Based Attributes
:keywords: lang-en omnigraph node tutorials threadsafe tutorials role-data
Tutorial Node: Role-Based Attributes
====================================
.. <description>
This is a tutorial node. It creates both an input and output attribute of every supported role-based data type. The values are modified in a simple way so that the compute modifies values.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:a_color3d", "``colord[3]``", "This is an attribute interpreted as a double-precision 3d color", "[0.0, 0.0, 0.0]"
"inputs:a_color3f", "``colorf[3]``", "This is an attribute interpreted as a single-precision 3d color", "[0.0, 0.0, 0.0]"
"inputs:a_color3h", "``colorh[3]``", "This is an attribute interpreted as a half-precision 3d color", "[0.0, 0.0, 0.0]"
"inputs:a_color4d", "``colord[4]``", "This is an attribute interpreted as a double-precision 4d color", "[0.0, 0.0, 0.0, 0.0]"
"inputs:a_color4f", "``colorf[4]``", "This is an attribute interpreted as a single-precision 4d color", "[0.0, 0.0, 0.0, 0.0]"
"inputs:a_color4h", "``colorh[4]``", "This is an attribute interpreted as a half-precision 4d color", "[0.0, 0.0, 0.0, 0.0]"
"inputs:a_frame", "``frame[4]``", "This is an attribute interpreted as a coordinate frame", "[[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]]"
"inputs:a_matrix2d", "``matrixd[2]``", "This is an attribute interpreted as a double-precision 2d matrix", "[[1.0, 0.0], [0.0, 1.0]]"
"inputs:a_matrix3d", "``matrixd[3]``", "This is an attribute interpreted as a double-precision 3d matrix", "[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]"
"inputs:a_matrix4d", "``matrixd[4]``", "This is an attribute interpreted as a double-precision 4d matrix", "[[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]]"
"inputs:a_normal3d", "``normald[3]``", "This is an attribute interpreted as a double-precision 3d normal", "[0.0, 0.0, 0.0]"
"inputs:a_normal3f", "``normalf[3]``", "This is an attribute interpreted as a single-precision 3d normal", "[0.0, 0.0, 0.0]"
"inputs:a_normal3h", "``normalh[3]``", "This is an attribute interpreted as a half-precision 3d normal", "[0.0, 0.0, 0.0]"
"inputs:a_point3d", "``pointd[3]``", "This is an attribute interpreted as a double-precision 3d point", "[0.0, 0.0, 0.0]"
"inputs:a_point3f", "``pointf[3]``", "This is an attribute interpreted as a single-precision 3d point", "[0.0, 0.0, 0.0]"
"inputs:a_point3h", "``pointh[3]``", "This is an attribute interpreted as a half-precision 3d point", "[0.0, 0.0, 0.0]"
"inputs:a_quatd", "``quatd[4]``", "This is an attribute interpreted as a double-precision 4d quaternion", "[0.0, 0.0, 0.0, 0.0]"
"inputs:a_quatf", "``quatf[4]``", "This is an attribute interpreted as a single-precision 4d quaternion", "[0.0, 0.0, 0.0, 0.0]"
"inputs:a_quath", "``quath[4]``", "This is an attribute interpreted as a half-precision 4d quaternion", "[0.0, 0.0, 0.0, 0.0]"
"inputs:a_texcoord2d", "``texcoordd[2]``", "This is an attribute interpreted as a double-precision 2d texcoord", "[0.0, 0.0]"
"inputs:a_texcoord2f", "``texcoordf[2]``", "This is an attribute interpreted as a single-precision 2d texcoord", "[0.0, 0.0]"
"inputs:a_texcoord2h", "``texcoordh[2]``", "This is an attribute interpreted as a half-precision 2d texcoord", "[0.0, 0.0]"
"inputs:a_texcoord3d", "``texcoordd[3]``", "This is an attribute interpreted as a double-precision 3d texcoord", "[0.0, 0.0, 0.0]"
"inputs:a_texcoord3f", "``texcoordf[3]``", "This is an attribute interpreted as a single-precision 3d texcoord", "[0.0, 0.0, 0.0]"
"inputs:a_texcoord3h", "``texcoordh[3]``", "This is an attribute interpreted as a half-precision 3d texcoord", "[0.0, 0.0, 0.0]"
"inputs:a_timecode", "``timecode``", "This is a computed attribute interpreted as a timecode", "1.0"
"inputs:a_vector3d", "``vectord[3]``", "This is an attribute interpreted as a double-precision 3d vector", "[0.0, 0.0, 0.0]"
"inputs:a_vector3f", "``vectorf[3]``", "This is an attribute interpreted as a single-precision 3d vector", "[0.0, 0.0, 0.0]"
"inputs:a_vector3h", "``vectorh[3]``", "This is an attribute interpreted as a half-precision 3d vector", "[0.0, 0.0, 0.0]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:a_color3d", "``colord[3]``", "This is a computed attribute interpreted as a double-precision 3d color", "None"
"outputs:a_color3f", "``colorf[3]``", "This is a computed attribute interpreted as a single-precision 3d color", "None"
"outputs:a_color3h", "``colorh[3]``", "This is a computed attribute interpreted as a half-precision 3d color", "None"
"outputs:a_color4d", "``colord[4]``", "This is a computed attribute interpreted as a double-precision 4d color", "None"
"outputs:a_color4f", "``colorf[4]``", "This is a computed attribute interpreted as a single-precision 4d color", "None"
"outputs:a_color4h", "``colorh[4]``", "This is a computed attribute interpreted as a half-precision 4d color", "None"
"outputs:a_frame", "``frame[4]``", "This is a computed attribute interpreted as a coordinate frame", "None"
"outputs:a_matrix2d", "``matrixd[2]``", "This is a computed attribute interpreted as a double-precision 2d matrix", "None"
"outputs:a_matrix3d", "``matrixd[3]``", "This is a computed attribute interpreted as a double-precision 3d matrix", "None"
"outputs:a_matrix4d", "``matrixd[4]``", "This is a computed attribute interpreted as a double-precision 4d matrix", "None"
"outputs:a_normal3d", "``normald[3]``", "This is a computed attribute interpreted as a double-precision 3d normal", "None"
"outputs:a_normal3f", "``normalf[3]``", "This is a computed attribute interpreted as a single-precision 3d normal", "None"
"outputs:a_normal3h", "``normalh[3]``", "This is a computed attribute interpreted as a half-precision 3d normal", "None"
"outputs:a_point3d", "``pointd[3]``", "This is a computed attribute interpreted as a double-precision 3d point", "None"
"outputs:a_point3f", "``pointf[3]``", "This is a computed attribute interpreted as a single-precision 3d point", "None"
"outputs:a_point3h", "``pointh[3]``", "This is a computed attribute interpreted as a half-precision 3d point", "None"
"outputs:a_quatd", "``quatd[4]``", "This is a computed attribute interpreted as a double-precision 4d quaternion", "None"
"outputs:a_quatf", "``quatf[4]``", "This is a computed attribute interpreted as a single-precision 4d quaternion", "None"
"outputs:a_quath", "``quath[4]``", "This is a computed attribute interpreted as a half-precision 4d quaternion", "None"
"outputs:a_texcoord2d", "``texcoordd[2]``", "This is a computed attribute interpreted as a double-precision 2d texcoord", "None"
"outputs:a_texcoord2f", "``texcoordf[2]``", "This is a computed attribute interpreted as a single-precision 2d texcoord", "None"
"outputs:a_texcoord2h", "``texcoordh[2]``", "This is a computed attribute interpreted as a half-precision 2d texcoord", "None"
"outputs:a_texcoord3d", "``texcoordd[3]``", "This is a computed attribute interpreted as a double-precision 3d texcoord", "None"
"outputs:a_texcoord3f", "``texcoordf[3]``", "This is a computed attribute interpreted as a single-precision 3d texcoord", "None"
"outputs:a_texcoord3h", "``texcoordh[3]``", "This is a computed attribute interpreted as a half-precision 3d texcoord", "None"
"outputs:a_timecode", "``timecode``", "This is a computed attribute interpreted as a timecode", "None"
"outputs:a_vector3d", "``vectord[3]``", "This is a computed attribute interpreted as a double-precision 3d vector", "None"
"outputs:a_vector3f", "``vectorf[3]``", "This is a computed attribute interpreted as a single-precision 3d vector", "None"
"outputs:a_vector3h", "``vectorh[3]``", "This is a computed attribute interpreted as a half-precision 3d vector", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.RoleData"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.RoleData.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Role-Based Attributes"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialRoleDataDatabase"
"Python Module", "omni.graph.tutorials"
| 9,219 | reStructuredText | 72.759999 | 201 | 0.647793 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialVectorizedABIPassthrough.rst | .. _omni_graph_tutorials_TutorialVectorizedABIPassThrough_1:
.. _omni_graph_tutorials_TutorialVectorizedABIPassThrough:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Vectorized Passthrough via ABI
:keywords: lang-en omnigraph node tutorials tutorials tutorial-vectorized-a-b-i-pass-through
Tutorial Node: Vectorized Passthrough via ABI
=============================================
.. <description>
Simple passthrough node that copy its input to its output in a vectorized way
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:value", "``float``", "input value", "0.0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:value", "``float``", "output value", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.TutorialVectorizedABIPassThrough"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.TutorialVectorizedABIPassThrough.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Vectorized Passthrough via ABI"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialVectorizedABIPassthroughDatabase"
"Python Module", "omni.graph.tutorials"
| 1,847 | reStructuredText | 25.782608 | 103 | 0.59935 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialVectorizedPassthrough.rst | .. _omni_graph_tutorials_TutorialVectorizedPassThrough_1:
.. _omni_graph_tutorials_TutorialVectorizedPassThrough:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Vectorized Passthrough
:keywords: lang-en omnigraph node tutorials tutorials tutorial-vectorized-pass-through
Tutorial Node: Vectorized Passthrough
=====================================
.. <description>
Simple passthrough node that copy its input to its output in a vectorized way
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:value", "``float``", "input value", "0.0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:value", "``float``", "output value", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.TutorialVectorizedPassThrough"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.TutorialVectorizedPassThrough.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Vectorized Passthrough"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialVectorizedPassthroughDatabase"
"Python Module", "omni.graph.tutorials"
| 1,794 | reStructuredText | 25.014492 | 103 | 0.59699 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialComplexDataPy.rst | .. _omni_graph_tutorials_ComplexDataPy_1:
.. _omni_graph_tutorials_ComplexDataPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Python Node: Attributes With Arrays of Tuples
:keywords: lang-en omnigraph node tutorials tutorials complex-data-py
Tutorial Python Node: Attributes With Arrays of Tuples
======================================================
.. <description>
This is a tutorial node written in Python. It will compute the point3f array by multiplying each element of the float array by the three element vector in the multiplier.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:a_inputArray", "``float[]``", "Input array", "[]"
"inputs:a_vectorMultiplier", "``float[3]``", "Vector multiplier", "[1.0, 2.0, 3.0]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:a_productArray", "``pointf[3][]``", "Output array", "[]"
"outputs:a_tokenArray", "``token[]``", "String representations of the input array", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.ComplexDataPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.ComplexDataPy.svg"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Python Node: Attributes With Arrays of Tuples"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialComplexDataPyDatabase"
"Python Module", "omni.graph.tutorials"
| 2,073 | reStructuredText | 28.211267 | 170 | 0.591413 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialCpuGpuExtended.rst | .. _omni_graph_tutorials_CpuGpuExtended_1:
.. _omni_graph_tutorials_CpuGpuExtended:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: CPU/GPU Extended Attributes
:keywords: lang-en omnigraph node tutorials tutorials cpu-gpu-extended
Tutorial Node: CPU/GPU Extended Attributes
==========================================
.. <description>
This is a tutorial node. It exercises functionality for accessing data in extended attributes that are on the GPU as well as those whose CPU/GPU location is decided at runtime. The compute adds the two inputs 'gpuData' and 'cpuData' together, placing the result in `cpuGpuSum`, whose memory location is determined by the 'gpu' flag. This node is identical to OgnTutorialCpuGpuExtendedPy.ogn, except is is implemented in C++.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"CPU Input Attribute (*inputs:cpuData*)", "``any``", "Input attribute whose data always lives on the CPU", "None"
"Results To GPU (*inputs:gpu*)", "``bool``", "If true then put the sum on the GPU, otherwise put it on the CPU", "False"
"GPU Input Attribute (*inputs:gpuData*)", "``any``", "Input attribute whose data always lives on the GPU", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Sum (*outputs:cpuGpuSum*)", "``any``", "This is the attribute with the selected data. If the 'gpu' attribute is set to true then this attribute's contents will be entirely on the GPU, otherwise it will be on the CPU.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.CpuGpuExtended"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.CpuGpuExtended.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"tags", "tutorial,extended,gpu"
"uiName", "Tutorial Node: CPU/GPU Extended Attributes"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialCpuGpuExtendedDatabase"
"Python Module", "omni.graph.tutorials"
| 2,595 | reStructuredText | 35.055555 | 424 | 0.631214 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialBundles.rst | .. _omni_graph_tutorials_BundleManipulation_1:
.. _omni_graph_tutorials_BundleManipulation:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Bundle Manipulation
:keywords: lang-en omnigraph node tutorials tutorials bundle-manipulation
Tutorial Node: Bundle Manipulation
==================================
.. <description>
This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Filtered Bundle (*inputs:filteredBundle*)", "``bundle``", "Bundle whose contents are filtered before being added to the output", "None"
"inputs:filters", "``token[]``", "List of filter names to be applied to the filteredBundle. Any filter name appearing in this list will be applied to members of that bundle and only those passing all filters will be added to the output bundle. Legal filter values are 'big' (arrays of size > 10), 'x' (attributes whose name contains the letter x), and 'int' (attributes whose base type is integer).", "[]"
"Full Bundle (*inputs:fullBundle*)", "``bundle``", "Bundle whose contents are passed to the output in their entirety", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:combinedBundle", "``bundle``", "This is the union of fullBundle and filtered members of the filteredBundle.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.BundleManipulation"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.BundleManipulation.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Bundle Manipulation"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialBundlesDatabase"
"Python Module", "omni.graph.tutorials"
| 2,437 | reStructuredText | 33.338028 | 410 | 0.632335 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialTupleArrays.rst | .. _omni_graph_tutorials_TupleArrays_1:
.. _omni_graph_tutorials_TupleArrays:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Attributes With Arrays of Tuples
:keywords: lang-en omnigraph node tutorials threadsafe tutorials tuple-arrays
Tutorial Node: Attributes With Arrays of Tuples
===============================================
.. <description>
This is a tutorial node. It will compute the float array 'result' as the elementwise dot product of the input arrays 'a' and 'b'.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:a", "``float[3][]``", "First array", "[]"
"inputs:b", "``float[3][]``", "Second array", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:result", "``float[]``", "Dot-product array", "[]"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.TupleArrays"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.TupleArrays.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Attributes With Arrays of Tuples"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialTupleArraysDatabase"
"Python Module", "omni.graph.tutorials"
| 1,857 | reStructuredText | 25.542857 | 130 | 0.568659 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialBundleData.rst | .. _omni_graph_tutorials_BundleData_1:
.. _omni_graph_tutorials_BundleData:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Bundle Data
:keywords: lang-en omnigraph node tutorials tutorials bundle-data
Tutorial Node: Bundle Data
==========================
.. <description>
This is a tutorial node. It exercises functionality for access of data within bundle attributes.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Input Bundle (*inputs:bundle*)", "``bundle``", "Bundle whose contents are modified for passing to the output", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:bundle", "``bundle``", "This is the bundle with values of known types doubled.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.BundleData"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.BundleData.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Bundle Data"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialBundleDataDatabase"
"Python Module", "omni.graph.tutorials"
| 1,774 | reStructuredText | 24.724637 | 122 | 0.585682 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialState.rst | .. _omni_graph_tutorials_State_1:
.. _omni_graph_tutorials_State:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Internal States
:keywords: lang-en omnigraph node tutorials threadsafe tutorials state
Tutorial Node: Internal States
==============================
.. <description>
This is a tutorial node. It makes use of internal state information to continuously increment an output.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Enable Override (*inputs:override*)", "``bool``", "When true get the output from the overrideValue, otherwise use the internal value", "False"
"Override Value (*inputs:overrideValue*)", "``int64``", "Value to use instead of the monotonically increasing internal one when 'override' is true", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"State-Based Output (*outputs:monotonic*)", "``int64``", "Monotonically increasing output, set by internal state information", "0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.State"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.State.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Internal States"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialStateDatabase"
"Python Module", "omni.graph.tutorials"
| 1,994 | reStructuredText | 27.5 | 156 | 0.601304 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialArrayData.rst | .. _omni_graph_tutorials_ArrayData_1:
.. _omni_graph_tutorials_ArrayData:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Array Attributes
:keywords: lang-en omnigraph node tutorials threadsafe tutorials array-data
Tutorial Node: Array Attributes
===============================
.. <description>
This is a tutorial node. It will compute the array 'result' as the input array 'original' with every element multiplied by the constant 'multiplier'.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:gates", "``bool[]``", "Boolean mask telling which elements of the array should be multiplied", "[]"
"inputs:info", "``token[]``", "List of strings providing commentary", "['There', 'is', 'no', 'data']"
"inputs:multiplier", "``float``", "Multiplier of the array elements", "1.0"
"inputs:original", "``float[]``", "Array to be multiplied", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:infoSize", "``int``", "Number of letters in all strings in the info input", "None"
"outputs:negativeValues", "``bool[]``", "Array of booleans set to true if the corresponding 'result' is negative", "None"
"outputs:result", "``float[]``", "Multiplied array", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.ArrayData"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.ArrayData.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Array Attributes"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialArrayDataDatabase"
"Python Module", "omni.graph.tutorials"
| 2,282 | reStructuredText | 29.851351 | 150 | 0.593777 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialCpuGpuBundles.rst | .. _omni_graph_tutorials_CpuGpuBundles_1:
.. _omni_graph_tutorials_CpuGpuBundles:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: CPU/GPU Bundles
:keywords: lang-en omnigraph node tutorials tutorials cpu-gpu-bundles
Tutorial Node: CPU/GPU Bundles
==============================
.. <description>
This is a tutorial node. It exercises functionality for accessing data in bundles that are on the GPU as well as bundles whose CPU/GPU location is decided at runtime. The compute looks for bundled attributes named 'points' and, if they are found, computes their dot products. If the bundle on the output contains an integer array type named 'dotProducts' then the results are placed there, otherwise a new attribute of that name and type is created on the output bundle to hold the results. This node is identical to OgnTutorialCpuGpuBundlesPy.ogn, except it is implemented in C++.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"CPU Input Bundle (*inputs:cpuBundle*)", "``bundle``", "Input bundle whose data always lives on the CPU", "None"
"Results To GPU (*inputs:gpu*)", "``bool``", "If true then copy gpuBundle onto the output, otherwise copy cpuBundle", "False"
"GPU Input Bundle (*inputs:gpuBundle*)", "``bundle``", "Input bundle whose data always lives on the GPU", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Constructed Bundle (*outputs:cpuGpuBundle*)", "``bundle``", "This is the bundle with the merged data. If the 'gpu' attribute is set to true then this bundle's contents will be entirely on the GPU, otherwise they will be on the CPU.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.CpuGpuBundles"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.CpuGpuBundles.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"tags", "tutorial,bundle,gpu"
"uiName", "Tutorial Node: CPU/GPU Bundles"
"__tokens", "[""points"", ""dotProducts""]"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialCpuGpuBundlesDatabase"
"Python Module", "omni.graph.tutorials"
| 2,762 | reStructuredText | 36.849315 | 581 | 0.64084 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialBundleAddAttributes.rst | .. _omni_graph_tutorials_BundleAddAttributes_1:
.. _omni_graph_tutorials_BundleAddAttributes:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Bundle Add Attributes
:keywords: lang-en omnigraph node tutorials tutorials bundle-add-attributes
Tutorial Node: Bundle Add Attributes
====================================
.. <description>
This is a tutorial node. It exercises functionality for adding and removing attributes on output bundles.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:addedAttributeNames", "``token[]``", "Names for the attribute types to be added. The size of this array must match the size of the 'typesToAdd' array to be legal.", "[]"
"inputs:removedAttributeNames", "``token[]``", "Names for the attribute types to be removed. Non-existent attributes will be ignored.", "[]"
"Attribute Types To Add (*inputs:typesToAdd*)", "``token[]``", "List of type descriptions to add to the bundle. The strings in this list correspond to the strings that represent the attribute types in the .ogn file (e.g. float[3][], colord[3], bool", "[]"
"inputs:useBatchedAPI", "``bool``", "Controls whether or not to used batched APIS for adding/removing attributes", "False"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Constructed Bundle (*outputs:bundle*)", "``bundle``", "This is the bundle with all attributes added by compute.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.BundleAddAttributes"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.BundleAddAttributes.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Bundle Add Attributes"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialBundleAddAttributesDatabase"
"Python Module", "omni.graph.tutorials"
| 2,494 | reStructuredText | 33.652777 | 259 | 0.627506 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialBundlesPy.rst | .. _omni_graph_tutorials_BundleManipulationPy_1:
.. _omni_graph_tutorials_BundleManipulationPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Python Node: Bundle Manipulation
:keywords: lang-en omnigraph node tutorials tutorials bundle-manipulation-py
Tutorial Python Node: Bundle Manipulation
=========================================
.. <description>
This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents. The configuration is the same as omni.graph.tutorials.BundleManipulation except that the implementation language is Python
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Filtered Bundle (*inputs:filteredBundle*)", "``bundle``", "Bundle whose contents are filtered before being added to the output", "None"
"inputs:filters", "``token[]``", "List of filter names to be applied to the filteredBundle. Any filter name appearing in this list will be applied to members of that bundle and only those passing all filters will be added to the output bundle. Legal filter values are 'big' (arrays of size > 10), 'x' (attributes whose name contains the letter x), and 'int' (attributes whose base type is integer).", "[]"
"Full Bundle (*inputs:fullBundle*)", "``bundle``", "Bundle whose contents are passed to the output in their entirety", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:combinedBundle", "``bundle``", "This is the union of fullBundle and filtered members of the filteredBundle.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.BundleManipulationPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.BundleManipulationPy.svg"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Python Node: Bundle Manipulation"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialBundlesPyDatabase"
"Python Module", "omni.graph.tutorials"
| 2,604 | reStructuredText | 35.69014 | 410 | 0.645929 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialExtendedTypes.rst | .. _omni_graph_tutorials_ExtendedTypes_1:
.. _omni_graph_tutorials_ExtendedTypes:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Extended Attribute Types
:keywords: lang-en omnigraph node tutorials threadsafe tutorials extended-types
Tutorial Node: Extended Attribute Types
=======================================
.. <description>
This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Flexible Values (*inputs:flexible*)", "``['float[3][]', 'token']``", "Flexible data type input", "None"
"Float Or Token (*inputs:floatOrToken*)", "``['float', 'token']``", "Attribute that can either be a float value or a token value", "None"
"To Negate (*inputs:toNegate*)", "``['bool[]', 'float[]']``", "Attribute that can either be an array of booleans or an array of floats", "None"
"Tuple Values (*inputs:tuple*)", "``any``", "Variable size/type tuple values", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Doubled Input Value (*outputs:doubledResult*)", "``any``", "If the input 'simpleInput' is a float this is 2x the value. If it is a token this contains the input token repeated twice.", "None"
"Inverted Flexible Values (*outputs:flexible*)", "``['float[3][]', 'token']``", "Flexible data type output", "None"
"Negated Array Values (*outputs:negatedResult*)", "``['bool[]', 'float[]']``", "Result of negating the data from the 'toNegate' input", "None"
"Negative Tuple Values (*outputs:tuple*)", "``any``", "Negated values of the tuple input", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.ExtendedTypes"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.ExtendedTypes.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Extended Attribute Types"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialExtendedTypesDatabase"
"Python Module", "omni.graph.tutorials"
| 2,695 | reStructuredText | 34.946666 | 196 | 0.607792 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialABI.rst | .. _omni_graph_tutorials_Abi_1:
.. _omni_graph_tutorials_Abi:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: ABI Overrides
:keywords: lang-en omnigraph node tutorials,tutorial:abi tutorials abi
Tutorial Node: ABI Overrides
============================
.. <description>
This tutorial node shows how to override ABI methods on your node.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:namespace:a_bool", "``bool``", "The input is any boolean value", "True"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:namespace:a_bool", "``bool``", "The output is computed as the negation of the input", "True"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.Abi"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.Abi.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "python"
"uiName", "Tutorial Node: ABI Overrides"
"Categories", "tutorials,tutorial:abi"
"__categoryDescriptions", "tutorial:abi,Tutorial nodes that override the ABI functions"
"Generated Class Name", "OgnTutorialABIDatabase"
"Python Module", "omni.graph.tutorials"
| 1,795 | reStructuredText | 24.657143 | 105 | 0.582173 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialCpuGpuBundlesPy.rst | .. _omni_graph_tutorials_CpuGpuBundlesPy_1:
.. _omni_graph_tutorials_CpuGpuBundlesPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Python Node: CPU/GPU Bundles
:keywords: lang-en omnigraph node tutorials tutorials cpu-gpu-bundles-py
Tutorial Python Node: CPU/GPU Bundles
=====================================
.. <description>
This is a tutorial node. It exercises functionality for accessing data in bundles that are on the GPU as well as bundles whose CPU/GPU location is decided at runtime. The compute looks for bundled attributes named 'points' and, if they are found, computes the dot products. If the bundle on the output contains an integer array type named 'dotProducts' then the results are placed there, otherwise a new attribute of that name and type is created on the output bundle to hold the results. This node is identical to OgnTutorialCpuGpuBundles.ogn, except is is implemented in Python.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"CPU Input Bundle (*inputs:cpuBundle*)", "``bundle``", "Input bundle whose data always lives on the CPU", "None"
"Results To GPU (*inputs:gpu*)", "``bool``", "If true then copy gpuBundle onto the output, otherwise copy cpuBundle", "False"
"GPU Input Bundle (*inputs:gpuBundle*)", "``bundle``", "Input bundle whose data always lives on the GPU", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Constructed Bundle (*outputs:cpuGpuBundle*)", "``bundle``", "This is the bundle with the merged data. If the 'gpu' attribute is set to true then this bundle's contents will be entirely on the GPU, otherwise it will be on the CPU.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.CpuGpuBundlesPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.CpuGpuBundlesPy.svg"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"tags", "tutorial,bundle,gpu"
"uiName", "Tutorial Python Node: CPU/GPU Bundles"
"__tokens", "[""points"", ""dotProducts""]"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialCpuGpuBundlesPyDatabase"
"Python Module", "omni.graph.tutorials"
| 2,803 | reStructuredText | 37.410958 | 580 | 0.643596 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialCudaDataCpu.rst | .. _omni_graph_tutorials_CudaCpuArrays_1:
.. _omni_graph_tutorials_CudaCpuArrays:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Attributes With CUDA Array Pointers In Cpu Memory
:keywords: lang-en omnigraph node tutorials tutorials cuda-cpu-arrays
Tutorial Node: Attributes With CUDA Array Pointers In Cpu Memory
================================================================
.. <description>
This is a tutorial node. It illustrates the alternative method of extracting pointers to GPU array data in which the pointer returned is a CPU pointer and can be dereferenced on the CPU side. Without the cudaPointers value set that pointer would be a GPU pointer to an array of GPU pointers and could only be dereferenced on the device.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:multiplier", "``float[3]``", "Amplitude of the expansion for the input points", "[1.0, 1.0, 1.0]"
"inputs:points", "``float[3][]``", "Array of points to be moved", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:points", "``float[3][]``", "Final positions of points", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.CudaCpuArrays"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.CudaCpuArrays.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cuda"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Attributes With CUDA Array Pointers In Cpu Memory"
"__memoryType", "cuda"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialCudaDataCpuDatabase"
"Python Module", "omni.graph.tutorials"
| 2,248 | reStructuredText | 30.676056 | 336 | 0.605872 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialEmpty.rst | .. _omni_graph_tutorials_Empty_1:
.. _omni_graph_tutorials_Empty:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: No Attributes
:keywords: lang-en omnigraph node tutorials threadsafe tutorials empty
Tutorial Node: No Attributes
============================
.. <description>
This is a tutorial node. It does absolutely nothing and is only meant to serve as an example to use for setting up your build.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.Empty"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.Empty.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: No Attributes"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialEmptyDatabase"
"Python Module", "omni.graph.tutorials"
| 1,341 | reStructuredText | 25.313725 | 127 | 0.577927 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialABIPy.rst | .. _omni_graph_tutorials_AbiPy_1:
.. _omni_graph_tutorials_AbiPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Python Node: ABI Overrides
:keywords: lang-en omnigraph node tutorials,tutorial:abiPy tutorials abi-py
Tutorial Python Node: ABI Overrides
===================================
.. <description>
This tutorial node shows how to override ABI methods on your Python node. The algorithm of the node converts an RGB color into HSV components.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Color To Convert (*inputs:color*)", "``colord[3]``", "The color to be converted", "[0.0, 0.0, 0.0]"
"", "*multipleValues*", "value1,value2,value3", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:h", "``double``", "The hue component of the input color", "None"
"outputs:s", "``double``", "The saturation component of the input color", "None"
"outputs:v", "``double``", "The value component of the input color", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.AbiPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.AbiPy.svg"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Python Node: ABI Overrides"
"Categories", "tutorials,tutorial:abiPy"
"__categoryDescriptions", "tutorial:abiPy,Tutorial nodes that override the Python ABI functions"
"Generated Class Name", "OgnTutorialABIPyDatabase"
"Python Module", "omni.graph.tutorials"
| 2,139 | reStructuredText | 28.315068 | 142 | 0.59467 |
omniverse-code/kit/exts/omni.graph.tutorials/PACKAGE-LICENSES/omni.graph.tutorials-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.graph.tutorials/config/extension.toml | [package]
title = "OmniGraph Tutorials"
version = "1.3.3"
category = "Graph"
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
description = "Contains a collection of tutorials on constructing OmniGraph nodes."
repository = ""
keywords = ["kit", "omnigraph", "core", "tutorials"]
# Main Python module, available as "import omni.graph.tutorials"
[[python.module]]
name = "omni.graph.tutorials"
# Watch the .ogn files for hot reloading (only works for Python files)
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
# Other extensions on which this one relies
[dependencies]
"omni.graph" = {}
"omni.graph.nodes" = {}
"omni.graph.tools" = {}
"omni.kit.test" = {}
"omni.kit.stage_templates" = {}
"omni.usd" = {}
"omni.kit.pipapi" = {}
[python.pipapi]
requirements = ["numpy"] # SWIPAT filed under: http://nvbugs/3193231
[[native.plugin]]
path = "bin/*.plugin"
recursive = false
[[test]]
timeout = 300
stdoutFailPatterns.exclude = [
# Exclude carb.events leak that only shows up locally
"*[Error] [carb.events.plugin]*PooledAllocator*",
]
pythonTests.unreliable = [
"*test_bundle_gpu_py", # OM-50554
"*test_setting_in_ogn_python_api", # OM-55532
]
[documentation]
deps = [
["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph refs until that workflow is moved
]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 1,400 | TOML | 24.017857 | 108 | 0.68 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/__init__.py | """There is no public API to this module."""
__all__ = []
from ._impl.extension import _PublicExtension # noqa: F401
| 119 | Python | 22.999995 | 59 | 0.663866 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTupleArraysDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.TupleArrays
This is a tutorial node. It will compute the float array 'result' as the elementwise dot product of the input arrays 'a'
and 'b'.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialTupleArraysDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.TupleArrays
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
Outputs:
outputs.result
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a', 'float3[]', 0, None, 'First array', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:b', 'float3[]', 0, None, 'Second array', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:result', 'float[]', 0, None, 'Dot-product array', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def a(self):
data_view = og.AttributeValueHelper(self._attributes.a)
return data_view.get()
@a.setter
def a(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a)
data_view = og.AttributeValueHelper(self._attributes.a)
data_view.set(value)
self.a_size = data_view.get_array_size()
@property
def b(self):
data_view = og.AttributeValueHelper(self._attributes.b)
return data_view.get()
@b.setter
def b(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.b)
data_view = og.AttributeValueHelper(self._attributes.b)
data_view.set(value)
self.b_size = data_view.get_array_size()
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.result_size = 0
self._batchedWriteValues = { }
@property
def result(self):
data_view = og.AttributeValueHelper(self._attributes.result)
return data_view.get(reserved_element_count=self.result_size)
@result.setter
def result(self, value):
data_view = og.AttributeValueHelper(self._attributes.result)
data_view.set(value)
self.result_size = data_view.get_array_size()
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialTupleArraysDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTupleArraysDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTupleArraysDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,882 | Python | 44.253846 | 123 | 0.654029 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundlesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleManipulation
This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents.
"""
import carb
import numpy
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialBundlesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleManipulation
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.filteredBundle
inputs.filters
inputs.fullBundle
Outputs:
outputs.combinedBundle
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:filteredBundle', 'bundle', 0, 'Filtered Bundle', 'Bundle whose contents are filtered before being added to the output', {}, True, None, False, ''),
('inputs:filters', 'token[]', 0, None, "List of filter names to be applied to the filteredBundle. Any filter name\nappearing in this list will be applied to members of that bundle and only those\npassing all filters will be added to the output bundle. Legal filter values are\n'big' (arrays of size > 10), 'x' (attributes whose name contains the letter x), \nand 'int' (attributes whose base type is integer).", {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:fullBundle', 'bundle', 0, 'Full Bundle', 'Bundle whose contents are passed to the output in their entirety', {}, True, None, False, ''),
('outputs:combinedBundle', 'bundle', 0, None, 'This is the union of fullBundle and filtered members of the filteredBundle.', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.filteredBundle = og.AttributeRole.BUNDLE
role_data.inputs.fullBundle = og.AttributeRole.BUNDLE
role_data.outputs.combinedBundle = og.AttributeRole.BUNDLE
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def filteredBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.filteredBundle"""
return self.__bundles.filteredBundle
@property
def filters(self):
data_view = og.AttributeValueHelper(self._attributes.filters)
return data_view.get()
@filters.setter
def filters(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.filters)
data_view = og.AttributeValueHelper(self._attributes.filters)
data_view.set(value)
self.filters_size = data_view.get_array_size()
@property
def fullBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.fullBundle"""
return self.__bundles.fullBundle
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def combinedBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.combinedBundle"""
return self.__bundles.combinedBundle
@combinedBundle.setter
def combinedBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.combinedBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.combinedBundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialBundlesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundlesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundlesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,335 | Python | 51.4 | 475 | 0.678391 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialVectorizedPassthroughDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.TutorialVectorizedPassThrough
Simple passthrough node that copy its input to its output in a vectorized way
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialVectorizedPassthroughDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.TutorialVectorizedPassThrough
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.value
Outputs:
outputs.value
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:value', 'float', 0, None, 'input value', {}, True, 0.0, False, ''),
('outputs:value', 'float', 0, None, 'output value', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.value)
data_view = og.AttributeValueHelper(self._attributes.value)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
data_view = og.AttributeValueHelper(self._attributes.value)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialVectorizedPassthroughDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialVectorizedPassthroughDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialVectorizedPassthroughDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,092 | Python | 45.3 | 131 | 0.675373 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuExtendedPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuExtendedPy
This is a tutorial node. It exercises functionality for accessing data in extended attributes that are on the GPU as well
as those whose CPU/GPU location is decided at runtime. The compute adds the two inputs 'gpuData' and 'cpuData' together,
placing the result in `cpuGpuSum`, whose memory location is determined by the 'gpu' flag. This node is identical to OgnTutorialCpuGpuExtended.ogn,
except is is implemented in Python.
"""
from typing import Any
import carb
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCpuGpuExtendedPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuExtendedPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cpuData
inputs.gpu
inputs.gpuData
Outputs:
outputs.cpuGpuSum
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:cpuData', 'any', 2, 'CPU Input Attribute', 'Input attribute whose data always lives on the CPU', {}, True, None, False, ''),
('inputs:gpu', 'bool', 0, 'Results To GPU', 'If true then put the sum on the GPU, otherwise put it on the CPU', {}, True, False, False, ''),
('inputs:gpuData', 'any', 2, 'GPU Input Attribute', 'Input attribute whose data always lives on the GPU', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda'}, True, None, False, ''),
('outputs:cpuGpuSum', 'any', 2, 'Sum', "This is the attribute with the selected data. If the 'gpu' attribute is set to true then this\nattribute's contents will be entirely on the GPU, otherwise it will be on the CPU.", {ogn.MetadataKeys.MEMORY_TYPE: 'any'}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"gpu", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.gpu]
self._batchedReadValues = [False]
@property
def cpuData(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.cpuData"""
return og.RuntimeAttribute(self._attributes.cpuData.get_attribute_data(), self._context, True)
@cpuData.setter
def cpuData(self, value_to_set: Any):
"""Assign another attribute's value to outputs.cpuData"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.cpuData.value = value_to_set.value
else:
self.cpuData.value = value_to_set
@property
def gpuData(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.gpuData"""
return og.RuntimeAttribute(self._attributes.gpuData.get_attribute_data(), self._context, True)
@gpuData.setter
def gpuData(self, value_to_set: Any):
"""Assign another attribute's value to outputs.gpuData"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.gpuData.value = value_to_set.value
else:
self.gpuData.value = value_to_set
@property
def gpu(self):
return self._batchedReadValues[0]
@gpu.setter
def gpu(self, value):
self._batchedReadValues[0] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def cpuGpuSum(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.cpuGpuSum"""
return og.RuntimeAttribute(self._attributes.cpuGpuSum.get_attribute_data(), self._context, False)
@cpuGpuSum.setter
def cpuGpuSum(self, value_to_set: Any):
"""Assign another attribute's value to outputs.cpuGpuSum"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.cpuGpuSum.value = value_to_set.value
else:
self.cpuGpuSum.value = value_to_set
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialCpuGpuExtendedPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuExtendedPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuExtendedPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialCpuGpuExtendedPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.CpuGpuExtendedPy'
@staticmethod
def compute(context, node):
def database_valid():
if db.inputs.cpuData.type.base_type == og.BaseDataType.UNKNOWN:
db.log_warning('Required extended attribute inputs:cpuData is not resolved, compute skipped')
return False
if db.inputs.gpuData.type.base_type == og.BaseDataType.UNKNOWN:
db.log_warning('Required extended attribute inputs:gpuData is not resolved, compute skipped')
return False
if db.outputs.cpuGpuSum.type.base_type == og.BaseDataType.UNKNOWN:
db.log_warning('Required extended attribute outputs:cpuGpuSum is not resolved, compute skipped')
return False
return True
try:
per_node_data = OgnTutorialCpuGpuExtendedPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialCpuGpuExtendedPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialCpuGpuExtendedPyDatabase(node)
try:
compute_function = getattr(OgnTutorialCpuGpuExtendedPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialCpuGpuExtendedPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialCpuGpuExtendedPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialCpuGpuExtendedPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialCpuGpuExtendedPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialCpuGpuExtendedPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialCpuGpuExtendedPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialCpuGpuExtendedPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialCpuGpuExtendedPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialCpuGpuExtendedPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.TAGS, "tutorial,extended,gpu")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: CPU/GPU Extended Attributes")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises functionality for accessing data in extended attributes that are on the GPU as well as those whose CPU/GPU location is decided at runtime. The compute adds the two inputs 'gpuData' and 'cpuData' together, placing the result in `cpuGpuSum`, whose memory location is determined by the 'gpu' flag. This node is identical to OgnTutorialCpuGpuExtended.ogn, except is is implemented in Python.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.CpuGpuExtendedPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialCpuGpuExtendedPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialCpuGpuExtendedPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialCpuGpuExtendedPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialCpuGpuExtendedPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.CpuGpuExtendedPy")
| 14,441 | Python | 51.326087 | 497 | 0.651963 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCudaDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CudaData
This is a tutorial node. It performs different functions on the GPU to illustrate different types of data access. The first
adds inputs 'a' and 'b' to yield output 'sum', all of which are on the GPU. The second is a sample expansion deformation
that multiplies every point on a set of input points, stored on the GPU, by a constant value, stored on the CPU, to yield
a set of output points, also on the GPU. The third is an assortment of different data types illustrating how different data
is passed to the GPU. This particular node uses CUDA for its GPU computations, as indicated in the memory type value. Normal
use case for GPU compute is large amounts of data. For testing purposes this node only handles a very small amount but the
principle is the same.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCudaDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CudaData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
inputs.color
inputs.half
inputs.matrix
inputs.multiplier
inputs.points
Outputs:
outputs.color
outputs.half
outputs.matrix
outputs.points
outputs.sum
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a', 'float', 0, None, 'First value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:b', 'float', 0, None, 'Second value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:color', 'color3d', 0, None, 'Input with three doubles as a color for algorithm 3', {ogn.MetadataKeys.DEFAULT: '[1.0, 0.5, 1.0]'}, True, [1.0, 0.5, 1.0], False, ''),
('inputs:half', 'half', 0, None, 'Input of type half for algorithm 3', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:matrix', 'matrix4d', 0, None, 'Input with 16 doubles interpreted as a double-precision 4d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]'}, True, [[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]], False, ''),
('inputs:multiplier', 'float3', 0, None, 'Amplitude of the expansion for the input points in algorithm 2', {ogn.MetadataKeys.MEMORY_TYPE: 'cpu', ogn.MetadataKeys.DEFAULT: '[1.0, 1.0, 1.0]'}, True, [1.0, 1.0, 1.0], False, ''),
('inputs:points', 'float3[]', 0, None, 'Points to be moved by algorithm 2', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:color', 'color3d', 0, None, 'Output with three doubles as a color for algorithm 3', {}, True, None, False, ''),
('outputs:half', 'half', 0, None, 'Output of type half for algorithm 3', {}, True, None, False, ''),
('outputs:matrix', 'matrix4d', 0, None, 'Output with 16 doubles interpreted as a double-precision 4d matrix', {}, True, None, False, ''),
('outputs:points', 'float3[]', 0, None, 'Final positions of points from algorithm 2', {}, True, None, False, ''),
('outputs:sum', 'float', 0, None, 'Sum of the two inputs from algorithm 1', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.color = og.AttributeRole.COLOR
role_data.inputs.matrix = og.AttributeRole.MATRIX
role_data.outputs.color = og.AttributeRole.COLOR
role_data.outputs.matrix = og.AttributeRole.MATRIX
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def a(self):
data_view = og.AttributeValueHelper(self._attributes.a)
return data_view.get(on_gpu=True)
@a.setter
def a(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a)
data_view = og.AttributeValueHelper(self._attributes.a)
data_view.set(value, on_gpu=True)
@property
def b(self):
data_view = og.AttributeValueHelper(self._attributes.b)
return data_view.get(on_gpu=True)
@b.setter
def b(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.b)
data_view = og.AttributeValueHelper(self._attributes.b)
data_view.set(value, on_gpu=True)
@property
def color(self):
data_view = og.AttributeValueHelper(self._attributes.color)
return data_view.get(on_gpu=True)
@color.setter
def color(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.color)
data_view = og.AttributeValueHelper(self._attributes.color)
data_view.set(value, on_gpu=True)
@property
def half(self):
data_view = og.AttributeValueHelper(self._attributes.half)
return data_view.get(on_gpu=True)
@half.setter
def half(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.half)
data_view = og.AttributeValueHelper(self._attributes.half)
data_view.set(value, on_gpu=True)
@property
def matrix(self):
data_view = og.AttributeValueHelper(self._attributes.matrix)
return data_view.get(on_gpu=True)
@matrix.setter
def matrix(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.matrix)
data_view = og.AttributeValueHelper(self._attributes.matrix)
data_view.set(value, on_gpu=True)
@property
def multiplier(self):
data_view = og.AttributeValueHelper(self._attributes.multiplier)
return data_view.get()
@multiplier.setter
def multiplier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.multiplier)
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.set(value)
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
return data_view.get(on_gpu=True)
@points.setter
def points(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.points)
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.set(value, on_gpu=True)
self.points_size = data_view.get_array_size()
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.points_size = None
self._batchedWriteValues = { }
@property
def color(self):
data_view = og.AttributeValueHelper(self._attributes.color)
return data_view.get(on_gpu=True)
@color.setter
def color(self, value):
data_view = og.AttributeValueHelper(self._attributes.color)
data_view.set(value, on_gpu=True)
@property
def half(self):
data_view = og.AttributeValueHelper(self._attributes.half)
return data_view.get(on_gpu=True)
@half.setter
def half(self, value):
data_view = og.AttributeValueHelper(self._attributes.half)
data_view.set(value, on_gpu=True)
@property
def matrix(self):
data_view = og.AttributeValueHelper(self._attributes.matrix)
return data_view.get(on_gpu=True)
@matrix.setter
def matrix(self, value):
data_view = og.AttributeValueHelper(self._attributes.matrix)
data_view.set(value, on_gpu=True)
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
return data_view.get(reserved_element_count=self.points_size, on_gpu=True)
@points.setter
def points(self, value):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.set(value, on_gpu=True)
self.points_size = data_view.get_array_size()
@property
def sum(self):
data_view = og.AttributeValueHelper(self._attributes.sum)
return data_view.get(on_gpu=True)
@sum.setter
def sum(self, value):
data_view = og.AttributeValueHelper(self._attributes.sum)
data_view.set(value, on_gpu=True)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialCudaDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCudaDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCudaDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,300 | Python | 45.950382 | 343 | 0.633252 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuData
This is a tutorial node. It illustrates how to access data whose memory location, CPU or GPU, is determined at runtime in
the compute method. The data types are the same as for the purely CPU and purely GPU tutorials, it is only the access method
that changes. The input 'is_gpu' determines where the data of the other attributes can be accessed.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCpuGpuDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
inputs.is_gpu
inputs.multiplier
inputs.points
Outputs:
outputs.points
outputs.sum
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a', 'float', 0, None, 'First value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:b', 'float', 0, None, 'Second value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:is_gpu', 'bool', 0, None, 'Runtime switch determining where the data for the other attributes lives.', {ogn.MetadataKeys.MEMORY_TYPE: 'cpu', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:multiplier', 'float3', 0, None, 'Amplitude of the expansion for the input points in algorithm 2', {ogn.MetadataKeys.DEFAULT: '[1.0, 1.0, 1.0]'}, True, [1.0, 1.0, 1.0], False, ''),
('inputs:points', 'float3[]', 0, None, 'Points to be moved by algorithm 2', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:points', 'float3[]', 0, None, 'Final positions of points from algorithm 2', {}, True, None, False, ''),
('outputs:sum', 'float', 0, None, 'Sum of the two inputs from algorithm 1', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
class __a:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.a)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.a)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def a(self):
return self.__class__.__a(self)
class __b:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.b)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.b)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def b(self):
return self.__class__.__b(self)
@property
def is_gpu(self):
data_view = og.AttributeValueHelper(self._attributes.is_gpu)
return data_view.get()
@is_gpu.setter
def is_gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.is_gpu)
data_view = og.AttributeValueHelper(self._attributes.is_gpu)
data_view.set(value)
class __multiplier:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.multiplier)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.multiplier)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def multiplier(self):
return self.__class__.__multiplier(self)
class __points:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
self._parent.cpu_size = data_view.get_array_size()
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
self._parent.gpu_size = data_view.get_array_size()
@property
def points(self):
return self.__class__.__points(self)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.points_size = None
self._batchedWriteValues = { }
class __points:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get(reserved_element_count=self._parent.points_size)
@cpu.setter
def cpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
self._parent.cpu_size = data_view.get_array_size()
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get(reserved_element_count=self._parent.points_size, on_gpu=True)
@gpu.setter
def gpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
self._parent.gpu_size = data_view.get_array_size()
@property
def points(self):
return self.__class__.__points(self)
class __sum:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.sum)
return data_view.get()
@cpu.setter
def cpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.sum)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def sum(self):
return self.__class__.__sum(self)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialCpuGpuDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,813 | Python | 41.430463 | 218 | 0.590806 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuBundlesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuBundlesPy
This is a tutorial node. It exercises functionality for accessing data in bundles that are on the GPU as well as bundles
whose CPU/GPU location is decided at runtime. The compute looks for bundled attributes named 'points' and, if they are found,
computes the dot products. If the bundle on the output contains an integer array type named 'dotProducts' then the results
are placed there, otherwise a new attribute of that name and type is created on the output bundle to hold the results. This
node is identical to OgnTutorialCpuGpuBundles.ogn, except is is implemented in Python.
"""
import carb
import sys
import traceback
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCpuGpuBundlesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuBundlesPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cpuBundle
inputs.gpu
inputs.gpuBundle
Outputs:
outputs.cpuGpuBundle
Predefined Tokens:
tokens.points
tokens.dotProducts
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:cpuBundle', 'bundle', 0, 'CPU Input Bundle', 'Input bundle whose data always lives on the CPU', {}, True, None, False, ''),
('inputs:gpu', 'bool', 0, 'Results To GPU', 'If true then copy gpuBundle onto the output, otherwise copy cpuBundle', {}, True, False, False, ''),
('inputs:gpuBundle', 'bundle', 0, 'GPU Input Bundle', 'Input bundle whose data always lives on the GPU', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda'}, True, None, False, ''),
('outputs:cpuGpuBundle', 'bundle', 0, 'Constructed Bundle', "This is the bundle with the merged data. If the 'gpu' attribute is set to true then this\nbundle's contents will be entirely on the GPU, otherwise it will be on the CPU.", {ogn.MetadataKeys.MEMORY_TYPE: 'any'}, True, None, False, ''),
])
class tokens:
points = "points"
dotProducts = "dotProducts"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.cpuBundle = og.AttributeRole.BUNDLE
role_data.inputs.gpuBundle = og.AttributeRole.BUNDLE
role_data.outputs.cpuGpuBundle = og.AttributeRole.BUNDLE
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"gpu", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, ['inputs:gpuBundle'], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = [self._attributes.gpu]
self._batchedReadValues = [False]
@property
def cpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.cpuBundle"""
return self.__bundles.cpuBundle
@property
def gpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.gpuBundle"""
return self.__bundles.gpuBundle
@property
def gpu(self):
return self._batchedReadValues[0]
@gpu.setter
def gpu(self, value):
self._batchedReadValues[0] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, ['outputs_cpuGpuBundle'], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def cpuGpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.cpuGpuBundle"""
return self.__bundles.cpuGpuBundle
@cpuGpuBundle.setter
def cpuGpuBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.cpuGpuBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.cpuGpuBundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialCpuGpuBundlesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuBundlesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuBundlesPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialCpuGpuBundlesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.CpuGpuBundlesPy'
@staticmethod
def compute(context, node):
def database_valid():
if not db.inputs.cpuBundle.valid:
db.log_warning('Required bundle inputs.cpuBundle is invalid or not connected, compute skipped')
return False
if not db.inputs.gpuBundle.valid:
db.log_warning('Required bundle inputs.gpuBundle is invalid or not connected, compute skipped')
return False
if not db.outputs.cpuGpuBundle.valid:
db.log_error('Required bundle outputs.cpuGpuBundle is invalid, compute skipped')
return False
return True
try:
per_node_data = OgnTutorialCpuGpuBundlesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialCpuGpuBundlesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialCpuGpuBundlesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialCpuGpuBundlesPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialCpuGpuBundlesPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialCpuGpuBundlesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialCpuGpuBundlesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialCpuGpuBundlesPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialCpuGpuBundlesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialCpuGpuBundlesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialCpuGpuBundlesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialCpuGpuBundlesPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialCpuGpuBundlesPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.TAGS, "tutorial,bundle,gpu")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: CPU/GPU Bundles")
node_type.set_metadata(ogn.MetadataKeys.TOKENS, "[\"points\", \"dotProducts\"]")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises functionality for accessing data in bundles that are on the GPU as well as bundles whose CPU/GPU location is decided at runtime. The compute looks for bundled attributes named 'points' and, if they are found, computes the dot products. If the bundle on the output contains an integer array type named 'dotProducts' then the results are placed there, otherwise a new attribute of that name and type is created on the output bundle to hold the results. This node is identical to OgnTutorialCpuGpuBundles.ogn, except is is implemented in Python.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.CpuGpuBundlesPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialCpuGpuBundlesPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialCpuGpuBundlesPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialCpuGpuBundlesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialCpuGpuBundlesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.CpuGpuBundlesPy")
| 14,755 | Python | 51.7 | 652 | 0.658218 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialStateAttributesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.StateAttributesPy
This is a tutorial node. It exercises state attributes to remember data from on evaluation to the next.
"""
import carb
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialStateAttributesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.StateAttributesPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.ignored
State:
state.monotonic
state.reset
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:ignored', 'bool', 0, None, 'Ignore me', {}, True, False, False, ''),
('state:monotonic', 'int', 0, None, 'The monotonically increasing output value, reset to 0 when the reset value is true', {}, True, None, False, ''),
('state:reset', 'bool', 0, None, 'If true then the inputs are ignored and outputs are set to default values, then this\nflag is set to false for subsequent evaluations.', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"ignored", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.ignored]
self._batchedReadValues = [False]
@property
def ignored(self):
return self._batchedReadValues[0]
@ignored.setter
def ignored(self, value):
self._batchedReadValues[0] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
@property
def monotonic(self):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
return data_view.get()
@monotonic.setter
def monotonic(self, value):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
data_view.set(value)
@property
def reset(self):
data_view = og.AttributeValueHelper(self._attributes.reset)
return data_view.get()
@reset.setter
def reset(self, value):
data_view = og.AttributeValueHelper(self._attributes.reset)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialStateAttributesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialStateAttributesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialStateAttributesPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.StateAttributesPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialStateAttributesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialStateAttributesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialStateAttributesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialStateAttributesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialStateAttributesPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialStateAttributesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialStateAttributesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: State Attributes")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises state attributes to remember data from on evaluation to the next.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.StateAttributesPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialStateAttributesPyDatabase.INTERFACE.add_to_node_type(node_type)
node_type.set_has_state(True)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialStateAttributesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.StateAttributesPy")
| 11,647 | Python | 47.132231 | 238 | 0.649008 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundlesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleManipulationPy
This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents. The configuration
is the same as omni.graph.tutorials.BundleManipulation except that the implementation language is Python
"""
import carb
import numpy
import sys
import traceback
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialBundlesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleManipulationPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.filteredBundle
inputs.filters
inputs.fullBundle
Outputs:
outputs.combinedBundle
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:filteredBundle', 'bundle', 0, 'Filtered Bundle', 'Bundle whose contents are filtered before being added to the output', {}, True, None, False, ''),
('inputs:filters', 'token[]', 0, None, "List of filter names to be applied to the filteredBundle. Any filter name\nappearing in this list will be applied to members of that bundle and only those\npassing all filters will be added to the output bundle. Legal filter values are\n'big' (arrays of size > 10), 'x' (attributes whose name contains the letter x), \nand 'int' (attributes whose base type is integer).", {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:fullBundle', 'bundle', 0, 'Full Bundle', 'Bundle whose contents are passed to the output in their entirety', {}, True, None, False, ''),
('outputs:combinedBundle', 'bundle', 0, None, 'This is the union of fullBundle and filtered members of the filteredBundle.', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.filteredBundle = og.AttributeRole.BUNDLE
role_data.inputs.fullBundle = og.AttributeRole.BUNDLE
role_data.outputs.combinedBundle = og.AttributeRole.BUNDLE
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def filteredBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.filteredBundle"""
return self.__bundles.filteredBundle
@property
def filters(self):
data_view = og.AttributeValueHelper(self._attributes.filters)
return data_view.get()
@filters.setter
def filters(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.filters)
data_view = og.AttributeValueHelper(self._attributes.filters)
data_view.set(value)
self.filters_size = data_view.get_array_size()
@property
def fullBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.fullBundle"""
return self.__bundles.fullBundle
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def combinedBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.combinedBundle"""
return self.__bundles.combinedBundle
@combinedBundle.setter
def combinedBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.combinedBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.combinedBundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialBundlesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundlesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundlesPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.BundleManipulationPy'
@staticmethod
def compute(context, node):
def database_valid():
if not db.inputs.filteredBundle.valid:
db.log_warning('Required bundle inputs.filteredBundle is invalid or not connected, compute skipped')
return False
if not db.inputs.fullBundle.valid:
db.log_warning('Required bundle inputs.fullBundle is invalid or not connected, compute skipped')
return False
if not db.outputs.combinedBundle.valid:
db.log_error('Required bundle outputs.combinedBundle is invalid, compute skipped')
return False
return True
try:
per_node_data = OgnTutorialBundlesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialBundlesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialBundlesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialBundlesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialBundlesPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialBundlesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialBundlesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Bundle Manipulation")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents. The configuration is the same as omni.graph.tutorials.BundleManipulation except that the implementation language is Python")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.BundleManipulationPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialBundlesPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialBundlesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.BundleManipulationPy")
| 13,575 | Python | 51.015325 | 475 | 0.657459 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialRoleDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.RoleData
This is a tutorial node. It creates both an input and output attribute of every supported role-based data type. The values
are modified in a simple way so that the compute modifies values.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialRoleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.RoleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_color3d
inputs.a_color3f
inputs.a_color3h
inputs.a_color4d
inputs.a_color4f
inputs.a_color4h
inputs.a_frame
inputs.a_matrix2d
inputs.a_matrix3d
inputs.a_matrix4d
inputs.a_normal3d
inputs.a_normal3f
inputs.a_normal3h
inputs.a_point3d
inputs.a_point3f
inputs.a_point3h
inputs.a_quatd
inputs.a_quatf
inputs.a_quath
inputs.a_texcoord2d
inputs.a_texcoord2f
inputs.a_texcoord2h
inputs.a_texcoord3d
inputs.a_texcoord3f
inputs.a_texcoord3h
inputs.a_timecode
inputs.a_vector3d
inputs.a_vector3f
inputs.a_vector3h
Outputs:
outputs.a_color3d
outputs.a_color3f
outputs.a_color3h
outputs.a_color4d
outputs.a_color4f
outputs.a_color4h
outputs.a_frame
outputs.a_matrix2d
outputs.a_matrix3d
outputs.a_matrix4d
outputs.a_normal3d
outputs.a_normal3f
outputs.a_normal3h
outputs.a_point3d
outputs.a_point3f
outputs.a_point3h
outputs.a_quatd
outputs.a_quatf
outputs.a_quath
outputs.a_texcoord2d
outputs.a_texcoord2f
outputs.a_texcoord2h
outputs.a_texcoord3d
outputs.a_texcoord3f
outputs.a_texcoord3h
outputs.a_timecode
outputs.a_vector3d
outputs.a_vector3f
outputs.a_vector3h
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a_color3d', 'color3d', 0, None, 'This is an attribute interpreted as a double-precision 3d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_color3f', 'color3f', 0, None, 'This is an attribute interpreted as a single-precision 3d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_color3h', 'color3h', 0, None, 'This is an attribute interpreted as a half-precision 3d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_color4d', 'color4d', 0, None, 'This is an attribute interpreted as a double-precision 4d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_color4f', 'color4f', 0, None, 'This is an attribute interpreted as a single-precision 4d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_color4h', 'color4h', 0, None, 'This is an attribute interpreted as a half-precision 4d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_frame', 'frame4d', 0, None, 'This is an attribute interpreted as a coordinate frame', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]'}, True, [[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]], False, ''),
('inputs:a_matrix2d', 'matrix2d', 0, None, 'This is an attribute interpreted as a double-precision 2d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0], [0.0, 1.0]]'}, True, [[1.0, 0.0], [0.0, 1.0]], False, ''),
('inputs:a_matrix3d', 'matrix3d', 0, None, 'This is an attribute interpreted as a double-precision 3d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]'}, True, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], False, ''),
('inputs:a_matrix4d', 'matrix4d', 0, None, 'This is an attribute interpreted as a double-precision 4d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]'}, True, [[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]], False, ''),
('inputs:a_normal3d', 'normal3d', 0, None, 'This is an attribute interpreted as a double-precision 3d normal', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_normal3f', 'normal3f', 0, None, 'This is an attribute interpreted as a single-precision 3d normal', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_normal3h', 'normal3h', 0, None, 'This is an attribute interpreted as a half-precision 3d normal', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_point3d', 'point3d', 0, None, 'This is an attribute interpreted as a double-precision 3d point', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_point3f', 'point3f', 0, None, 'This is an attribute interpreted as a single-precision 3d point', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_point3h', 'point3h', 0, None, 'This is an attribute interpreted as a half-precision 3d point', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_quatd', 'quatd', 0, None, 'This is an attribute interpreted as a double-precision 4d quaternion', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_quatf', 'quatf', 0, None, 'This is an attribute interpreted as a single-precision 4d quaternion', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_quath', 'quath', 0, None, 'This is an attribute interpreted as a half-precision 4d quaternion', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_texcoord2d', 'texCoord2d', 0, None, 'This is an attribute interpreted as a double-precision 2d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0]'}, True, [0.0, 0.0], False, ''),
('inputs:a_texcoord2f', 'texCoord2f', 0, None, 'This is an attribute interpreted as a single-precision 2d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0]'}, True, [0.0, 0.0], False, ''),
('inputs:a_texcoord2h', 'texCoord2h', 0, None, 'This is an attribute interpreted as a half-precision 2d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0]'}, True, [0.0, 0.0], False, ''),
('inputs:a_texcoord3d', 'texCoord3d', 0, None, 'This is an attribute interpreted as a double-precision 3d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_texcoord3f', 'texCoord3f', 0, None, 'This is an attribute interpreted as a single-precision 3d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_texcoord3h', 'texCoord3h', 0, None, 'This is an attribute interpreted as a half-precision 3d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_timecode', 'timecode', 0, None, 'This is a computed attribute interpreted as a timecode', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:a_vector3d', 'vector3d', 0, None, 'This is an attribute interpreted as a double-precision 3d vector', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_vector3f', 'vector3f', 0, None, 'This is an attribute interpreted as a single-precision 3d vector', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_vector3h', 'vector3h', 0, None, 'This is an attribute interpreted as a half-precision 3d vector', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('outputs:a_color3d', 'color3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d color', {}, True, None, False, ''),
('outputs:a_color3f', 'color3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d color', {}, True, None, False, ''),
('outputs:a_color3h', 'color3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d color', {}, True, None, False, ''),
('outputs:a_color4d', 'color4d', 0, None, 'This is a computed attribute interpreted as a double-precision 4d color', {}, True, None, False, ''),
('outputs:a_color4f', 'color4f', 0, None, 'This is a computed attribute interpreted as a single-precision 4d color', {}, True, None, False, ''),
('outputs:a_color4h', 'color4h', 0, None, 'This is a computed attribute interpreted as a half-precision 4d color', {}, True, None, False, ''),
('outputs:a_frame', 'frame4d', 0, None, 'This is a computed attribute interpreted as a coordinate frame', {}, True, None, False, ''),
('outputs:a_matrix2d', 'matrix2d', 0, None, 'This is a computed attribute interpreted as a double-precision 2d matrix', {}, True, None, False, ''),
('outputs:a_matrix3d', 'matrix3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d matrix', {}, True, None, False, ''),
('outputs:a_matrix4d', 'matrix4d', 0, None, 'This is a computed attribute interpreted as a double-precision 4d matrix', {}, True, None, False, ''),
('outputs:a_normal3d', 'normal3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d normal', {}, True, None, False, ''),
('outputs:a_normal3f', 'normal3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d normal', {}, True, None, False, ''),
('outputs:a_normal3h', 'normal3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d normal', {}, True, None, False, ''),
('outputs:a_point3d', 'point3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d point', {}, True, None, False, ''),
('outputs:a_point3f', 'point3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d point', {}, True, None, False, ''),
('outputs:a_point3h', 'point3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d point', {}, True, None, False, ''),
('outputs:a_quatd', 'quatd', 0, None, 'This is a computed attribute interpreted as a double-precision 4d quaternion', {}, True, None, False, ''),
('outputs:a_quatf', 'quatf', 0, None, 'This is a computed attribute interpreted as a single-precision 4d quaternion', {}, True, None, False, ''),
('outputs:a_quath', 'quath', 0, None, 'This is a computed attribute interpreted as a half-precision 4d quaternion', {}, True, None, False, ''),
('outputs:a_texcoord2d', 'texCoord2d', 0, None, 'This is a computed attribute interpreted as a double-precision 2d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord2f', 'texCoord2f', 0, None, 'This is a computed attribute interpreted as a single-precision 2d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord2h', 'texCoord2h', 0, None, 'This is a computed attribute interpreted as a half-precision 2d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord3d', 'texCoord3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord3f', 'texCoord3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord3h', 'texCoord3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d texcoord', {}, True, None, False, ''),
('outputs:a_timecode', 'timecode', 0, None, 'This is a computed attribute interpreted as a timecode', {}, True, None, False, ''),
('outputs:a_vector3d', 'vector3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d vector', {}, True, None, False, ''),
('outputs:a_vector3f', 'vector3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d vector', {}, True, None, False, ''),
('outputs:a_vector3h', 'vector3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d vector', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.a_color3d = og.AttributeRole.COLOR
role_data.inputs.a_color3f = og.AttributeRole.COLOR
role_data.inputs.a_color3h = og.AttributeRole.COLOR
role_data.inputs.a_color4d = og.AttributeRole.COLOR
role_data.inputs.a_color4f = og.AttributeRole.COLOR
role_data.inputs.a_color4h = og.AttributeRole.COLOR
role_data.inputs.a_frame = og.AttributeRole.FRAME
role_data.inputs.a_matrix2d = og.AttributeRole.MATRIX
role_data.inputs.a_matrix3d = og.AttributeRole.MATRIX
role_data.inputs.a_matrix4d = og.AttributeRole.MATRIX
role_data.inputs.a_normal3d = og.AttributeRole.NORMAL
role_data.inputs.a_normal3f = og.AttributeRole.NORMAL
role_data.inputs.a_normal3h = og.AttributeRole.NORMAL
role_data.inputs.a_point3d = og.AttributeRole.POSITION
role_data.inputs.a_point3f = og.AttributeRole.POSITION
role_data.inputs.a_point3h = og.AttributeRole.POSITION
role_data.inputs.a_quatd = og.AttributeRole.QUATERNION
role_data.inputs.a_quatf = og.AttributeRole.QUATERNION
role_data.inputs.a_quath = og.AttributeRole.QUATERNION
role_data.inputs.a_texcoord2d = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord2f = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord2h = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord3d = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord3f = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord3h = og.AttributeRole.TEXCOORD
role_data.inputs.a_timecode = og.AttributeRole.TIMECODE
role_data.inputs.a_vector3d = og.AttributeRole.VECTOR
role_data.inputs.a_vector3f = og.AttributeRole.VECTOR
role_data.inputs.a_vector3h = og.AttributeRole.VECTOR
role_data.outputs.a_color3d = og.AttributeRole.COLOR
role_data.outputs.a_color3f = og.AttributeRole.COLOR
role_data.outputs.a_color3h = og.AttributeRole.COLOR
role_data.outputs.a_color4d = og.AttributeRole.COLOR
role_data.outputs.a_color4f = og.AttributeRole.COLOR
role_data.outputs.a_color4h = og.AttributeRole.COLOR
role_data.outputs.a_frame = og.AttributeRole.FRAME
role_data.outputs.a_matrix2d = og.AttributeRole.MATRIX
role_data.outputs.a_matrix3d = og.AttributeRole.MATRIX
role_data.outputs.a_matrix4d = og.AttributeRole.MATRIX
role_data.outputs.a_normal3d = og.AttributeRole.NORMAL
role_data.outputs.a_normal3f = og.AttributeRole.NORMAL
role_data.outputs.a_normal3h = og.AttributeRole.NORMAL
role_data.outputs.a_point3d = og.AttributeRole.POSITION
role_data.outputs.a_point3f = og.AttributeRole.POSITION
role_data.outputs.a_point3h = og.AttributeRole.POSITION
role_data.outputs.a_quatd = og.AttributeRole.QUATERNION
role_data.outputs.a_quatf = og.AttributeRole.QUATERNION
role_data.outputs.a_quath = og.AttributeRole.QUATERNION
role_data.outputs.a_texcoord2d = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord2f = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord2h = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord3d = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord3f = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord3h = og.AttributeRole.TEXCOORD
role_data.outputs.a_timecode = og.AttributeRole.TIMECODE
role_data.outputs.a_vector3d = og.AttributeRole.VECTOR
role_data.outputs.a_vector3f = og.AttributeRole.VECTOR
role_data.outputs.a_vector3h = og.AttributeRole.VECTOR
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def a_color3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
return data_view.get()
@a_color3d.setter
def a_color3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color3d)
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
data_view.set(value)
@property
def a_color3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
return data_view.get()
@a_color3f.setter
def a_color3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color3f)
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
data_view.set(value)
@property
def a_color3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
return data_view.get()
@a_color3h.setter
def a_color3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color3h)
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
data_view.set(value)
@property
def a_color4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
return data_view.get()
@a_color4d.setter
def a_color4d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color4d)
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
data_view.set(value)
@property
def a_color4f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
return data_view.get()
@a_color4f.setter
def a_color4f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color4f)
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
data_view.set(value)
@property
def a_color4h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
return data_view.get()
@a_color4h.setter
def a_color4h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color4h)
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
data_view.set(value)
@property
def a_frame(self):
data_view = og.AttributeValueHelper(self._attributes.a_frame)
return data_view.get()
@a_frame.setter
def a_frame(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_frame)
data_view = og.AttributeValueHelper(self._attributes.a_frame)
data_view.set(value)
@property
def a_matrix2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
return data_view.get()
@a_matrix2d.setter
def a_matrix2d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix2d)
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
data_view.set(value)
@property
def a_matrix3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
return data_view.get()
@a_matrix3d.setter
def a_matrix3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix3d)
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
data_view.set(value)
@property
def a_matrix4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
return data_view.get()
@a_matrix4d.setter
def a_matrix4d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix4d)
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
data_view.set(value)
@property
def a_normal3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
return data_view.get()
@a_normal3d.setter
def a_normal3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_normal3d)
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
data_view.set(value)
@property
def a_normal3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
return data_view.get()
@a_normal3f.setter
def a_normal3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_normal3f)
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
data_view.set(value)
@property
def a_normal3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
return data_view.get()
@a_normal3h.setter
def a_normal3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_normal3h)
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
data_view.set(value)
@property
def a_point3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
return data_view.get()
@a_point3d.setter
def a_point3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_point3d)
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
data_view.set(value)
@property
def a_point3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
return data_view.get()
@a_point3f.setter
def a_point3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_point3f)
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
data_view.set(value)
@property
def a_point3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
return data_view.get()
@a_point3h.setter
def a_point3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_point3h)
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
data_view.set(value)
@property
def a_quatd(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
return data_view.get()
@a_quatd.setter
def a_quatd(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_quatd)
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
data_view.set(value)
@property
def a_quatf(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
return data_view.get()
@a_quatf.setter
def a_quatf(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_quatf)
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
data_view.set(value)
@property
def a_quath(self):
data_view = og.AttributeValueHelper(self._attributes.a_quath)
return data_view.get()
@a_quath.setter
def a_quath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_quath)
data_view = og.AttributeValueHelper(self._attributes.a_quath)
data_view.set(value)
@property
def a_texcoord2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
return data_view.get()
@a_texcoord2d.setter
def a_texcoord2d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord2d)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
data_view.set(value)
@property
def a_texcoord2f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
return data_view.get()
@a_texcoord2f.setter
def a_texcoord2f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord2f)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
data_view.set(value)
@property
def a_texcoord2h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
return data_view.get()
@a_texcoord2h.setter
def a_texcoord2h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord2h)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
data_view.set(value)
@property
def a_texcoord3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
return data_view.get()
@a_texcoord3d.setter
def a_texcoord3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord3d)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
data_view.set(value)
@property
def a_texcoord3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
return data_view.get()
@a_texcoord3f.setter
def a_texcoord3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord3f)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
data_view.set(value)
@property
def a_texcoord3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
return data_view.get()
@a_texcoord3h.setter
def a_texcoord3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord3h)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
data_view.set(value)
@property
def a_timecode(self):
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
return data_view.get()
@a_timecode.setter
def a_timecode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_timecode)
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
data_view.set(value)
@property
def a_vector3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
return data_view.get()
@a_vector3d.setter
def a_vector3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_vector3d)
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
data_view.set(value)
@property
def a_vector3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
return data_view.get()
@a_vector3f.setter
def a_vector3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_vector3f)
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
data_view.set(value)
@property
def a_vector3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
return data_view.get()
@a_vector3h.setter
def a_vector3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_vector3h)
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def a_color3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
return data_view.get()
@a_color3d.setter
def a_color3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
data_view.set(value)
@property
def a_color3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
return data_view.get()
@a_color3f.setter
def a_color3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
data_view.set(value)
@property
def a_color3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
return data_view.get()
@a_color3h.setter
def a_color3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
data_view.set(value)
@property
def a_color4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
return data_view.get()
@a_color4d.setter
def a_color4d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
data_view.set(value)
@property
def a_color4f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
return data_view.get()
@a_color4f.setter
def a_color4f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
data_view.set(value)
@property
def a_color4h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
return data_view.get()
@a_color4h.setter
def a_color4h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
data_view.set(value)
@property
def a_frame(self):
data_view = og.AttributeValueHelper(self._attributes.a_frame)
return data_view.get()
@a_frame.setter
def a_frame(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_frame)
data_view.set(value)
@property
def a_matrix2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
return data_view.get()
@a_matrix2d.setter
def a_matrix2d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
data_view.set(value)
@property
def a_matrix3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
return data_view.get()
@a_matrix3d.setter
def a_matrix3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
data_view.set(value)
@property
def a_matrix4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
return data_view.get()
@a_matrix4d.setter
def a_matrix4d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
data_view.set(value)
@property
def a_normal3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
return data_view.get()
@a_normal3d.setter
def a_normal3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
data_view.set(value)
@property
def a_normal3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
return data_view.get()
@a_normal3f.setter
def a_normal3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
data_view.set(value)
@property
def a_normal3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
return data_view.get()
@a_normal3h.setter
def a_normal3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
data_view.set(value)
@property
def a_point3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
return data_view.get()
@a_point3d.setter
def a_point3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
data_view.set(value)
@property
def a_point3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
return data_view.get()
@a_point3f.setter
def a_point3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
data_view.set(value)
@property
def a_point3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
return data_view.get()
@a_point3h.setter
def a_point3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
data_view.set(value)
@property
def a_quatd(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
return data_view.get()
@a_quatd.setter
def a_quatd(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
data_view.set(value)
@property
def a_quatf(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
return data_view.get()
@a_quatf.setter
def a_quatf(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
data_view.set(value)
@property
def a_quath(self):
data_view = og.AttributeValueHelper(self._attributes.a_quath)
return data_view.get()
@a_quath.setter
def a_quath(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_quath)
data_view.set(value)
@property
def a_texcoord2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
return data_view.get()
@a_texcoord2d.setter
def a_texcoord2d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
data_view.set(value)
@property
def a_texcoord2f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
return data_view.get()
@a_texcoord2f.setter
def a_texcoord2f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
data_view.set(value)
@property
def a_texcoord2h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
return data_view.get()
@a_texcoord2h.setter
def a_texcoord2h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
data_view.set(value)
@property
def a_texcoord3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
return data_view.get()
@a_texcoord3d.setter
def a_texcoord3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
data_view.set(value)
@property
def a_texcoord3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
return data_view.get()
@a_texcoord3f.setter
def a_texcoord3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
data_view.set(value)
@property
def a_texcoord3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
return data_view.get()
@a_texcoord3h.setter
def a_texcoord3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
data_view.set(value)
@property
def a_timecode(self):
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
return data_view.get()
@a_timecode.setter
def a_timecode(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
data_view.set(value)
@property
def a_vector3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
return data_view.get()
@a_vector3d.setter
def a_vector3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
data_view.set(value)
@property
def a_vector3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
return data_view.get()
@a_vector3f.setter
def a_vector3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
data_view.set(value)
@property
def a_vector3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
return data_view.get()
@a_vector3h.setter
def a_vector3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialRoleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialRoleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialRoleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 42,891 | Python | 46.446903 | 346 | 0.616936 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTokensPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.TokensPy
This is a tutorial node. It exercises the feature of providing hardcoded token values in the database after a node type has
been initialized. It sets output booleans to the truth value of whether corresponding inputs appear in the hardcoded token
list.
"""
import carb
import numpy
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialTokensPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.TokensPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.valuesToCheck
Outputs:
outputs.isColor
Predefined Tokens:
tokens.red
tokens.green
tokens.blue
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:valuesToCheck', 'token[]', 0, None, 'Array of tokens that are to be checked', {}, True, [], False, ''),
('outputs:isColor', 'bool[]', 0, None, 'True values if the corresponding input value appears in the token list', {}, True, None, False, ''),
])
class tokens:
red = "red"
green = "green"
blue = "blue"
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def valuesToCheck(self):
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
return data_view.get()
@valuesToCheck.setter
def valuesToCheck(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.valuesToCheck)
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
data_view.set(value)
self.valuesToCheck_size = data_view.get_array_size()
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.isColor_size = None
self._batchedWriteValues = { }
@property
def isColor(self):
data_view = og.AttributeValueHelper(self._attributes.isColor)
return data_view.get(reserved_element_count=self.isColor_size)
@isColor.setter
def isColor(self, value):
data_view = og.AttributeValueHelper(self._attributes.isColor)
data_view.set(value)
self.isColor_size = data_view.get_array_size()
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialTokensPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTokensPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTokensPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.TokensPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialTokensPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialTokensPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialTokensPyDatabase(node)
try:
compute_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialTokensPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialTokensPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialTokensPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialTokensPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Tokens")
node_type.set_metadata(ogn.MetadataKeys.TOKENS, "[\"red\", \"green\", \"blue\"]")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises the feature of providing hardcoded token values in the database after a node type has been initialized. It sets output booleans to the truth value of whether corresponding inputs appear in the hardcoded token list.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.TokensPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialTokensPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialTokensPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.TokensPy")
| 11,282 | Python | 46.407563 | 324 | 0.649885 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialOverrideTypeDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.OverrideType
This is a tutorial node. It has an input and output of type float[3], an input and output of type double[3], and a type override
specification that lets the node use Carbonite types for the generated data on the float[3] attributes only. Ordinarily all
of the types would be defined in a seperate configuration file so that it can be shared for a project. In that case the type
definition build flag would also be used so that this information does not have to be embedded in every .ogn file in the
project. It is placed directly in the file here solely for instructional purposes. The compute is just a rotation of components
from x->y, y->z, and z->x, for each input type.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialOverrideTypeDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.OverrideType
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.data
inputs.typedData
Outputs:
outputs.data
outputs.typedData
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:data', 'double3', 0, 'Input value with a standard double type', 'The value to rotate', {}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:typedData', 'float3', 0, 'Input value with a modified float type', 'The value to rotate', {}, True, [0.0, 0.0, 0.0], False, ''),
('outputs:data', 'double3', 0, 'Output value with a standard double type', 'The rotated version of inputs::data', {}, True, None, False, ''),
('outputs:typedData', 'float3', 0, 'Output value with a modified float type', 'The rotated version of inputs::typedData', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def data(self):
data_view = og.AttributeValueHelper(self._attributes.data)
return data_view.get()
@data.setter
def data(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.data)
data_view = og.AttributeValueHelper(self._attributes.data)
data_view.set(value)
@property
def typedData(self):
data_view = og.AttributeValueHelper(self._attributes.typedData)
return data_view.get()
@typedData.setter
def typedData(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.typedData)
data_view = og.AttributeValueHelper(self._attributes.typedData)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def data(self):
data_view = og.AttributeValueHelper(self._attributes.data)
return data_view.get()
@data.setter
def data(self, value):
data_view = og.AttributeValueHelper(self._attributes.data)
data_view.set(value)
@property
def typedData(self):
data_view = og.AttributeValueHelper(self._attributes.typedData)
return data_view.get()
@typedData.setter
def typedData(self, value):
data_view = og.AttributeValueHelper(self._attributes.typedData)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialOverrideTypeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialOverrideTypeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialOverrideTypeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,869 | Python | 47.380281 | 157 | 0.669675 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundleDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleData
This is a tutorial node. It exercises functionality for access of data within bundle attributes.
"""
import carb
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialBundleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.bundle
Outputs:
outputs.bundle
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:bundle', 'bundle', 0, 'Input Bundle', 'Bundle whose contents are modified for passing to the output', {}, True, None, False, ''),
('outputs:bundle', 'bundle', 0, None, 'This is the bundle with values of known types doubled.', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.bundle = og.AttributeRole.BUNDLE
role_data.outputs.bundle = og.AttributeRole.BUNDLE
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.bundle"""
return self.__bundles.bundle
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.bundle"""
return self.__bundles.bundle
@bundle.setter
def bundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.bundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.bundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialBundleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,724 | Python | 48.353448 | 146 | 0.677324 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialEmptyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.Empty
This is a tutorial node. It does absolutely nothing and is only meant to serve as an example to use for setting up your
build.
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialEmptyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.Empty
Class Members:
node: Node being evaluated
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialEmptyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialEmptyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialEmptyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 4,018 | Python | 48.617283 | 120 | 0.696615 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialStateDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.State
This is a tutorial node. It makes use of internal state information to continuously increment an output.
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialStateDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.State
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.override
inputs.overrideValue
Outputs:
outputs.monotonic
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:override', 'bool', 0, 'Enable Override', 'When true get the output from the overrideValue, otherwise use the internal value', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:overrideValue', 'int64', 0, 'Override Value', "Value to use instead of the monotonically increasing internal one when 'override' is true", {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:monotonic', 'int64', 0, 'State-Based Output', 'Monotonically increasing output, set by internal state information', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def override(self):
data_view = og.AttributeValueHelper(self._attributes.override)
return data_view.get()
@override.setter
def override(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.override)
data_view = og.AttributeValueHelper(self._attributes.override)
data_view.set(value)
@property
def overrideValue(self):
data_view = og.AttributeValueHelper(self._attributes.overrideValue)
return data_view.get()
@overrideValue.setter
def overrideValue(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.overrideValue)
data_view = og.AttributeValueHelper(self._attributes.overrideValue)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def monotonic(self):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
return data_view.get()
@monotonic.setter
def monotonic(self, value):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,974 | Python | 47.185483 | 209 | 0.67392 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialDynamicAttributesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.DynamicAttributes
This is a C++ node that exercises the ability to add and remove database attribute accessors for dynamic attributes. When
the dynamic attribute is added the property will exist and be able to get/set the attribute values. When it does not the
property will not exist. The dynamic attribute names are found in the tokens below. If neither exist then the input value
is copied to the output directly. If 'firstBit' exists then the 'firstBit'th bit of the input is x-ored for the copy. If
'secondBit' exists then the 'secondBit'th bit of the input is x-ored for the copy. (Recall bitwise match xor(0,0)=0, xor(0,1)=1,
xor(1,0)=1, and xor(1,1)=0.) For example, if 'firstBit' is present and set to 1 then the bitmask will be b0010, where bit
1 is set. If the input is 7, or b0111, then the xor operation will flip bit 1, yielding b0101, or 5 as the result. If on
the next run 'secondBit' is also present and set to 2 then its bitmask will be b0100, where bit 2 is set. The input of 7
(b0111) flips bit 1 because firstBit=1 and flips bit 2 because secondBit=2, yielding a final result of 1 (b0001).
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialDynamicAttributesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.DynamicAttributes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.value
Outputs:
outputs.result
Predefined Tokens:
tokens.firstBit
tokens.secondBit
tokens.invert
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:value', 'uint', 0, None, 'Original value to be modified.', {}, True, 0, False, ''),
('outputs:result', 'uint', 0, None, 'Modified value', {}, True, None, False, ''),
])
class tokens:
firstBit = "inputs:firstBit"
secondBit = "inputs:secondBit"
invert = "inputs:invert"
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.value)
data_view = og.AttributeValueHelper(self._attributes.value)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def result(self):
data_view = og.AttributeValueHelper(self._attributes.result)
return data_view.get()
@result.setter
def result(self, value):
data_view = og.AttributeValueHelper(self._attributes.result)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialDynamicAttributesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialDynamicAttributesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialDynamicAttributesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,314 | Python | 48.335937 | 128 | 0.684194 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCudaDataCpuPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CudaCpuArraysPy
This is a tutorial node. It illustrates the alternative method of extracting pointers to GPU array data in which the pointer
returned is a CPU pointer and can be dereferenced on the CPU side. Without the cudaPointers value set that pointer would
be a GPU pointer to an array of GPU pointers and could only be dereferenced on the device. Both plain attribute and bundle
attribute extraction are shown.
"""
import carb
import numpy
import sys
import traceback
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCudaDataCpuPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CudaCpuArraysPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.multiplier
inputs.points
Outputs:
outputs.outBundle
outputs.points
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:multiplier', 'float3', 0, None, 'Amplitude of the expansion for the input points', {ogn.MetadataKeys.DEFAULT: '[1.0, 1.0, 1.0]'}, True, [1.0, 1.0, 1.0], False, ''),
('inputs:points', 'float3[]', 0, None, 'Array of points to be moved', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:outBundle', 'bundle', 0, None, 'Bundle containing a copy of the output points', {ogn.MetadataKeys.MEMORY_TYPE: 'any'}, True, None, False, ''),
('outputs:points', 'float3[]', 0, None, 'Final positions of points', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.outputs.outBundle = og.AttributeRole.BUNDLE
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def multiplier(self):
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
return data_view.get(on_gpu=True)
@multiplier.setter
def multiplier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.multiplier)
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
data_view.set(value, on_gpu=True)
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
return data_view.get(on_gpu=True)
@points.setter
def points(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.points)
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
data_view.set(value, on_gpu=True)
self.points_size = data_view.get_array_size()
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, ['outputs_outBundle'], read_only=False, gpu_ptr_kinds={"outputs_outBundle": og.PtrToPtrKind.CPU})
self.points_size = None
self._batchedWriteValues = { }
@property
def outBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.outBundle"""
return self.__bundles.outBundle
@outBundle.setter
def outBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.outBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.outBundle.bundle = bundle
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
return data_view.get(reserved_element_count=self.points_size, on_gpu=True)
@points.setter
def points(self, value):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
data_view.set(value, on_gpu=True)
self.points_size = data_view.get_array_size()
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialCudaDataCpuPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCudaDataCpuPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCudaDataCpuPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialCudaDataCpuPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.CudaCpuArraysPy'
@staticmethod
def compute(context, node):
def database_valid():
if not db.outputs.outBundle.valid:
db.log_error('Required bundle outputs.outBundle is invalid, compute skipped')
return False
return True
try:
per_node_data = OgnTutorialCudaDataCpuPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialCudaDataCpuPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialCudaDataCpuPyDatabase(node)
try:
compute_function = getattr(OgnTutorialCudaDataCpuPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialCudaDataCpuPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialCudaDataCpuPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialCudaDataCpuPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialCudaDataCpuPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialCudaDataCpuPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialCudaDataCpuPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialCudaDataCpuPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialCudaDataCpuPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialCudaDataCpuPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.MEMORY_TYPE, "cuda")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Python Tutorial Node: Attributes With CUDA Array Pointers In Cpu Memory")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It illustrates the alternative method of extracting pointers to GPU array data in which the pointer returned is a CPU pointer and can be dereferenced on the CPU side. Without the cudaPointers value set that pointer would be a GPU pointer to an array of GPU pointers and could only be dereferenced on the device. Both plain attribute and bundle attribute extraction are shown.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
node_type.set_metadata(ogn.MetadataKeys.MEMORY_TYPE, "cuda")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.CudaCpuArraysPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialCudaDataCpuPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialCudaDataCpuPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialCudaDataCpuPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialCudaDataCpuPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.CudaCpuArraysPy")
| 14,034 | Python | 49.851449 | 472 | 0.654339 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialDefaultsDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.Defaults
This is a tutorial node. It will move the values of inputs to corresponding outputs. Inputs all have unspecified, and therefore
empty, default values.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialDefaultsDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.Defaults
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_array
inputs.a_bool
inputs.a_double
inputs.a_float
inputs.a_half
inputs.a_int
inputs.a_int2
inputs.a_int64
inputs.a_matrix
inputs.a_string
inputs.a_token
inputs.a_uchar
inputs.a_uint
inputs.a_uint64
Outputs:
outputs.a_array
outputs.a_bool
outputs.a_double
outputs.a_float
outputs.a_half
outputs.a_int
outputs.a_int2
outputs.a_int64
outputs.a_matrix
outputs.a_string
outputs.a_token
outputs.a_uchar
outputs.a_uint
outputs.a_uint64
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a_array', 'float[]', 0, None, 'This is an attribute of type array of floats', {}, True, [], False, ''),
('inputs:a_bool', 'bool', 0, None, 'This is an attribute of type boolean', {}, True, False, False, ''),
('inputs:a_double', 'double', 0, None, 'This is an attribute of type 64 bit floating point', {}, True, 0.0, False, ''),
('inputs:a_float', 'float', 0, None, 'This is an attribute of type 32 bit floating point', {}, True, 0.0, False, ''),
('inputs:a_half', 'half', 0, None, 'This is an attribute of type 16 bit floating point', {}, True, 0.0, False, ''),
('inputs:a_int', 'int', 0, None, 'This is an attribute of type 32 bit integer', {}, True, 0, False, ''),
('inputs:a_int2', 'int2', 0, None, 'This is an attribute of type 2-tuple of integers', {}, True, [0, 0], False, ''),
('inputs:a_int64', 'int64', 0, None, 'This is an attribute of type 64 bit integer', {}, True, 0, False, ''),
('inputs:a_matrix', 'matrix2d', 0, None, 'This is an attribute of type 2x2 matrix', {}, True, [[1.0, 0.0], [0.0, 1.0]], False, ''),
('inputs:a_string', 'string', 0, None, 'This is an attribute of type string', {}, True, "", False, ''),
('inputs:a_token', 'token', 0, None, 'This is an attribute of type interned string with fast comparison and hashing', {}, True, "", False, ''),
('inputs:a_uchar', 'uchar', 0, None, 'This is an attribute of type unsigned 8 bit integer', {}, True, 0, False, ''),
('inputs:a_uint', 'uint', 0, None, 'This is an attribute of type unsigned 32 bit integer', {}, True, 0, False, ''),
('inputs:a_uint64', 'uint64', 0, None, 'This is an attribute of type unsigned 64 bit integer', {}, True, 0, False, ''),
('outputs:a_array', 'float[]', 0, None, 'This is a computed attribute of type array of floats', {}, True, None, False, ''),
('outputs:a_bool', 'bool', 0, None, 'This is a computed attribute of type boolean', {}, True, None, False, ''),
('outputs:a_double', 'double', 0, None, 'This is a computed attribute of type 64 bit floating point', {}, True, None, False, ''),
('outputs:a_float', 'float', 0, None, 'This is a computed attribute of type 32 bit floating point', {}, True, None, False, ''),
('outputs:a_half', 'half', 0, None, 'This is a computed attribute of type 16 bit floating point', {}, True, None, False, ''),
('outputs:a_int', 'int', 0, None, 'This is a computed attribute of type 32 bit integer', {}, True, None, False, ''),
('outputs:a_int2', 'int2', 0, None, 'This is a computed attribute of type 2-tuple of integers', {}, True, None, False, ''),
('outputs:a_int64', 'int64', 0, None, 'This is a computed attribute of type 64 bit integer', {}, True, None, False, ''),
('outputs:a_matrix', 'matrix2d', 0, None, 'This is a computed attribute of type 2x2 matrix', {}, True, None, False, ''),
('outputs:a_string', 'string', 0, None, 'This is a computed attribute of type string', {}, True, None, False, ''),
('outputs:a_token', 'token', 0, None, 'This is a computed attribute of type interned string with fast comparison and hashing', {}, True, None, False, ''),
('outputs:a_uchar', 'uchar', 0, None, 'This is a computed attribute of type unsigned 8 bit integer', {}, True, None, False, ''),
('outputs:a_uint', 'uint', 0, None, 'This is a computed attribute of type unsigned 32 bit integer', {}, True, None, False, ''),
('outputs:a_uint64', 'uint64', 0, None, 'This is a computed attribute of type unsigned 64 bit integer', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.a_matrix = og.AttributeRole.MATRIX
role_data.inputs.a_string = og.AttributeRole.TEXT
role_data.outputs.a_matrix = og.AttributeRole.MATRIX
role_data.outputs.a_string = og.AttributeRole.TEXT
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def a_array(self):
data_view = og.AttributeValueHelper(self._attributes.a_array)
return data_view.get()
@a_array.setter
def a_array(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_array)
data_view = og.AttributeValueHelper(self._attributes.a_array)
data_view.set(value)
self.a_array_size = data_view.get_array_size()
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_bool)
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double)
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float)
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_half)
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int)
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int2)
data_view = og.AttributeValueHelper(self._attributes.a_int2)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int64)
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_matrix(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
return data_view.get()
@a_matrix.setter
def a_matrix(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix)
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
data_view.set(value)
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get()
@a_string.setter
def a_string(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_string)
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_token)
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
return data_view.get()
@a_uchar.setter
def a_uchar(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_uchar)
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
data_view.set(value)
@property
def a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint)
return data_view.get()
@a_uint.setter
def a_uint(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_uint)
data_view = og.AttributeValueHelper(self._attributes.a_uint)
data_view.set(value)
@property
def a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
return data_view.get()
@a_uint64.setter
def a_uint64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_uint64)
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.a_array_size = None
self.a_string_size = None
self._batchedWriteValues = { }
@property
def a_array(self):
data_view = og.AttributeValueHelper(self._attributes.a_array)
return data_view.get(reserved_element_count=self.a_array_size)
@a_array.setter
def a_array(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_array)
data_view.set(value)
self.a_array_size = data_view.get_array_size()
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_matrix(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
return data_view.get()
@a_matrix.setter
def a_matrix(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
data_view.set(value)
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get(reserved_element_count=self.a_string_size)
@a_string.setter
def a_string(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
return data_view.get()
@a_uchar.setter
def a_uchar(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
data_view.set(value)
@property
def a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint)
return data_view.get()
@a_uint.setter
def a_uint(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_uint)
data_view.set(value)
@property
def a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
return data_view.get()
@a_uint64.setter
def a_uint64(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialDefaultsDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialDefaultsDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialDefaultsDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 19,763 | Python | 41.412017 | 162 | 0.601882 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialComplexDataPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ComplexDataPy
This is a tutorial node written in Python. It will compute the point3f array by multiplying each element of the float array
by the three element vector in the multiplier.
"""
import carb
import numpy
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialComplexDataPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ComplexDataPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_inputArray
inputs.a_vectorMultiplier
Outputs:
outputs.a_productArray
outputs.a_tokenArray
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a_inputArray', 'float[]', 0, None, 'Input array', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:a_vectorMultiplier', 'float3', 0, None, 'Vector multiplier', {ogn.MetadataKeys.DEFAULT: '[1.0, 2.0, 3.0]'}, True, [1.0, 2.0, 3.0], False, ''),
('outputs:a_productArray', 'point3f[]', 0, None, 'Output array', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:a_tokenArray', 'token[]', 0, None, 'String representations of the input array', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.outputs.a_productArray = og.AttributeRole.POSITION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"a_vectorMultiplier", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.a_vectorMultiplier]
self._batchedReadValues = [[1.0, 2.0, 3.0]]
@property
def a_inputArray(self):
data_view = og.AttributeValueHelper(self._attributes.a_inputArray)
return data_view.get()
@a_inputArray.setter
def a_inputArray(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_inputArray)
data_view = og.AttributeValueHelper(self._attributes.a_inputArray)
data_view.set(value)
self.a_inputArray_size = data_view.get_array_size()
@property
def a_vectorMultiplier(self):
return self._batchedReadValues[0]
@a_vectorMultiplier.setter
def a_vectorMultiplier(self, value):
self._batchedReadValues[0] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.a_productArray_size = 0
self.a_tokenArray_size = None
self._batchedWriteValues = { }
@property
def a_productArray(self):
data_view = og.AttributeValueHelper(self._attributes.a_productArray)
return data_view.get(reserved_element_count=self.a_productArray_size)
@a_productArray.setter
def a_productArray(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_productArray)
data_view.set(value)
self.a_productArray_size = data_view.get_array_size()
@property
def a_tokenArray(self):
data_view = og.AttributeValueHelper(self._attributes.a_tokenArray)
return data_view.get(reserved_element_count=self.a_tokenArray_size)
@a_tokenArray.setter
def a_tokenArray(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_tokenArray)
data_view.set(value)
self.a_tokenArray_size = data_view.get_array_size()
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialComplexDataPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialComplexDataPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialComplexDataPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialComplexDataPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.ComplexDataPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialComplexDataPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialComplexDataPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialComplexDataPyDatabase(node)
try:
compute_function = getattr(OgnTutorialComplexDataPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialComplexDataPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialComplexDataPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialComplexDataPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialComplexDataPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialComplexDataPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialComplexDataPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialComplexDataPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialComplexDataPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialComplexDataPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Attributes With Arrays of Tuples")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node written in Python. It will compute the point3f array by multiplying each element of the float array by the three element vector in the multiplier.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.ComplexDataPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialComplexDataPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialComplexDataPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialComplexDataPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialComplexDataPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.ComplexDataPy")
| 13,000 | Python | 47.330855 | 242 | 0.646615 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundleAddAttributesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleAddAttributesPy
This is a Python tutorial node. It exercises functionality for adding and removing attributes on output bundles.
"""
import carb
import numpy
import sys
import traceback
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialBundleAddAttributesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleAddAttributesPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.addedAttributeNames
inputs.removedAttributeNames
inputs.typesToAdd
inputs.useBatchedAPI
Outputs:
outputs.bundle
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:addedAttributeNames', 'token[]', 0, None, "Names for the attribute types to be added. The size of this array must match the size\nof the 'typesToAdd' array to be legal.", {}, True, [], False, ''),
('inputs:removedAttributeNames', 'token[]', 0, None, 'Names for the attribute types to be removed. Non-existent attributes will be ignored.', {}, True, [], False, ''),
('inputs:typesToAdd', 'token[]', 0, 'Attribute Types To Add', 'List of type descriptions to add to the bundle. The strings in this list correspond to the\nstrings that represent the attribute types in the .ogn file (e.g. float[3][], colord[3], bool', {}, True, [], False, ''),
('inputs:useBatchedAPI', 'bool', 0, None, 'Controls whether or not to used batched APIS for adding/removing attributes', {}, True, False, False, ''),
('outputs:bundle', 'bundle', 0, 'Constructed Bundle', 'This is the bundle with all attributes added by compute.', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.outputs.bundle = og.AttributeRole.BUNDLE
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"useBatchedAPI", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.useBatchedAPI]
self._batchedReadValues = [False]
@property
def addedAttributeNames(self):
data_view = og.AttributeValueHelper(self._attributes.addedAttributeNames)
return data_view.get()
@addedAttributeNames.setter
def addedAttributeNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.addedAttributeNames)
data_view = og.AttributeValueHelper(self._attributes.addedAttributeNames)
data_view.set(value)
self.addedAttributeNames_size = data_view.get_array_size()
@property
def removedAttributeNames(self):
data_view = og.AttributeValueHelper(self._attributes.removedAttributeNames)
return data_view.get()
@removedAttributeNames.setter
def removedAttributeNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.removedAttributeNames)
data_view = og.AttributeValueHelper(self._attributes.removedAttributeNames)
data_view.set(value)
self.removedAttributeNames_size = data_view.get_array_size()
@property
def typesToAdd(self):
data_view = og.AttributeValueHelper(self._attributes.typesToAdd)
return data_view.get()
@typesToAdd.setter
def typesToAdd(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.typesToAdd)
data_view = og.AttributeValueHelper(self._attributes.typesToAdd)
data_view.set(value)
self.typesToAdd_size = data_view.get_array_size()
@property
def useBatchedAPI(self):
return self._batchedReadValues[0]
@useBatchedAPI.setter
def useBatchedAPI(self, value):
self._batchedReadValues[0] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.bundle"""
return self.__bundles.bundle
@bundle.setter
def bundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.bundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.bundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialBundleAddAttributesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundleAddAttributesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundleAddAttributesPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialBundleAddAttributesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.BundleAddAttributesPy'
@staticmethod
def compute(context, node):
def database_valid():
if not db.outputs.bundle.valid:
db.log_error('Required bundle outputs.bundle is invalid, compute skipped')
return False
return True
try:
per_node_data = OgnTutorialBundleAddAttributesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialBundleAddAttributesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialBundleAddAttributesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialBundleAddAttributesPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialBundleAddAttributesPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialBundleAddAttributesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialBundleAddAttributesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialBundleAddAttributesPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialBundleAddAttributesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialBundleAddAttributesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialBundleAddAttributesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialBundleAddAttributesPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialBundleAddAttributesPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Bundle Add Attributes")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a Python tutorial node. It exercises functionality for adding and removing attributes on output bundles.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.BundleAddAttributesPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialBundleAddAttributesPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialBundleAddAttributesPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialBundleAddAttributesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialBundleAddAttributesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.BundleAddAttributesPy")
| 14,503 | Python | 49.186851 | 284 | 0.654485 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialABIPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.AbiPy
This tutorial node shows how to override ABI methods on your Python node. The algorithm of the node converts an RGB color
into HSV components.
"""
import carb
import numpy
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialABIPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.AbiPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.color
Outputs:
outputs.h
outputs.s
outputs.v
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:color', 'color3d', 0, 'Color To Convert', 'The color to be converted', {'multipleValues': 'value1,value2,value3', ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('outputs:h', 'double', 0, None, 'The hue component of the input color', {}, True, None, False, ''),
('outputs:s', 'double', 0, None, 'The saturation component of the input color', {}, True, None, False, ''),
('outputs:v', 'double', 0, None, 'The value component of the input color', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.color = og.AttributeRole.COLOR
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"color", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.color]
self._batchedReadValues = [[0.0, 0.0, 0.0]]
@property
def color(self):
return self._batchedReadValues[0]
@color.setter
def color(self, value):
self._batchedReadValues[0] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"h", "s", "v", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def h(self):
value = self._batchedWriteValues.get(self._attributes.h)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.h)
return data_view.get()
@h.setter
def h(self, value):
self._batchedWriteValues[self._attributes.h] = value
@property
def s(self):
value = self._batchedWriteValues.get(self._attributes.s)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.s)
return data_view.get()
@s.setter
def s(self, value):
self._batchedWriteValues[self._attributes.s] = value
@property
def v(self):
value = self._batchedWriteValues.get(self._attributes.v)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.v)
return data_view.get()
@v.setter
def v(self, value):
self._batchedWriteValues[self._attributes.v] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialABIPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialABIPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialABIPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialABIPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.AbiPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialABIPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialABIPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialABIPyDatabase(node)
try:
compute_function = getattr(OgnTutorialABIPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialABIPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialABIPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialABIPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialABIPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialABIPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialABIPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialABIPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialABIPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialABIPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: ABI Overrides")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials,tutorial:abiPy")
node_type.set_metadata(ogn.MetadataKeys.CATEGORY_DESCRIPTIONS, "tutorial:abiPy,Tutorial nodes that override the Python ABI functions")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This tutorial node shows how to override ABI methods on your Python node. The algorithm of the node converts an RGB color into HSV components.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.AbiPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialABIPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialABIPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialABIPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialABIPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.AbiPy")
| 12,926 | Python | 44.517605 | 214 | 0.624555 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTupleDataDatabase.py | """Support for simplified access to data on nodes of type omni.tutorials.TupleData
This is a tutorial node. It creates both an input and output attribute of some of the supported tuple types. The values
are modified in a simple way so that the compute can be tested.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialTupleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.tutorials.TupleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_double2
inputs.a_double3
inputs.a_float2
inputs.a_float3
inputs.a_half2
inputs.a_int2
Outputs:
outputs.a_double2
outputs.a_double3
outputs.a_float2
outputs.a_float3
outputs.a_half2
outputs.a_int2
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a_double2', 'double2', 0, None, 'This is an attribute with two double values', {ogn.MetadataKeys.DEFAULT: '[1.1, 2.2]'}, True, [1.1, 2.2], False, ''),
('inputs:a_double3', 'double3', 0, None, 'This is an attribute with three double values', {ogn.MetadataKeys.DEFAULT: '[1.1, 2.2, 3.3]'}, True, [1.1, 2.2, 3.3], False, ''),
('inputs:a_float2', 'float2', 0, None, 'This is an attribute with two float values', {ogn.MetadataKeys.DEFAULT: '[4.4, 5.5]'}, True, [4.4, 5.5], False, ''),
('inputs:a_float3', 'float3', 0, None, 'This is an attribute with three float values', {ogn.MetadataKeys.DEFAULT: '[6.6, 7.7, 8.8]'}, True, [6.6, 7.7, 8.8], False, ''),
('inputs:a_half2', 'half2', 0, None, 'This is an attribute with two 16-bit float values', {ogn.MetadataKeys.DEFAULT: '[7.0, 8.0]'}, True, [7.0, 8.0], False, ''),
('inputs:a_int2', 'int2', 0, None, 'This is an attribute with two 32-bit integer values', {ogn.MetadataKeys.DEFAULT: '[10, 11]'}, True, [10, 11], False, ''),
('outputs:a_double2', 'double2', 0, None, 'This is a computed attribute with two double values', {}, True, None, False, ''),
('outputs:a_double3', 'double3', 0, None, 'This is a computed attribute with three double values', {}, True, None, False, ''),
('outputs:a_float2', 'float2', 0, None, 'This is a computed attribute with two float values', {}, True, None, False, ''),
('outputs:a_float3', 'float3', 0, None, 'This is a computed attribute with three float values', {}, True, None, False, ''),
('outputs:a_half2', 'half2', 0, None, 'This is a computed attribute with two 16-bit float values', {}, True, None, False, ''),
('outputs:a_int2', 'int2', 0, None, 'This is a computed attribute with two 32-bit integer values', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def a_double2(self):
data_view = og.AttributeValueHelper(self._attributes.a_double2)
return data_view.get()
@a_double2.setter
def a_double2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double2)
data_view = og.AttributeValueHelper(self._attributes.a_double2)
data_view.set(value)
@property
def a_double3(self):
data_view = og.AttributeValueHelper(self._attributes.a_double3)
return data_view.get()
@a_double3.setter
def a_double3(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double3)
data_view = og.AttributeValueHelper(self._attributes.a_double3)
data_view.set(value)
@property
def a_float2(self):
data_view = og.AttributeValueHelper(self._attributes.a_float2)
return data_view.get()
@a_float2.setter
def a_float2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float2)
data_view = og.AttributeValueHelper(self._attributes.a_float2)
data_view.set(value)
@property
def a_float3(self):
data_view = og.AttributeValueHelper(self._attributes.a_float3)
return data_view.get()
@a_float3.setter
def a_float3(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float3)
data_view = og.AttributeValueHelper(self._attributes.a_float3)
data_view.set(value)
@property
def a_half2(self):
data_view = og.AttributeValueHelper(self._attributes.a_half2)
return data_view.get()
@a_half2.setter
def a_half2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_half2)
data_view = og.AttributeValueHelper(self._attributes.a_half2)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int2)
data_view = og.AttributeValueHelper(self._attributes.a_int2)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def a_double2(self):
data_view = og.AttributeValueHelper(self._attributes.a_double2)
return data_view.get()
@a_double2.setter
def a_double2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double2)
data_view.set(value)
@property
def a_double3(self):
data_view = og.AttributeValueHelper(self._attributes.a_double3)
return data_view.get()
@a_double3.setter
def a_double3(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double3)
data_view.set(value)
@property
def a_float2(self):
data_view = og.AttributeValueHelper(self._attributes.a_float2)
return data_view.get()
@a_float2.setter
def a_float2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float2)
data_view.set(value)
@property
def a_float3(self):
data_view = og.AttributeValueHelper(self._attributes.a_float3)
return data_view.get()
@a_float3.setter
def a_float3(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float3)
data_view.set(value)
@property
def a_half2(self):
data_view = og.AttributeValueHelper(self._attributes.a_half2)
return data_view.get()
@a_half2.setter
def a_half2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_half2)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialTupleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTupleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTupleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,851 | Python | 43.842975 | 179 | 0.625933 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialVectorizedABIPassthroughDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.TutorialVectorizedABIPassThrough
Simple passthrough node that copy its input to its output in a vectorized way
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialVectorizedABIPassthroughDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.TutorialVectorizedABIPassThrough
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.value
Outputs:
outputs.value
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:value', 'float', 0, None, 'input value', {}, True, 0.0, False, ''),
('outputs:value', 'float', 0, None, 'output value', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.value)
data_view = og.AttributeValueHelper(self._attributes.value)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
data_view = og.AttributeValueHelper(self._attributes.value)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialVectorizedABIPassthroughDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialVectorizedABIPassthroughDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialVectorizedABIPassthroughDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,110 | Python | 45.463636 | 134 | 0.676517 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundleDataPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleDataPy
This is a tutorial node. It exercises functionality for access of data within bundle attributes. The configuration is the
same as omni.graph.tutorials.BundleData except that the implementation language is Python
"""
import carb
import sys
import traceback
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialBundleDataPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleDataPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.bundle
Outputs:
outputs.bundle
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:bundle', 'bundle', 0, 'Input Bundle', 'Bundle whose contents are modified for passing to the output', {}, True, None, False, ''),
('outputs:bundle', 'bundle', 0, 'Output Bundle', 'This is the bundle with values of known types doubled.', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.bundle = og.AttributeRole.BUNDLE
role_data.outputs.bundle = og.AttributeRole.BUNDLE
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.bundle"""
return self.__bundles.bundle
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.bundle"""
return self.__bundles.bundle
@bundle.setter
def bundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.bundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.bundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialBundleDataPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundleDataPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundleDataPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialBundleDataPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.BundleDataPy'
@staticmethod
def compute(context, node):
def database_valid():
if not db.inputs.bundle.valid:
db.log_warning('Required bundle inputs.bundle is invalid or not connected, compute skipped')
return False
if not db.outputs.bundle.valid:
db.log_error('Required bundle outputs.bundle is invalid, compute skipped')
return False
return True
try:
per_node_data = OgnTutorialBundleDataPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialBundleDataPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialBundleDataPyDatabase(node)
try:
compute_function = getattr(OgnTutorialBundleDataPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialBundleDataPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialBundleDataPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialBundleDataPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialBundleDataPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialBundleDataPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialBundleDataPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialBundleDataPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialBundleDataPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialBundleDataPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Bundle Data")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises functionality for access of data within bundle attributes. The configuration is the same as omni.graph.tutorials.BundleData except that the implementation language is Python")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.BundleDataPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialBundleDataPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialBundleDataPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialBundleDataPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialBundleDataPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.BundleDataPy")
| 11,742 | Python | 49.18376 | 283 | 0.654403 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialExtendedTypesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypesPy
This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types. It is identical
to OgnTutorialExtendedTypes.ogn, except the language of implementation is selected to be python.
"""
from typing import Any
import carb
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialExtendedTypesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypesPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.flexible
inputs.floatOrToken
inputs.toNegate
inputs.tuple
Outputs:
outputs.doubledResult
outputs.flexible
outputs.negatedResult
outputs.tuple
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:flexible', 'float[3][],token', 1, 'Flexible Values', 'Flexible data type input', {}, True, None, False, ''),
('inputs:floatOrToken', 'float,token', 1, 'Float Or Token', 'Attribute that can either be a float value or a token value', {}, True, None, False, ''),
('inputs:toNegate', 'bool[],float[]', 1, 'To Negate', 'Attribute that can either be an array of booleans or an array of floats', {}, True, None, False, ''),
('inputs:tuple', 'any', 2, 'Tuple Values', 'Variable size/type tuple values', {}, True, None, False, ''),
('outputs:doubledResult', 'any', 2, 'Doubled Input Value', "If the input 'floatOrToken' is a float this is 2x the value.\nIf it is a token this contains the input token repeated twice.", {}, True, None, False, ''),
('outputs:flexible', 'float[3][],token', 1, 'Inverted Flexible Values', 'Flexible data type output', {}, True, None, False, ''),
('outputs:negatedResult', 'bool[],float[]', 1, 'Negated Array Values', "Result of negating the data from the 'toNegate' input", {}, True, None, False, ''),
('outputs:tuple', 'any', 2, 'Negative Tuple Values', 'Negated values of the tuple input', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, True)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def floatOrToken(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.floatOrToken"""
return og.RuntimeAttribute(self._attributes.floatOrToken.get_attribute_data(), self._context, True)
@floatOrToken.setter
def floatOrToken(self, value_to_set: Any):
"""Assign another attribute's value to outputs.floatOrToken"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.floatOrToken.value = value_to_set.value
else:
self.floatOrToken.value = value_to_set
@property
def toNegate(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.toNegate"""
return og.RuntimeAttribute(self._attributes.toNegate.get_attribute_data(), self._context, True)
@toNegate.setter
def toNegate(self, value_to_set: Any):
"""Assign another attribute's value to outputs.toNegate"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.toNegate.value = value_to_set.value
else:
self.toNegate.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, True)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.value = value_to_set
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def doubledResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.doubledResult"""
return og.RuntimeAttribute(self._attributes.doubledResult.get_attribute_data(), self._context, False)
@doubledResult.setter
def doubledResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.doubledResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.doubledResult.value = value_to_set.value
else:
self.doubledResult.value = value_to_set
@property
def flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, False)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def negatedResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.negatedResult"""
return og.RuntimeAttribute(self._attributes.negatedResult.get_attribute_data(), self._context, False)
@negatedResult.setter
def negatedResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.negatedResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.negatedResult.value = value_to_set.value
else:
self.negatedResult.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, False)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.value = value_to_set
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialExtendedTypesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialExtendedTypesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialExtendedTypesPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.ExtendedTypesPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialExtendedTypesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialExtendedTypesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialExtendedTypesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialExtendedTypesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialExtendedTypesPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialExtendedTypesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialExtendedTypesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Extended Attribute Types")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types. It is identical to OgnTutorialExtendedTypes.ogn, except the language of implementation is selected to be python.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.ExtendedTypesPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialExtendedTypesPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialExtendedTypesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.ExtendedTypesPy")
| 16,110 | Python | 49.823344 | 290 | 0.646369 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuExtendedDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuExtended
This is a tutorial node. It exercises functionality for accessing data in extended attributes that are on the GPU as well
as those whose CPU/GPU location is decided at runtime. The compute adds the two inputs 'gpuData' and 'cpuData' together,
placing the result in `cpuGpuSum`, whose memory location is determined by the 'gpu' flag. This node is identical to OgnTutorialCpuGpuExtendedPy.ogn,
except is is implemented in C++.
"""
from typing import Any
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCpuGpuExtendedDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuExtended
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cpuData
inputs.gpu
inputs.gpuData
Outputs:
outputs.cpuGpuSum
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:cpuData', 'any', 2, 'CPU Input Attribute', 'Input attribute whose data always lives on the CPU', {}, True, None, False, ''),
('inputs:gpu', 'bool', 0, 'Results To GPU', 'If true then put the sum on the GPU, otherwise put it on the CPU', {}, True, False, False, ''),
('inputs:gpuData', 'any', 2, 'GPU Input Attribute', 'Input attribute whose data always lives on the GPU', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda'}, True, None, False, ''),
('outputs:cpuGpuSum', 'any', 2, 'Sum', "This is the attribute with the selected data. If the 'gpu' attribute is set to true then this\nattribute's contents will be entirely on the GPU, otherwise it will be on the CPU.", {ogn.MetadataKeys.MEMORY_TYPE: 'any'}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def cpuData(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.cpuData"""
return og.RuntimeAttribute(self._attributes.cpuData.get_attribute_data(), self._context, True)
@cpuData.setter
def cpuData(self, value_to_set: Any):
"""Assign another attribute's value to outputs.cpuData"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.cpuData.value = value_to_set.value
else:
self.cpuData.value = value_to_set
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gpu)
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def gpuData(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.gpuData"""
return og.RuntimeAttribute(self._attributes.gpuData.get_attribute_data(), self._context, True)
@gpuData.setter
def gpuData(self, value_to_set: Any):
"""Assign another attribute's value to outputs.gpuData"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.gpuData.value = value_to_set.value
else:
self.gpuData.value = value_to_set
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def cpuGpuSum(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.cpuGpuSum"""
return og.RuntimeAttribute(self._attributes.cpuGpuSum.get_attribute_data(), self._context, False)
@cpuGpuSum.setter
def cpuGpuSum(self, value_to_set: Any):
"""Assign another attribute's value to outputs.cpuGpuSum"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.cpuGpuSum.value = value_to_set.value
else:
self.cpuGpuSum.value = value_to_set
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialCpuGpuExtendedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuExtendedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuExtendedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,494 | Python | 49.986394 | 290 | 0.667734 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialSimpleDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.SimpleData
This is a tutorial node. It creates both an input and output attribute of every simple supported data type. The values are
modified in a simple way so that the compute modifies values.
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialSimpleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.SimpleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_bool
inputs.a_constant_input
inputs.a_double
inputs.a_float
inputs.a_half
inputs.a_int
inputs.a_int64
inputs.a_objectId
inputs.a_path
inputs.a_string
inputs.a_token
inputs.unsigned_a_uchar
inputs.unsigned_a_uint
inputs.unsigned_a_uint64
Outputs:
outputs.a_bool
outputs.a_double
outputs.a_float
outputs.a_half
outputs.a_int
outputs.a_int64
outputs.a_objectId
outputs.a_path
outputs.a_string
outputs.a_token
outputs.unsigned_a_uchar
outputs.unsigned_a_uint
outputs.unsigned_a_uint64
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a_bool', 'bool', 0, 'Sample Boolean Input', 'This is an attribute of type boolean', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('inputs:a_constant_input', 'int', 0, None, 'This is an input attribute whose value can be set but can only be connected as a source.', {ogn.MetadataKeys.OUTPUT_ONLY: '1'}, True, 0, False, ''),
('inputs:a_double', 'double', 0, None, 'This is an attribute of type 64 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_float', 'float', 0, None, 'This is an attribute of type 32 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_half', 'half', 0, 'Sample Half Precision Input', 'This is an attribute of type 16 bit float', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:a_int', 'int', 0, None, 'This is an attribute of type 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_int64', 'int64', 0, None, 'This is an attribute of type 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_objectId', 'objectId', 0, None, 'This is an attribute of type objectId', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_path', 'path', 0, None, 'This is an attribute of type path', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('inputs:a_string', 'string', 0, None, 'This is an attribute of type string', {ogn.MetadataKeys.DEFAULT: '"helloString"'}, True, "helloString", False, ''),
('inputs:a_token', 'token', 0, None, 'This is an attribute of type interned string with fast comparison and hashing', {ogn.MetadataKeys.DEFAULT: '"helloToken"'}, True, "helloToken", False, ''),
('inputs:unsigned:a_uchar', 'uchar', 0, None, 'This is an attribute of type unsigned 8 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:unsigned:a_uint', 'uint', 0, None, 'This is an attribute of type unsigned 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:unsigned:a_uint64', 'uint64', 0, None, 'This is an attribute of type unsigned 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:a_bool', 'bool', 0, 'Sample Boolean Output', 'This is a computed attribute of type boolean', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('outputs:a_double', 'double', 0, None, 'This is a computed attribute of type 64 bit floating point', {ogn.MetadataKeys.DEFAULT: '5.0'}, True, 5.0, False, ''),
('outputs:a_float', 'float', 0, None, 'This is a computed attribute of type 32 bit floating point', {ogn.MetadataKeys.DEFAULT: '4.0'}, True, 4.0, False, ''),
('outputs:a_half', 'half', 0, 'Sample Half Precision Output', 'This is a computed attribute of type 16 bit float', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('outputs:a_int', 'int', 0, None, 'This is a computed attribute of type 32 bit integer', {ogn.MetadataKeys.DEFAULT: '2'}, True, 2, False, ''),
('outputs:a_int64', 'int64', 0, None, 'This is a computed attribute of type 64 bit integer', {ogn.MetadataKeys.DEFAULT: '3'}, True, 3, False, ''),
('outputs:a_objectId', 'objectId', 0, None, 'This is a computed attribute of type objectId', {ogn.MetadataKeys.DEFAULT: '8'}, True, 8, False, ''),
('outputs:a_path', 'path', 0, None, 'This is a computed attribute of type path', {ogn.MetadataKeys.DEFAULT: '"/"'}, True, "/", False, ''),
('outputs:a_string', 'string', 0, None, 'This is a computed attribute of type string', {ogn.MetadataKeys.DEFAULT: '"seven"'}, True, "seven", False, ''),
('outputs:a_token', 'token', 0, None, 'This is a computed attribute of type interned string with fast comparison and hashing', {ogn.MetadataKeys.DEFAULT: '"six"'}, True, "six", False, ''),
('outputs:unsigned:a_uchar', 'uchar', 0, None, 'This is a computed attribute of type unsigned 8 bit integer', {ogn.MetadataKeys.DEFAULT: '9'}, True, 9, False, ''),
('outputs:unsigned:a_uint', 'uint', 0, None, 'This is a computed attribute of type unsigned 32 bit integer', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''),
('outputs:unsigned:a_uint64', 'uint64', 0, None, 'This is a computed attribute of type unsigned 64 bit integer', {ogn.MetadataKeys.DEFAULT: '11'}, True, 11, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.a_objectId = og.AttributeRole.OBJECT_ID
role_data.inputs.a_path = og.AttributeRole.PATH
role_data.inputs.a_string = og.AttributeRole.TEXT
role_data.outputs.a_objectId = og.AttributeRole.OBJECT_ID
role_data.outputs.a_path = og.AttributeRole.PATH
role_data.outputs.a_string = og.AttributeRole.TEXT
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_bool)
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_constant_input(self):
data_view = og.AttributeValueHelper(self._attributes.a_constant_input)
return data_view.get()
@a_constant_input.setter
def a_constant_input(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_constant_input)
data_view = og.AttributeValueHelper(self._attributes.a_constant_input)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double)
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float)
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_half)
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int)
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int64)
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_objectId(self):
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
return data_view.get()
@a_objectId.setter
def a_objectId(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_objectId)
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
data_view.set(value)
@property
def a_path(self):
data_view = og.AttributeValueHelper(self._attributes.a_path)
return data_view.get()
@a_path.setter
def a_path(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_path)
data_view = og.AttributeValueHelper(self._attributes.a_path)
data_view.set(value)
self.a_path_size = data_view.get_array_size()
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get()
@a_string.setter
def a_string(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_string)
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_token)
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def unsigned_a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
return data_view.get()
@unsigned_a_uchar.setter
def unsigned_a_uchar(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.unsigned_a_uchar)
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
data_view.set(value)
@property
def unsigned_a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
return data_view.get()
@unsigned_a_uint.setter
def unsigned_a_uint(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.unsigned_a_uint)
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
data_view.set(value)
@property
def unsigned_a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
return data_view.get()
@unsigned_a_uint64.setter
def unsigned_a_uint64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.unsigned_a_uint64)
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.a_path_size = 1
self.a_string_size = 5
self._batchedWriteValues = { }
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_objectId(self):
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
return data_view.get()
@a_objectId.setter
def a_objectId(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
data_view.set(value)
@property
def a_path(self):
data_view = og.AttributeValueHelper(self._attributes.a_path)
return data_view.get(reserved_element_count=self.a_path_size)
@a_path.setter
def a_path(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_path)
data_view.set(value)
self.a_path_size = data_view.get_array_size()
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get(reserved_element_count=self.a_string_size)
@a_string.setter
def a_string(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def unsigned_a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
return data_view.get()
@unsigned_a_uchar.setter
def unsigned_a_uchar(self, value):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
data_view.set(value)
@property
def unsigned_a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
return data_view.get()
@unsigned_a_uint.setter
def unsigned_a_uint(self, value):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
data_view.set(value)
@property
def unsigned_a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
return data_view.get()
@unsigned_a_uint64.setter
def unsigned_a_uint64(self, value):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialSimpleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialSimpleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialSimpleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 20,824 | Python | 44.769231 | 201 | 0.618565 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialExtendedTypesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypes
This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types.
"""
from typing import Any
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialExtendedTypesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.flexible
inputs.floatOrToken
inputs.toNegate
inputs.tuple
Outputs:
outputs.doubledResult
outputs.flexible
outputs.negatedResult
outputs.tuple
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:flexible', 'float[3][],token', 1, 'Flexible Values', 'Flexible data type input', {}, True, None, False, ''),
('inputs:floatOrToken', 'float,token', 1, 'Float Or Token', 'Attribute that can either be a float value or a token value', {}, True, None, False, ''),
('inputs:toNegate', 'bool[],float[]', 1, 'To Negate', 'Attribute that can either be an array of booleans or an array of floats', {}, True, None, False, ''),
('inputs:tuple', 'any', 2, 'Tuple Values', 'Variable size/type tuple values', {}, True, None, False, ''),
('outputs:doubledResult', 'any', 2, 'Doubled Input Value', "If the input 'simpleInput' is a float this is 2x the value.\nIf it is a token this contains the input token repeated twice.", {}, True, None, False, ''),
('outputs:flexible', 'float[3][],token', 1, 'Inverted Flexible Values', 'Flexible data type output', {}, True, None, False, ''),
('outputs:negatedResult', 'bool[],float[]', 1, 'Negated Array Values', "Result of negating the data from the 'toNegate' input", {}, True, None, False, ''),
('outputs:tuple', 'any', 2, 'Negative Tuple Values', 'Negated values of the tuple input', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, True)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def floatOrToken(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.floatOrToken"""
return og.RuntimeAttribute(self._attributes.floatOrToken.get_attribute_data(), self._context, True)
@floatOrToken.setter
def floatOrToken(self, value_to_set: Any):
"""Assign another attribute's value to outputs.floatOrToken"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.floatOrToken.value = value_to_set.value
else:
self.floatOrToken.value = value_to_set
@property
def toNegate(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.toNegate"""
return og.RuntimeAttribute(self._attributes.toNegate.get_attribute_data(), self._context, True)
@toNegate.setter
def toNegate(self, value_to_set: Any):
"""Assign another attribute's value to outputs.toNegate"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.toNegate.value = value_to_set.value
else:
self.toNegate.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, True)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.value = value_to_set
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def doubledResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.doubledResult"""
return og.RuntimeAttribute(self._attributes.doubledResult.get_attribute_data(), self._context, False)
@doubledResult.setter
def doubledResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.doubledResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.doubledResult.value = value_to_set.value
else:
self.doubledResult.value = value_to_set
@property
def flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, False)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def negatedResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.negatedResult"""
return og.RuntimeAttribute(self._attributes.negatedResult.get_attribute_data(), self._context, False)
@negatedResult.setter
def negatedResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.negatedResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.negatedResult.value = value_to_set.value
else:
self.negatedResult.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, False)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.value = value_to_set
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialExtendedTypesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialExtendedTypesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialExtendedTypesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,390 | Python | 49.687805 | 221 | 0.648893 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialSIMDAddDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.TutorialSIMDFloatAdd
Add 2 floats together using SIMD instruction set
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialSIMDAddDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.TutorialSIMDFloatAdd
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
Outputs:
outputs.result
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a', 'float', 0, None, 'first input operand', {}, True, 0.0, False, ''),
('inputs:b', 'float', 0, None, 'second input operand', {}, True, 0.0, False, ''),
('outputs:result', 'float', 0, None, 'the sum of a and b', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def a(self):
data_view = og.AttributeValueHelper(self._attributes.a)
return data_view.get()
@a.setter
def a(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a)
data_view = og.AttributeValueHelper(self._attributes.a)
data_view.set(value)
@property
def b(self):
data_view = og.AttributeValueHelper(self._attributes.b)
return data_view.get()
@b.setter
def b(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.b)
data_view = og.AttributeValueHelper(self._attributes.b)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def result(self):
data_view = og.AttributeValueHelper(self._attributes.result)
return data_view.get()
@result.setter
def result(self, value):
data_view = og.AttributeValueHelper(self._attributes.result)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialSIMDAddDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialSIMDAddDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialSIMDAddDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,476 | Python | 43.169354 | 117 | 0.655953 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundleAddAttributesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleAddAttributes
This is a tutorial node. It exercises functionality for adding and removing attributes on output bundles.
"""
import carb
import numpy
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialBundleAddAttributesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleAddAttributes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.addedAttributeNames
inputs.removedAttributeNames
inputs.typesToAdd
inputs.useBatchedAPI
Outputs:
outputs.bundle
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:addedAttributeNames', 'token[]', 0, None, "Names for the attribute types to be added. The size of this array must match the size\nof the 'typesToAdd' array to be legal.", {}, True, [], False, ''),
('inputs:removedAttributeNames', 'token[]', 0, None, 'Names for the attribute types to be removed. Non-existent attributes will be ignored.', {}, True, [], False, ''),
('inputs:typesToAdd', 'token[]', 0, 'Attribute Types To Add', 'List of type descriptions to add to the bundle. The strings in this list correspond to the\nstrings that represent the attribute types in the .ogn file (e.g. float[3][], colord[3], bool', {}, True, [], False, ''),
('inputs:useBatchedAPI', 'bool', 0, None, 'Controls whether or not to used batched APIS for adding/removing attributes', {}, True, False, False, ''),
('outputs:bundle', 'bundle', 0, 'Constructed Bundle', 'This is the bundle with all attributes added by compute.', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.outputs.bundle = og.AttributeRole.BUNDLE
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def addedAttributeNames(self):
data_view = og.AttributeValueHelper(self._attributes.addedAttributeNames)
return data_view.get()
@addedAttributeNames.setter
def addedAttributeNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.addedAttributeNames)
data_view = og.AttributeValueHelper(self._attributes.addedAttributeNames)
data_view.set(value)
self.addedAttributeNames_size = data_view.get_array_size()
@property
def removedAttributeNames(self):
data_view = og.AttributeValueHelper(self._attributes.removedAttributeNames)
return data_view.get()
@removedAttributeNames.setter
def removedAttributeNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.removedAttributeNames)
data_view = og.AttributeValueHelper(self._attributes.removedAttributeNames)
data_view.set(value)
self.removedAttributeNames_size = data_view.get_array_size()
@property
def typesToAdd(self):
data_view = og.AttributeValueHelper(self._attributes.typesToAdd)
return data_view.get()
@typesToAdd.setter
def typesToAdd(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.typesToAdd)
data_view = og.AttributeValueHelper(self._attributes.typesToAdd)
data_view.set(value)
self.typesToAdd_size = data_view.get_array_size()
@property
def useBatchedAPI(self):
data_view = og.AttributeValueHelper(self._attributes.useBatchedAPI)
return data_view.get()
@useBatchedAPI.setter
def useBatchedAPI(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.useBatchedAPI)
data_view = og.AttributeValueHelper(self._attributes.useBatchedAPI)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.bundle"""
return self.__bundles.bundle
@bundle.setter
def bundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.bundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.bundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialBundleAddAttributesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundleAddAttributesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundleAddAttributesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,372 | Python | 49.137724 | 284 | 0.671046 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialStatePyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.StatePy
This is a tutorial node. It makes use of internal state information to continuously increment an output.
"""
import carb
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialStatePyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.StatePy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.override
inputs.overrideValue
Outputs:
outputs.monotonic
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:override', 'bool', 0, None, 'When true get the output from the overrideValue, otherwise use the internal value', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:overrideValue', 'int64', 0, None, "Value to use instead of the monotonically increasing internal one when 'override' is true", {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:monotonic', 'int64', 0, None, 'Monotonically increasing output, set by internal state information', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"override", "overrideValue", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.override, self._attributes.overrideValue]
self._batchedReadValues = [False, 0]
@property
def override(self):
return self._batchedReadValues[0]
@override.setter
def override(self, value):
self._batchedReadValues[0] = value
@property
def overrideValue(self):
return self._batchedReadValues[1]
@overrideValue.setter
def overrideValue(self, value):
self._batchedReadValues[1] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"monotonic", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def monotonic(self):
value = self._batchedWriteValues.get(self._attributes.monotonic)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.monotonic)
return data_view.get()
@monotonic.setter
def monotonic(self, value):
self._batchedWriteValues[self._attributes.monotonic] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialStatePyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialStatePyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialStatePyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.StatePy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialStatePyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialStatePyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialStatePyDatabase(node)
try:
compute_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialStatePyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialStatePyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialStatePyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialStatePyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialStatePyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Internal States")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It makes use of internal state information to continuously increment an output.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.StatePy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialStatePyDatabase.INTERFACE.add_to_node_type(node_type)
node_type.set_has_state(True)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialStatePyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialStatePyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.StatePy")
| 12,036 | Python | 46.203921 | 197 | 0.638003 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialArrayDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ArrayData
This is a tutorial node. It will compute the array 'result' as the input array 'original' with every element multiplied
by the constant 'multiplier'.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialArrayDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ArrayData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.gates
inputs.info
inputs.multiplier
inputs.original
Outputs:
outputs.infoSize
outputs.negativeValues
outputs.result
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:gates', 'bool[]', 0, None, 'Boolean mask telling which elements of the array should be multiplied', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:info', 'token[]', 0, None, 'List of strings providing commentary', {ogn.MetadataKeys.DEFAULT: '["There", "is", "no", "data"]'}, True, ['There', 'is', 'no', 'data'], False, ''),
('inputs:multiplier', 'float', 0, None, 'Multiplier of the array elements', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:original', 'float[]', 0, None, 'Array to be multiplied', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:infoSize', 'int', 0, None, 'Number of letters in all strings in the info input', {}, True, None, False, ''),
('outputs:negativeValues', 'bool[]', 0, None, "Array of booleans set to true if the corresponding 'result' is negative", {}, True, None, False, ''),
('outputs:result', 'float[]', 0, None, 'Multiplied array', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def gates(self):
data_view = og.AttributeValueHelper(self._attributes.gates)
return data_view.get()
@gates.setter
def gates(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gates)
data_view = og.AttributeValueHelper(self._attributes.gates)
data_view.set(value)
self.gates_size = data_view.get_array_size()
@property
def info(self):
data_view = og.AttributeValueHelper(self._attributes.info)
return data_view.get()
@info.setter
def info(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.info)
data_view = og.AttributeValueHelper(self._attributes.info)
data_view.set(value)
self.info_size = data_view.get_array_size()
@property
def multiplier(self):
data_view = og.AttributeValueHelper(self._attributes.multiplier)
return data_view.get()
@multiplier.setter
def multiplier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.multiplier)
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.set(value)
@property
def original(self):
data_view = og.AttributeValueHelper(self._attributes.original)
return data_view.get()
@original.setter
def original(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.original)
data_view = og.AttributeValueHelper(self._attributes.original)
data_view.set(value)
self.original_size = data_view.get_array_size()
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.negativeValues_size = None
self.result_size = None
self._batchedWriteValues = { }
@property
def infoSize(self):
data_view = og.AttributeValueHelper(self._attributes.infoSize)
return data_view.get()
@infoSize.setter
def infoSize(self, value):
data_view = og.AttributeValueHelper(self._attributes.infoSize)
data_view.set(value)
@property
def negativeValues(self):
data_view = og.AttributeValueHelper(self._attributes.negativeValues)
return data_view.get(reserved_element_count=self.negativeValues_size)
@negativeValues.setter
def negativeValues(self, value):
data_view = og.AttributeValueHelper(self._attributes.negativeValues)
data_view.set(value)
self.negativeValues_size = data_view.get_array_size()
@property
def result(self):
data_view = og.AttributeValueHelper(self._attributes.result)
return data_view.get(reserved_element_count=self.result_size)
@result.setter
def result(self, value):
data_view = og.AttributeValueHelper(self._attributes.result)
data_view.set(value)
self.result_size = data_view.get_array_size()
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialArrayDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialArrayDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialArrayDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,507 | Python | 44.989189 | 193 | 0.645233 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuBundlesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuBundles
This is a tutorial node. It exercises functionality for accessing data in bundles that are on the GPU as well as bundles
whose CPU/GPU location is decided at runtime. The compute looks for bundled attributes named 'points' and, if they are found,
computes their dot products. If the bundle on the output contains an integer array type named 'dotProducts' then the results
are placed there, otherwise a new attribute of that name and type is created on the output bundle to hold the results. This
node is identical to OgnTutorialCpuGpuBundlesPy.ogn, except it is implemented in C++.
"""
import carb
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCpuGpuBundlesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuBundles
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cpuBundle
inputs.gpu
inputs.gpuBundle
Outputs:
outputs.cpuGpuBundle
Predefined Tokens:
tokens.points
tokens.dotProducts
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:cpuBundle', 'bundle', 0, 'CPU Input Bundle', 'Input bundle whose data always lives on the CPU', {}, True, None, False, ''),
('inputs:gpu', 'bool', 0, 'Results To GPU', 'If true then copy gpuBundle onto the output, otherwise copy cpuBundle', {}, True, False, False, ''),
('inputs:gpuBundle', 'bundle', 0, 'GPU Input Bundle', 'Input bundle whose data always lives on the GPU', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda'}, True, None, False, ''),
('outputs:cpuGpuBundle', 'bundle', 0, 'Constructed Bundle', "This is the bundle with the merged data. If the 'gpu' attribute is set to true then this\nbundle's contents will be entirely on the GPU, otherwise they will be on the CPU.", {ogn.MetadataKeys.MEMORY_TYPE: 'any'}, True, None, False, ''),
])
class tokens:
points = "points"
dotProducts = "dotProducts"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.cpuBundle = og.AttributeRole.BUNDLE
role_data.inputs.gpuBundle = og.AttributeRole.BUNDLE
role_data.outputs.cpuGpuBundle = og.AttributeRole.BUNDLE
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, ['inputs:gpuBundle'], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def cpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.cpuBundle"""
return self.__bundles.cpuBundle
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gpu)
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def gpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.gpuBundle"""
return self.__bundles.gpuBundle
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.__bundles = og.BundleContainer(context, node, attributes, ['outputs_cpuGpuBundle'], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def cpuGpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.cpuGpuBundle"""
return self.__bundles.cpuGpuBundle
@cpuGpuBundle.setter
def cpuGpuBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.cpuGpuBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.cpuGpuBundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialCpuGpuBundlesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuBundlesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuBundlesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,696 | Python | 50.313333 | 305 | 0.680223 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTokensDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.Tokens
This is a tutorial node. It exercises the feature of providing hardcoded token values in the database after a node type has
been initialized. It sets output booleans to the truth value of whether corresponding inputs appear in the hardcoded token
list.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialTokensDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.Tokens
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.valuesToCheck
Outputs:
outputs.isColor
Predefined Tokens:
tokens.red
tokens.green
tokens.blue
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:valuesToCheck', 'token[]', 0, None, 'Array of tokens that are to be checked', {}, True, [], False, ''),
('outputs:isColor', 'bool[]', 0, None, 'True values if the corresponding input value appears in the token list', {}, True, None, False, ''),
])
class tokens:
red = "red"
green = "green"
blue = "blue"
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def valuesToCheck(self):
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
return data_view.get()
@valuesToCheck.setter
def valuesToCheck(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.valuesToCheck)
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
data_view.set(value)
self.valuesToCheck_size = data_view.get_array_size()
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.isColor_size = None
self._batchedWriteValues = { }
@property
def isColor(self):
data_view = og.AttributeValueHelper(self._attributes.isColor)
return data_view.get(reserved_element_count=self.isColor_size)
@isColor.setter
def isColor(self, value):
data_view = og.AttributeValueHelper(self._attributes.isColor)
data_view.set(value)
self.isColor_size = data_view.get_array_size()
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialTokensDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTokensDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTokensDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,709 | Python | 44.31746 | 148 | 0.673148 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCudaDataCpuDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CudaCpuArrays
This is a tutorial node. It illustrates the alternative method of extracting pointers to GPU array data in which the pointer
returned is a CPU pointer and can be dereferenced on the CPU side. Without the cudaPointers value set that pointer would
be a GPU pointer to an array of GPU pointers and could only be dereferenced on the device.
"""
import carb
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCudaDataCpuDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CudaCpuArrays
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.multiplier
inputs.points
Outputs:
outputs.points
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:multiplier', 'float3', 0, None, 'Amplitude of the expansion for the input points', {ogn.MetadataKeys.DEFAULT: '[1.0, 1.0, 1.0]'}, True, [1.0, 1.0, 1.0], False, ''),
('inputs:points', 'float3[]', 0, None, 'Array of points to be moved', {ogn.MetadataKeys.MEMORY_TYPE: 'any', ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:points', 'float3[]', 0, None, 'Final positions of points', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def multiplier(self):
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
return data_view.get(on_gpu=True)
@multiplier.setter
def multiplier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.multiplier)
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
data_view.set(value, on_gpu=True)
class __points:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
self._parent.cpu_size = data_view.get_array_size()
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
self._parent.gpu_size = data_view.get_array_size()
@property
def points(self):
return self.__class__.__points(self)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.points_size = None
self._batchedWriteValues = { }
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
return data_view.get(reserved_element_count=self.points_size, on_gpu=True)
@points.setter
def points(self, value):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
data_view.set(value, on_gpu=True)
self.points_size = data_view.get_array_size()
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialCudaDataCpuDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCudaDataCpuDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCudaDataCpuDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,406 | Python | 46.480769 | 181 | 0.648123 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialSimpleDataPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.SimpleDataPy
This is a tutorial node. It creates both an input and output attribute of every simple supported data type. The values are
modified in a simple way so that the compute modifies values. It is the same as node omni.graph.tutorials.SimpleData, except
it is implemented in Python instead of C++.
"""
import carb
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialSimpleDataPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.SimpleDataPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_bool
inputs.a_constant_input
inputs.a_double
inputs.a_float
inputs.a_half
inputs.a_int
inputs.a_int64
inputs.a_objectId
inputs.a_path
inputs.a_string
inputs.a_token
inputs.a_uchar
inputs.a_uint
inputs.a_uint64
Outputs:
outputs.a_a_boolUiName
outputs.a_bool
outputs.a_double
outputs.a_float
outputs.a_half
outputs.a_int
outputs.a_int64
outputs.a_nodeTypeUiName
outputs.a_objectId
outputs.a_path
outputs.a_string
outputs.a_token
outputs.a_uchar
outputs.a_uint
outputs.a_uint64
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:a_bool', 'bool', 0, 'Simple Boolean Input', 'This is an attribute of type boolean', {ogn.MetadataKeys.DEFAULT: 'true'}, False, True, False, ''),
('inputs:a_constant_input', 'int', 0, None, 'This is an input attribute whose value can be set but can only be connected as a source.', {ogn.MetadataKeys.OUTPUT_ONLY: '1'}, True, 0, False, ''),
('inputs:a_double', 'double', 0, None, 'This is an attribute of type 64 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_float', 'float', 0, None, 'This is an attribute of type 32 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_half', 'half', 0, None, 'This is an attribute of type 16 bit float', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:a_int', 'int', 0, None, 'This is an attribute of type 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_int64', 'int64', 0, None, 'This is an attribute of type 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_objectId', 'objectId', 0, None, 'This is an attribute of type objectId', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_path', 'path', 0, None, 'This is an attribute of type path', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('inputs:a_string', 'string', 0, None, 'This is an attribute of type string', {ogn.MetadataKeys.DEFAULT: '"helloString"'}, True, "helloString", False, ''),
('inputs:a_token', 'token', 0, None, 'This is an attribute of type interned string with fast comparison and hashing', {ogn.MetadataKeys.DEFAULT: '"helloToken"'}, True, "helloToken", False, ''),
('inputs:a_uchar', 'uchar', 0, None, 'This is an attribute of type unsigned 8 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_uint', 'uint', 0, None, 'This is an attribute of type unsigned 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_uint64', 'uint64', 0, None, 'This is an attribute of type unsigned 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:a_a_boolUiName', 'string', 0, None, 'Computed attribute containing the UI name of input a_bool', {}, True, None, False, ''),
('outputs:a_bool', 'bool', 0, None, 'This is a computed attribute of type boolean', {}, True, None, False, ''),
('outputs:a_double', 'double', 0, None, 'This is a computed attribute of type 64 bit floating point', {}, True, None, False, ''),
('outputs:a_float', 'float', 0, None, 'This is a computed attribute of type 32 bit floating point', {}, True, None, False, ''),
('outputs:a_half', 'half', 0, None, 'This is a computed attribute of type 16 bit float', {}, True, None, False, ''),
('outputs:a_int', 'int', 0, None, 'This is a computed attribute of type 32 bit integer', {}, True, None, False, ''),
('outputs:a_int64', 'int64', 0, None, 'This is a computed attribute of type 64 bit integer', {}, True, None, False, ''),
('outputs:a_nodeTypeUiName', 'string', 0, None, 'Computed attribute containing the UI name of this node type', {}, True, None, False, ''),
('outputs:a_objectId', 'objectId', 0, None, 'This is a computed attribute of type objectId', {}, True, None, False, ''),
('outputs:a_path', 'path', 0, None, 'This is a computed attribute of type path', {ogn.MetadataKeys.DEFAULT: '"/Child"'}, True, "/Child", False, ''),
('outputs:a_string', 'string', 0, None, 'This is a computed attribute of type string', {ogn.MetadataKeys.DEFAULT: '"This string is empty"'}, True, "This string is empty", False, ''),
('outputs:a_token', 'token', 0, None, 'This is a computed attribute of type interned string with fast comparison and hashing', {}, True, None, False, ''),
('outputs:a_uchar', 'uchar', 0, None, 'This is a computed attribute of type unsigned 8 bit integer', {}, True, None, False, ''),
('outputs:a_uint', 'uint', 0, None, 'This is a computed attribute of type unsigned 32 bit integer', {}, True, None, False, ''),
('outputs:a_uint64', 'uint64', 0, None, 'This is a computed attribute of type unsigned 64 bit integer', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.a_objectId = og.AttributeRole.OBJECT_ID
role_data.inputs.a_path = og.AttributeRole.PATH
role_data.inputs.a_string = og.AttributeRole.TEXT
role_data.outputs.a_a_boolUiName = og.AttributeRole.TEXT
role_data.outputs.a_nodeTypeUiName = og.AttributeRole.TEXT
role_data.outputs.a_objectId = og.AttributeRole.OBJECT_ID
role_data.outputs.a_path = og.AttributeRole.PATH
role_data.outputs.a_string = og.AttributeRole.TEXT
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"a_bool", "a_constant_input", "a_double", "a_float", "a_half", "a_int", "a_int64", "a_objectId", "a_path", "a_string", "a_token", "a_uchar", "a_uint", "a_uint64", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.a_bool, self._attributes.a_constant_input, self._attributes.a_double, self._attributes.a_float, self._attributes.a_half, self._attributes.a_int, self._attributes.a_int64, self._attributes.a_objectId, self._attributes.a_path, self._attributes.a_string, self._attributes.a_token, self._attributes.a_uchar, self._attributes.a_uint, self._attributes.a_uint64]
self._batchedReadValues = [True, 0, 0, 0, 0.0, 0, 0, 0, "", "helloString", "helloToken", 0, 0, 0]
@property
def a_bool(self):
return self._batchedReadValues[0]
@a_bool.setter
def a_bool(self, value):
self._batchedReadValues[0] = value
@property
def a_constant_input(self):
return self._batchedReadValues[1]
@a_constant_input.setter
def a_constant_input(self, value):
self._batchedReadValues[1] = value
@property
def a_double(self):
return self._batchedReadValues[2]
@a_double.setter
def a_double(self, value):
self._batchedReadValues[2] = value
@property
def a_float(self):
return self._batchedReadValues[3]
@a_float.setter
def a_float(self, value):
self._batchedReadValues[3] = value
@property
def a_half(self):
return self._batchedReadValues[4]
@a_half.setter
def a_half(self, value):
self._batchedReadValues[4] = value
@property
def a_int(self):
return self._batchedReadValues[5]
@a_int.setter
def a_int(self, value):
self._batchedReadValues[5] = value
@property
def a_int64(self):
return self._batchedReadValues[6]
@a_int64.setter
def a_int64(self, value):
self._batchedReadValues[6] = value
@property
def a_objectId(self):
return self._batchedReadValues[7]
@a_objectId.setter
def a_objectId(self, value):
self._batchedReadValues[7] = value
@property
def a_path(self):
return self._batchedReadValues[8]
@a_path.setter
def a_path(self, value):
self._batchedReadValues[8] = value
@property
def a_string(self):
return self._batchedReadValues[9]
@a_string.setter
def a_string(self, value):
self._batchedReadValues[9] = value
@property
def a_token(self):
return self._batchedReadValues[10]
@a_token.setter
def a_token(self, value):
self._batchedReadValues[10] = value
@property
def a_uchar(self):
return self._batchedReadValues[11]
@a_uchar.setter
def a_uchar(self, value):
self._batchedReadValues[11] = value
@property
def a_uint(self):
return self._batchedReadValues[12]
@a_uint.setter
def a_uint(self, value):
self._batchedReadValues[12] = value
@property
def a_uint64(self):
return self._batchedReadValues[13]
@a_uint64.setter
def a_uint64(self, value):
self._batchedReadValues[13] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"a_a_boolUiName", "a_bool", "a_double", "a_float", "a_half", "a_int", "a_int64", "a_nodeTypeUiName", "a_objectId", "a_path", "a_string", "a_token", "a_uchar", "a_uint", "a_uint64", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.a_a_boolUiName_size = None
self.a_nodeTypeUiName_size = None
self.a_path_size = 6
self.a_string_size = 20
self._batchedWriteValues = { }
@property
def a_a_boolUiName(self):
value = self._batchedWriteValues.get(self._attributes.a_a_boolUiName)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_a_boolUiName)
return data_view.get()
@a_a_boolUiName.setter
def a_a_boolUiName(self, value):
self._batchedWriteValues[self._attributes.a_a_boolUiName] = value
@property
def a_bool(self):
value = self._batchedWriteValues.get(self._attributes.a_bool)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
self._batchedWriteValues[self._attributes.a_bool] = value
@property
def a_double(self):
value = self._batchedWriteValues.get(self._attributes.a_double)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
self._batchedWriteValues[self._attributes.a_double] = value
@property
def a_float(self):
value = self._batchedWriteValues.get(self._attributes.a_float)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
self._batchedWriteValues[self._attributes.a_float] = value
@property
def a_half(self):
value = self._batchedWriteValues.get(self._attributes.a_half)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
self._batchedWriteValues[self._attributes.a_half] = value
@property
def a_int(self):
value = self._batchedWriteValues.get(self._attributes.a_int)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
self._batchedWriteValues[self._attributes.a_int] = value
@property
def a_int64(self):
value = self._batchedWriteValues.get(self._attributes.a_int64)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
self._batchedWriteValues[self._attributes.a_int64] = value
@property
def a_nodeTypeUiName(self):
value = self._batchedWriteValues.get(self._attributes.a_nodeTypeUiName)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_nodeTypeUiName)
return data_view.get()
@a_nodeTypeUiName.setter
def a_nodeTypeUiName(self, value):
self._batchedWriteValues[self._attributes.a_nodeTypeUiName] = value
@property
def a_objectId(self):
value = self._batchedWriteValues.get(self._attributes.a_objectId)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
return data_view.get()
@a_objectId.setter
def a_objectId(self, value):
self._batchedWriteValues[self._attributes.a_objectId] = value
@property
def a_path(self):
value = self._batchedWriteValues.get(self._attributes.a_path)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_path)
return data_view.get()
@a_path.setter
def a_path(self, value):
self._batchedWriteValues[self._attributes.a_path] = value
@property
def a_string(self):
value = self._batchedWriteValues.get(self._attributes.a_string)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get()
@a_string.setter
def a_string(self, value):
self._batchedWriteValues[self._attributes.a_string] = value
@property
def a_token(self):
value = self._batchedWriteValues.get(self._attributes.a_token)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
self._batchedWriteValues[self._attributes.a_token] = value
@property
def a_uchar(self):
value = self._batchedWriteValues.get(self._attributes.a_uchar)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
return data_view.get()
@a_uchar.setter
def a_uchar(self, value):
self._batchedWriteValues[self._attributes.a_uchar] = value
@property
def a_uint(self):
value = self._batchedWriteValues.get(self._attributes.a_uint)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_uint)
return data_view.get()
@a_uint.setter
def a_uint(self, value):
self._batchedWriteValues[self._attributes.a_uint] = value
@property
def a_uint64(self):
value = self._batchedWriteValues.get(self._attributes.a_uint64)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
return data_view.get()
@a_uint64.setter
def a_uint64(self, value):
self._batchedWriteValues[self._attributes.a_uint64] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialSimpleDataPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialSimpleDataPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialSimpleDataPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.SimpleDataPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialSimpleDataPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialSimpleDataPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialSimpleDataPyDatabase(node)
try:
compute_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialSimpleDataPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialSimpleDataPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialSimpleDataPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialSimpleDataPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Attributes With Simple Data")
node_type.set_metadata(ogn.MetadataKeys.ICON_COLOR, "#FF00FF00")
node_type.set_metadata(ogn.MetadataKeys.ICON_BACKGROUND_COLOR, "#7FFF0000")
node_type.set_metadata(ogn.MetadataKeys.ICON_BORDER_COLOR, "#FF0000FF")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It creates both an input and output attribute of every simple supported data type. The values are modified in a simple way so that the compute modifies values. It is the same as node omni.graph.tutorials.SimpleData, except it is implemented in Python instead of C++.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.SimpleDataPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialSimpleDataPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialSimpleDataPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.SimpleDataPy")
| 27,413 | Python | 44.163097 | 415 | 0.605735 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial2/tutorial2.rst | .. _ogn_tutorial_simpleData:
Tutorial 2 - Simple Data Node
=============================
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_simpleDataPy` for a similar example in Python.
OgnTutorialSimpleData.ogn
-------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.SimpleData", which has one
input and one output attribute of each simple type.
.. literalinclude:: OgnTutorialSimpleData.ogn
:linenos:
:language: json
OgnTutorialSimpleData.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:: OgnTutorialSimpleData.cpp
:linenos:
:language: c++
Note how the attribute values are available through the OgnTutorialSimpleDataDatabase class. The generated interface
creates access methods for every attribute, named for the attribute itself. Inputs will be returned as const
references, outputs will be returned as non-const references.
Attribute Data
--------------
Two types of attribute data are created, which help with ease of access and of use - the attribute name lookup
information, and the attribute type definition.
Attribute data is accessed via a name-based lookup. This is not particularly efficient, so to facilitate this process
the attribute name is translated into a fast access token. In addition, the information about the attribute's type and
default value is constant for all nodes of the same type so that is stored as well, in static data.
Normally you would use an *auto* declaration for attribute types. Sometimes you want to pass around attribute data so
it is helpful to have access to the attribute's data type. In the generated code a ``using namespace`` is set up to
provide a very simple syntax for accessing the attribute's metadata from within the node:
.. code-block:: c++
std::cout << "Attribute name is " << inputs::a_bool.m_name << std::endl;
std::cout << "Attribute type is " << inputs::a_bool.m_dataType << std::endl;
extern "C" void processAttribute(inputs::a_bool_t& value);
// Equivalent to extern "C" void processAttribute(bool& value);
Attribute Data Access
---------------------
The attributes are automatically namespaced with *inputs* and *outputs*. In the USD file the attribute names
will appear as *inputs:XXX* or *outputs:XXX*. In the C++ interface the colon is illegal so a contained struct
is used to make use of the period equivalent, as *inputs.XXX* or *outputs.XXX*.
The minimum information provided by these wrapper classes is a reference to the underlying data, accessed by
``operator()``. For this class, these are the types it provides:
+--------------------+--------------------+
| Database Function | Returned Type |
+====================+====================+
| inputs.a_bool() | const bool& |
+--------------------+--------------------+
| inputs.a_half() | const pxr::GfHalf& |
+--------------------+--------------------+
| inputs.a_int() | const int& |
+--------------------+--------------------+
| inputs.a_int64() | const int64_t& |
+--------------------+--------------------+
| inputs.a_float() | const float& |
+--------------------+--------------------+
| inputs.a_double() | const double& |
+--------------------+--------------------+
| inputs.a_path() | const std::string& |
+--------------------+--------------------+
| inputs.a_string() | const std::string& |
+--------------------+--------------------+
| inputs.a_token() | const NameToken& |
+--------------------+--------------------+
| outputs.a_bool() | bool& |
+--------------------+--------------------+
| outputs.a_half() | pxr::GfHalf& |
+--------------------+--------------------+
| outputs.a_int() | int& |
+--------------------+--------------------+
| outputs.a_int64() | int64_t& |
+--------------------+--------------------+
| outputs.a_float() | float& |
+--------------------+--------------------+
| outputs.a_double() | double& |
+--------------------+--------------------+
| outputs.a_string() | std::string& |
+--------------------+--------------------+
| outputs.a_token() | NameToken& |
+--------------------+--------------------+
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.
Note how input attributes return *const* data while output attributes do not. This reinforces the restriction that
input data should never be written to, as it would cause graph synchronization problems.
The type *pxr::GfHalf* is an implementation of a 16-bit floating point value, though any other may also be used with
a runtime cast of the value. *omni::graph::core::NameToken* is a simple token through which a unique string can be
looked up at runtime.
Helpers
-------
A few helpers are provided in the database class definition to help make coding with it more natural.
initializeType
++++++++++++++
Function signature ``static void initializeType(const NodeTypeObj& nodeTypeObj)`` is an implementation of the ABI
function that is called once for each node type, initializing such things as its mandatory attributes and their default
values.
validate
++++++++
Function signature ``bool validate()``. If any of the mandatory attributes do not have values then the generated code
will exit early with an error message and not actually call the node's compute method.
token
+++++
Function signature ``NameToken token(const char* tokenName)``.
Provides a simple conversion from a string to the unique token representing that string, for fast comparison of
strings and for use with the attributes whose data types are *token*.
Compute Status 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 printf-like variable sets of parameters.
``void logError(Args...)`` 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.
``void logWarning(Args...)`` 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.
typedefs
++++++++
Although not part of the database class per se, a typedef alias is created for every attribute so that you can
use its type directly without knowing the detailed type; a midway point between exact types and *auto*. The main
use for such types might be passing attribute data between functions.
Here are the corresponding typedef names for each of the attributes:
+--------------------+--------------------+
| Typedef Alias | Actual Type |
+====================+====================+
| inputs.a_bool_t | const bool& |
+--------------------+--------------------+
| inputs.a_half_t | const pxr::GfHalf& |
+--------------------+--------------------+
| inputs.a_int_t | const int& |
+--------------------+--------------------+
| inputs.a_int64_t | const int64_t& |
+--------------------+--------------------+
| inputs.a_float_t | const float& |
+--------------------+--------------------+
| inputs.a_double_t | const double& |
+--------------------+--------------------+
| inputs.a_token_t | const NameToken& |
+--------------------+--------------------+
| outputs.a_bool_t | bool& |
+--------------------+--------------------+
| outputs.a_half_t | pxr::GfHalf& |
+--------------------+--------------------+
| outputs.a_int_t | int& |
+--------------------+--------------------+
| outputs.a_int64_t | int64_t& |
+--------------------+--------------------+
| outputs.a_float_t | float& |
+--------------------+--------------------+
| outputs.a_double_t | double& |
+--------------------+--------------------+
| outputs.a_token_t | NameToken& |
+--------------------+--------------------+
Notice the similarity between this table and the one above. The typedef name is formed by adding the extension *_t*
to the attribute accessor name, similar to C++ standard type naming conventions. The typedef should always correspond
to the return value of the attribute's ``operator()``.
Direct 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 methods provided, which correspond to the objects passed
in to the ABI compute method.
Context function signature ``const GraphContextObj& abi_context() const``, for accessing the underlying OmniGraph
evaluation context and its interface.
Node function signature ``const NodeObj& nodeObj abi_node() const``, for accessing the underlying OmniGraph node
object and its interface.
In addition, the attribute ABI objects are extracted into a shared structure so that they can be accessed in a
manner similar to the attribute data. For example ``db.attributes.inputs.a_bool()`` returns the `AttributeObj` that
refers to the input attribute named `a_bool`. It can be used to directly call ABI functions when required, though
again it should be emphasized that this will be a rare occurrence - all of the common operations can be performed
more easily using the database interfaces.
Node Computation Tests
----------------------
The "tests" section of the .ogn file contains a list of tests consisting of a description and attribute values,
both inputs and outputs, that will be used for the test.
The test runs by setting all of the named input attributes to their values, running the compute, then comparing the
resulting output attribute values against those specified by the test.
For example to test the computation of the boolean attribute, whose output is the negation of the input, these
two test values could be specified:
.. code::json
{
"tests": [
{
"description": "Check that true becomes false",
"inputs": {
"a_bool": true
},
"outputs": {
"a_bool": false
}
}
]
}
The "description" field is optional, though highly recommended to aid in debugging which tests are failing.
Any unspecified inputs take their default value, and any unspecified outputs do not get checked after the compute.
For simple attribute lists an abbreviated version of the syntax can be used, where the inputs and outputs get their
fully namespaced names so that there is no need for the "inputs" and "outputs" objects.
.. code::json
{
"tests": [
{
"description": "Check that false becomes true",
"inputs:a_bool": false,
"outputs:a_bool": true
}
]
}
| 11,492 | reStructuredText | 44.607143 | 120 | 0.607031 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial2/OgnTutorialSimpleData.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 <OgnTutorialSimpleDataDatabase.h>
#include <string>
// Even though the path is stored as a string this tutorial will use the SdfPath API to manipulate it
#include <pxr/usd/sdf/path.h>
// This class exercises access to the DataModel through the generated database class for all simple data types
// It's a good practice to namespace your nodes, so that they are guaranteed to be unique. Using this practice
// you can shorten your class names as well. This class could have equally been named "OgnSimpleData", since
// the "Tutorial" part of it is just another incarnation of the namespace.
namespace omni
{
namespace graph
{
namespace core
{
namespace tutorial
{
class OgnTutorialSimpleData
{
public:
static bool compute(OgnTutorialSimpleDataDatabase& db)
{
// 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() = !db.inputs.a_bool();
db.outputs.a_half() = 1.0f + 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.0f + db.inputs.a_float();
db.outputs.a_objectId() = 1 + db.inputs.a_objectId();
// The namespace separator ":" has special meaning in C++ so it is replaced by "_" when it appears in names
// Attribute "outputs:unsigned:a_uchar" becomes "outputs.unsigned_a_uchar".
db.outputs.unsigned_a_uchar() = 1 + db.inputs.unsigned_a_uchar();
db.outputs.unsigned_a_uint() = 1 + db.inputs.unsigned_a_uint();
db.outputs.unsigned_a_uint64() = 1 + db.inputs.unsigned_a_uint64();
// Internally the string type is more akin to a std::string_view, not available until C++17.
// The data is a pair of (const char*, size_t), but the interface provided through the accessor is
// castable to a std::string.
//
// This code shows the recommended way to use it, extracting inputs into a std::string for manipulation and
// then assigning outputs from the results. Using the referenced object directly could cause a lot of
// unnecessary fabric allocations. (i.e. avoid auto& outputStringView = db.outputs.a_string())
std::string outputString(db.inputs.a_string());
if (outputString.length() > 0)
{
auto foundStringAt = outputString.find("hello");
if (foundStringAt != std::string::npos)
{
outputString.replace(foundStringAt, 5, "world");
}
db.outputs.a_string() = outputString;
}
else
{
db.outputs.a_string() = "";
}
// The token interface is made available in the database as well, for convenience.
// By calling "db.stringToToken()" you can look up the token ID of a given string.
// There is also a symmetrical "db.tokenToString()" for going the other way.
std::string outputTokenString = db.tokenToString(db.inputs.a_token());
if (outputTokenString.length() > 0)
{
auto foundTokenAt = outputTokenString.find("hello");
if (foundTokenAt != std::string::npos)
{
outputTokenString.replace(foundTokenAt, 5, "world");
db.outputs.a_token() = db.stringToToken(outputTokenString.c_str());
}
}
else
{
db.outputs.a_token() = db.stringToToken("");
}
// Path just gets a new child named "Child". There's not requirement that the path point to anything
// that exists in the scene so any string will work here.
//
std::string outputPath = (std::string)db.inputs.a_path();
// 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::SdfPath API this is how you could do it:
//
// pxr::SdfPath sdfPath{outputPath};
// pxr::TfToken childToken{asTfToken(db.stringToToken("/Child"))};
// if (sdfPath.IsValid())
// {
// db.outputs.a_path() = sdfPath.AppendChild(childToken).GetString();
// }
//
outputPath += "/Child";
db.outputs.a_path() = outputPath;
// Drop down to the ABI to find attribute metadata, currently not available through the database
auto& nodeObj = db.abi_node();
auto attributeObj = nodeObj.iNode->getAttribute(nodeObj, "inputs:a_bool");
// The hardcoded metadata keyword is available through the node
auto uiName = attributeObj.iAttribute->getMetadata(attributeObj, kOgnMetadataUiName);
std::string expectedUiName{ "Sample Boolean Input" };
CARB_ASSERT(uiName && (expectedUiName == uiName));
// Confirm that the piece of metadata that differentiates objectId from regular uint64 is in place
auto objectIdAttributeObj = nodeObj.iNode->getAttribute(nodeObj, "inputs:a_objectId");
auto objectIdMetadata = attributeObj.iAttribute->getMetadata(objectIdAttributeObj, kOgnMetadataObjectId);
CARB_ASSERT(objectIdMetadata);
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
| 6,814 | C++ | 46.657342 | 119 | 0.657617 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial20/OgnTutorialTokens.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 <OgnTutorialTokensDatabase.h>
class OgnTutorialTokens
{
public:
static bool compute(OgnTutorialTokensDatabase& db)
{
const auto& valuesToCheck = db.inputs.valuesToCheck();
auto& isColor = db.outputs.isColor();
isColor.resize( valuesToCheck.size() );
if (valuesToCheck.size() == 0)
{
return true;
}
// Walk the list of inputs, setting the corresponding output to true if and only if the input is in
// the list of allowable tokens.
size_t index{ 0 };
for (const auto& inputValue : valuesToCheck)
{
// When the database is available you can use it to access the token values directly. When it is not
// you can access them statically (e.g. OgnTutorialTokensDatabase.token.red)
if ((inputValue == db.tokens.red) || (inputValue == db.tokens.green) || (inputValue == db.tokens.blue))
{
isColor[index] = true;
}
else
{
isColor[index] = false;
}
index++;
}
return true;
}
};
REGISTER_OGN_NODE()
| 1,617 | C++ | 32.708333 | 115 | 0.619666 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial20/OgnTutorialTokensPy.py | """
Implementation of a node handling hardcoded tokens. Tokens are a fixed set of strings, usually used for things
like keywords and enum names. In C++ tokens are more efficient than strings for lookup as they are represented
as a single long integer. The Python access methods are set up the same way, though at present there is no
differentiation between strings and tokens in Python code.
"""
class OgnTutorialTokensPy:
"""Exercise access to hardcoded tokens"""
@staticmethod
def compute(db) -> bool:
"""
Run through a list of input tokens and set booleans in a corresponding output array indicating if the
token appears in the list of hardcoded color names.
"""
values_to_check = db.inputs.valuesToCheck
# When assigning the entire array the size does not have to be set in advance
db.outputs.isColor = [value in [db.tokens.red, db.tokens.green, db.tokens.blue] for value in values_to_check]
return True
| 990 | Python | 38.639998 | 117 | 0.717172 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial20/tutorial20.rst | .. _ogn_tutorial_tokens:
Tutorial 20 - Tokens
====================
Tokens are a method of providing fast access to strings that have fixed contents. All strings with the same contents
can be translated into the same shared token. Token comparison is as fast as integer comparisons, rather than the more
expensive string comparisons you would need for a general string.
One example of where they are useful is in having a fixed set of allowable values for an input string. For example you
might choose a color channel by selecting from the names "red", "green", and "blue", or you might know that a mesh
bundle's contents always use the attribute names "normals", "points", and "faces".
Tokens can be accessed through the database methods ``tokenToString()`` and ``stringToToken()``. Using the ``tokens``
keyword in a .ogn file merely provides a shortcut to always having certain tokens available. In the color case then
if you have a token input containing the color your comparison code changes from this:
.. code-block:: c++
const auto& colorToken = db.inputs.colorToken();
if (colorToken == db.stringToToken("red"))
{
// do red stuff
}
else if (colorToken == db.stringToToken("green"))
{
// do green stuff
}
else if (colorToken == db.stringToToken("blue"))
{
// do blue stuff
}
to this, which has much faster comparison times:
.. code-block:: c++
const auto& colorToken = db.inputs.colorToken();
if (colorToken == db.tokens.red)
{
// do red stuff
}
else if (colorToken == db.tokens.green)
{
// do green stuff
}
else if (colorToken == db.tokens.blue)
{
// do blue stuff
}
In Python there isn't a first-class object that is a token but the same token access is provided for consistency:
.. code-block:: python
color_token = db.inputs.colorToken
if color_token == db.tokens.red:
# do red stuff
elif color_token == db.tokens.green:
# do green stuff
elif color_token == db.tokens.blue:
# do blue stuff
OgnTutorialTokens.ogn
---------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.Tokens", which contains some hardcoded
tokens to use in the compute method.
.. literalinclude:: OgnTutorialTokens.ogn
:linenos:
:language: json
OgnTutorialTokens.cpp
---------------------
The *cpp* file contains the implementation of the compute method. It illustrates how to access the hardcoded tokens
to avoid writing the boilerplate code yourself.
.. literalinclude:: OgnTutorialTokens.cpp
:linenos:
:language: c++
OgnTutorialTokensPy.py
----------------------
The *py* file contains the implementation of the compute method in Python. The .ogn file is the same as the above,
except for the addition of the implementation language key ``"language": "python"``. The compute follows the same
algorithm as the *cpp* equivalent.
.. literalinclude:: OgnTutorialTokensPy.py
:linenos:
:language: python
| 3,032 | reStructuredText | 32.32967 | 118 | 0.686016 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial7/tutorial7.rst | .. _ogn_tutorial_roleData:
Tutorial 7 - Role-Based Data Node
=================================
The role-based data node creates one input attribute and one output attribute of each of the role-based type. A
role-based type is defined as data with an underlying simple data type, with an interpretation of that simple
data, called a "role".
Examples of roles are **color**, **quat**, and **timecode**. For consistency the tuple counts for each of the
roles are included in the declaration so that the "shape" of the underlying data is more obvious.
OgnTutorialRoleData.ogn
-----------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.RoleData", which has one
input and one output attribute of each Role type.
.. literalinclude:: OgnTutorialRoleData.ogn
:linenos:
:language: json
OgnTutorialRoleData.cpp
-----------------------
The *cpp* file contains the implementation of the compute method, which modifies
each of the inputs by adding 1.0 to all components to create outputs that have different, testable, values.
.. literalinclude:: OgnTutorialRoleData.cpp
:linenos:
:language: c++
Role-Based Attribute Access
---------------------------
Here is a subset of the generated role-based attributes from the database. It contains color attributes, a matrix
attribute, and a timecode attribute. Notice how the underlying data types of the attributes are provided, again
with the ability to cast to different interface classes with the same memory layout.
+----------------------+-------------------+
| Database Function | Returned Type |
+======================+===================+
| inputs.a_color3d() | const GfVec3d& |
+----------------------+-------------------+
| inputs.a_color4f() | const GfVec4f& |
+----------------------+-------------------+
| inputs.a_frame() | const GfMatrix4d& |
+----------------------+-------------------+
| inputs.a_timecode() | const double& |
+----------------------+-------------------+
| outputs.a_color3d() | GfVec3d& |
+----------------------+-------------------+
| outputs.a_color4f() | GfVec4f& |
+----------------------+-------------------+
| outputs.a_frame() | GfMatrix4d& |
+----------------------+-------------------+
| outputs.a_timecode() | double& |
+----------------------+-------------------+
The full set of corresponding data types can be found in :ref:`ogn_attribute_roles`.
This role information is available on all attribute interfaces through the ``role()`` method. For example you can
find that the first attribute is a color by making this check:
.. code-block:: c++
static bool compute(OgnTutorialRoleDataDatabase& db)
{
if (db.inputs.a_color3d.role == eColor )
{
processValueAsAColor( db.inputs.a_color3d() );
}
}
| 2,856 | reStructuredText | 38.680555 | 113 | 0.576681 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial7/OgnTutorialRoleData.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 <OgnTutorialRoleDataDatabase.h>
// This class exercises access to the DataModel through the generated database class for all role-based data types
namespace
{
// Helper values to make it easy to add 1 to values of different lengths
GfHalf h1{ 1.0f };
GfVec2d increment2d{ 1.0, 1.0 };
GfVec2f increment2f{ 1.0f, 1.0f };
GfVec2h increment2h{ h1, h1 };
GfVec3d increment3d{ 1.0, 1.0, 1.0 };
GfVec3f increment3f{ 1.0f, 1.0f, 1.0f };
GfVec3h increment3h{ h1, h1, h1 };
GfVec4d increment4d{ 1.0, 1.0, 1.0, 1.0 };
GfVec4f increment4f{ 1.0f, 1.0f, 1.0f, 1.0f };
GfVec4h increment4h{ h1, h1, h1, h1 };
GfQuatd incrementQd{ 1.0, 1.0, 1.0, 1.0 };
GfQuatf incrementQf{ 1.0f, 1.0f, 1.0f, 1.0f };
GfQuath incrementQh{ h1, h1, h1, h1 };
GfMatrix4d incrementM4d{ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
GfMatrix3d incrementM3d{ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
GfMatrix2d incrementM2d{ 1.0, 1.0, 1.0, 1.0 };
}
// Helper macro to simplify the code but include all of the error checking
#define ComputeOne(ATTRIBUTE_NAME, INCREMENT_VARIABLE, ROLE_EXPECTED) \
foundError = false; \
if (db.inputs.ATTRIBUTE_NAME.role() != ROLE_EXPECTED) \
{ \
db.logWarning("Input role type %d != %d", (int)db.inputs.ATTRIBUTE_NAME.role(), (int)ROLE_EXPECTED); \
foundError = true; \
foundAnyErrors = true; \
} \
if (db.outputs.ATTRIBUTE_NAME.role() != ROLE_EXPECTED) \
{ \
db.logWarning("output role type %d != %d", (int)db.outputs.ATTRIBUTE_NAME.role(), (int)ROLE_EXPECTED); \
foundError = true; \
foundAnyErrors = true; \
} \
if (!foundError) \
{ \
db.outputs.ATTRIBUTE_NAME() = db.inputs.ATTRIBUTE_NAME() + INCREMENT_VARIABLE; \
}
class OgnTutorialRoleData
{
public:
static bool compute(OgnTutorialRoleDataDatabase& db)
{
// The roles for the attributes only serve to guide how to interpret them. When accessed from the
// database they take the form of their raw underlying type. For example a point3d will have the
// same GfVec3d type as a double[3], as will a vector3d and a normal3d.
// Keep track if any role errors were found with this, continuing to the end of evaluation after errors
bool foundAnyErrors{ false }; // Toggled on as soon as any error is found
bool foundError{ false }; // Toggled off and on for each attribute
// Walk through all of the data types, using the macro to perform error checking
ComputeOne(a_color3d, increment3d, AttributeRole::eColor);
ComputeOne(a_color3f, increment3f, AttributeRole::eColor);
ComputeOne(a_color3h, increment3h, AttributeRole::eColor);
//
ComputeOne(a_color4d, increment4d, AttributeRole::eColor);
ComputeOne(a_color4f, increment4f, AttributeRole::eColor);
ComputeOne(a_color4h, increment4h, AttributeRole::eColor);
//
ComputeOne(a_frame, incrementM4d, AttributeRole::eFrame);
//
ComputeOne(a_matrix2d, incrementM2d, AttributeRole::eMatrix
);
ComputeOne(a_matrix3d, incrementM3d, AttributeRole::eMatrix
);
ComputeOne(a_matrix4d, incrementM4d, AttributeRole::eMatrix
);
//
ComputeOne(a_normal3d, increment3d, AttributeRole::eNormal);
ComputeOne(a_normal3f, increment3f, AttributeRole::eNormal);
ComputeOne(a_normal3h, increment3h, AttributeRole::eNormal);
//
ComputeOne(a_point3d, increment3d, AttributeRole::ePosition);
ComputeOne(a_point3f, increment3f, AttributeRole::ePosition);
ComputeOne(a_point3h, increment3h, AttributeRole::ePosition);
//
ComputeOne(a_quatd, incrementQd, AttributeRole::eQuaternion);
ComputeOne(a_quatf, incrementQf, AttributeRole::eQuaternion);
ComputeOne(a_quath, incrementQh, AttributeRole::eQuaternion);
//
ComputeOne(a_texcoord2d, increment2d, AttributeRole::eTexCoord);
ComputeOne(a_texcoord2f, increment2f, AttributeRole::eTexCoord);
ComputeOne(a_texcoord2h, increment2h, AttributeRole::eTexCoord);
//
ComputeOne(a_texcoord3d, increment3d, AttributeRole::eTexCoord);
ComputeOne(a_texcoord3f, increment3f, AttributeRole::eTexCoord);
ComputeOne(a_texcoord3h, increment3h, AttributeRole::eTexCoord);
//
ComputeOne(a_timecode, 1.0, AttributeRole::eTimeCode);
//
ComputeOne(a_vector3d, increment3d, AttributeRole::eVector);
ComputeOne(a_vector3f, increment3f, AttributeRole::eVector);
ComputeOne(a_vector3h, increment3h, AttributeRole::eVector);
return foundAnyErrors;
}
};
REGISTER_OGN_NODE()
| 6,498 | C++ | 55.025862 | 120 | 0.538319 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial29/OgnTutorialVectorizedABIPassthrough.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 <OgnTutorialVectorizedABIPassthroughDatabase.h>
// The method used by the computation to perform the passthrough
// 0 = simple copy, no vectorization
#define TUTO_ABI_PASSTHROUGH_METHOD_SIMPLE 0
// 1 = vectorized copy by indexing the instance directly per attribute
#define TUTO_ABI_PASSTHROUGH_METHOD_ATTR 1
// 2 = vectorized copy by mutating attribute data handles
#define TUTO_ABI_PASSTHROUGH_METHOD_MUTATE 2
// 3 = vectorized copy using raw data
#define TUTO_ABI_PASSTHROUGH_METHOD_RAW 3
//By default, use the most efficient method
#define TUTO_ABI_PASSTHROUGH_METHOD TUTO_ABI_PASSTHROUGH_METHOD_RAW
// This node perform a copy of its input to its output
class OgnTutorialVectorizedABIPassthrough
{
public:
#if TUTO_ABI_PASSTHROUGH_METHOD == TUTO_ABI_PASSTHROUGH_METHOD_SIMPLE
// begin-regular
static bool compute(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
NodeContextHandle nodeHandle = nodeObj.nodeContextHandle;
auto inputValueAttr =
getAttributeR(contextObj, nodeHandle, Token("inputs:value"), kAccordingToContextIndex);
const float* inputValue = getDataR<float>(contextObj, inputValueAttr);
auto outputValueAttr =
getAttributeW(contextObj, nodeHandle, Token("outputs:value"), kAccordingToContextIndex);
float* outputValue = getDataW<float>(contextObj, outputValueAttr);
if(inputValue && outputValue)
{
*outputValue = *inputValue;
return true;
}
return false;
}
// end-regular
#elif TUTO_ABI_PASSTHROUGH_METHOD == TUTO_ABI_PASSTHROUGH_METHOD_ATTR
// begin-attr
static size_t computeVectorized(GraphContextObj const& contextObj, NodeObj const& nodeObj, size_t count)
{
GraphContextObj const* contexts = nullptr;
NodeObj const* nodes = nullptr;
//When using auto instancing, similiar graphs can get merged together, and computed vectorized
// In such case, each instance represent a different node in a different graph
// Accessing the data either through the provided node, or through the actual auto-insance node would work properly
// But any other ABI call requiring the node would need to provide the proper node
// While not necessary in this contezt, do the work of using the proper auto-instance node
// in order to demonstrate how to use it.
size_t handleCount = nodeObj.iNode->getAutoInstances(nodeObj, contexts, nodes);
auto nodeHandle = [&](InstanceIndex index) -> NodeContextHandle
{ return nodes[handleCount == 1 ? 0 : index.index].nodeContextHandle; };
auto context = [&](InstanceIndex index) -> GraphContextObj
{ return contexts[handleCount == 1 ? 0 : index.index]; };
size_t ret = 0;
const float* inputValue{ nullptr };
float* outputValue{ nullptr };
auto inToken = Token("inputs:value");
auto outToken = Token("outputs:value");
for (InstanceIndex idx{ 0 }; idx < InstanceIndex{ count }; ++idx)
{
auto inputValueAttr = getAttributeR(context(idx), nodeHandle(idx), inToken, idx);
inputValue = getDataR<float>(context(idx), inputValueAttr);
auto outputValueAttr = getAttributeW(context(idx), nodeHandle(idx), outToken, idx);
outputValue = getDataW<float>(context(idx), outputValueAttr);
if(inputValue && outputValue)
{
*outputValue = *inputValue;
++ret;
}
}
return ret;
}
// end-attr
#elif TUTO_ABI_PASSTHROUGH_METHOD == TUTO_ABI_PASSTHROUGH_METHOD_MUTATE
// begin-mutate
static size_t computeVectorized(GraphContextObj const& contextObj, NodeObj const& nodeObj, size_t count)
{
NodeContextHandle nodeHandle = nodeObj.nodeContextHandle;
size_t ret = 0;
const float* inputValue{ nullptr };
float* outputValue{ nullptr };
auto inputValueAttr =
getAttributeR(contextObj, nodeHandle, Token("inputs:value"), kAccordingToContextIndex);
auto outputValueAttr =
getAttributeW(contextObj, nodeHandle, Token("outputs:value"), kAccordingToContextIndex);
while (count--)
{
inputValue = getDataR<float>(contextObj, inputValueAttr);
outputValue = getDataW<float>(contextObj, outputValueAttr);
if(inputValue && outputValue)
{
*outputValue = *inputValue;
++ret;
}
inputValueAttr = contextObj.iAttributeData->moveToAnotherInstanceR(contextObj, inputValueAttr, 1);
outputValueAttr = contextObj.iAttributeData->moveToAnotherInstanceW(contextObj, outputValueAttr, 1);
}
return ret;
}
// end-mutate
#elif TUTO_ABI_PASSTHROUGH_METHOD == TUTO_ABI_PASSTHROUGH_METHOD_RAW
// begin-raw
static size_t computeVectorized(GraphContextObj const& contextObj, NodeObj const& nodeObj, size_t count)
{
NodeContextHandle nodeHandle = nodeObj.nodeContextHandle;
auto inputValueAttr =
getAttributeR(contextObj, nodeHandle, Token("inputs:value"), kAccordingToContextIndex);
const float* inputValue = getDataR<float>(contextObj, inputValueAttr);
auto outputValueAttr =
getAttributeW(contextObj, nodeHandle, Token("outputs:value"), kAccordingToContextIndex);
float* outputValue = getDataW<float>(contextObj, outputValueAttr);
if(inputValue && outputValue)
{
memcpy(outputValue, inputValue, count * sizeof(float));
return count;
}
return 0;
}
// end-raw
#endif
};
REGISTER_OGN_NODE()
| 6,186 | C++ | 38.407643 | 123 | 0.676043 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial17/tutorial17.rst | .. _ogn_tutorial_state_attributes_py:
Tutorial 17 - Python State Attributes Node
==========================================
This node illustrates how you can use state attributes. These are attributes that are not meant to be connected to
other nodes as they maintain a node's internal state, persistent from one evaluation to the next.
As they are persistent, care must be taken that they be initialized properly. This can take the form of a reset
flag, as seen on this node, state flag values with known defaults that describe the validity of the state attribute
data, or using a checksum on inputs, among other possibilities.
State attributes can be both read and written, like output attributes. The presence of state attributes will also
inform the evaluators on what type of parallel scheduling is appropriate.
These attributes provide a similar functionality to those found in :ref:`ogn_tutorial_state_py`, except that being
node attributes the structure is visible to the outside world, making it easier to construct UI and visualizers for
it.
OgnTutorialStateAttributesPy.ogn
--------------------------------
The *.ogn* file containing the implementation of a node named "omni.graph.tutorials.StateAttributesPy", with a couple of state
attributes that both read and write values during the compute.
.. literalinclude:: OgnTutorialStateAttributesPy.ogn
:linenos:
:language: json
OgnTutorialStateAttributesPy.py
-------------------------------
The *.py* file contains the compute method that uses the state attributes to run the algorithm.
.. literalinclude:: OgnTutorialStateAttributesPy.py
:linenos:
:language: python
Test Script
-----------
The .ogn test infrastructure currently only supports single evaluation, which will not be sufficient to test state
attribute manipulations. This test script runs multiple evaluations and verifies that the state information is
updated as expected after each evaluation.
.. literalinclude:: ../../python/tests/test_tutorial_state_attributes_py.py
:linenos:
:language: python
| 2,060 | reStructuredText | 42.851063 | 126 | 0.752913 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial17/OgnTutorialStateAttributesPy.py | """
Implementation of a Python node that uses state attributes to maintain information between evaluations.
The node has a simple monotonically increasing state output "monotonic" that can be reset by setting the state
attribute "reset" to true.
"""
class OgnTutorialStateAttributesPy:
"""Use internal node state information in addition to inputs"""
@staticmethod
def compute(db) -> bool:
"""Compute the output based on inputs and internal state"""
# State attributes are the only ones guaranteed to remember and modify their values.
# Care must be taken to set proper defaults when the node initializes, otherwise you could be
# starting in an unknown state.
if db.state.reset:
db.state.monotonic = 0
db.state.reset = False
else:
db.state.monotonic = db.state.monotonic + 1
return True
| 897 | Python | 33.53846 | 110 | 0.688963 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial11/tutorial11.rst | .. _ogn_tutorial_complexData_py:
Tutorial 11 - Complex Data Node in Python
=========================================
This node fills on the remainder of the (CPU for now) data types available through Python. It combines the
progressive introduction in C++ of :ref:`ogn_tutorial_tupleData`, :ref:`ogn_tutorial_arrayData`,
:ref:`ogn_tutorial_tupleArrays`, and :ref:`ogn_tutorial_roleData`.
Rather than providing an exhaustive set of attribute types there will be one chosen from each of the
aforementioned categories of types. See the section `Pythonic Complex Attribute Type Access`_ for details on
how to access the representative types.
OgnTutorialComplexDataPy.ogn
----------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.ComplexDataPy", which has one
input and one output attribute of each complex (arrays, tuples, roles) type.
.. literalinclude:: OgnTutorialComplexDataPy.ogn
:linenos:
:language: json
OgnTutorialComplexDataPy.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:: OgnTutorialComplexDataPy.py
:linenos:
:language: python
Note how the attribute values are available through the ``OgnTutorialComplexDataPyDatabase`` 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 Complex Attribute Type Access
--------------------------------------
Complex data in Python takes advantage of the numpy library to handle arrays so you should always include this
line at the top of your node if you have array data:
.. code-block:: python
import numpy
+----------------------+---------------------+-------------------------+
| Database Property | Representative Type | Returned Type |
+======================+=====================+=========================+
| inputs.a_float3 | Tuple | [float, float, float] |
+----------------------+---------------------+-------------------------+
| inputs.a_floatArray | Array | numpy.ndarray[float, 1] |
+----------------------+---------------------+-------------------------+
| inputs.a_point3Array | Role-Based | numpy.ndarray[float, 3] |
+----------------------+---------------------+-------------------------+
As with simple data, the values returned are all references to the real data in the FlatCache, our managed memory store,
pointing to the correct location at evaluation time.
Python Role Information
-----------------------
The attribute roles can be checked in Python similar to C++ by using the ``role()`` method on the generated database
class.
.. code-block:: python
def compute(db) -> bool:
"""Run my algorithm"""
if db.role(db.outputs.a_pointArray) == db.ROLE_POINT:
print("Hey, I did get the correct role")
This table shows the list of Python role names and the corresponding attribute types that match them:
+-----------------+---------------------------------+
| Python Role | Attribute Types |
+=================+=================================+
| ROLE_COLOR | colord, colorf, colorh |
+-----------------+---------------------------------+
| ROLE_FRAME | frame |
+-----------------+---------------------------------+
| ROLE_NORMAL | normald, normalf, normalh |
+-----------------+---------------------------------+
| ROLE_POSITION | positiond, positionf, positionh |
+-----------------+---------------------------------+
| ROLE_QUATERNION | quatd, quatf, quath |
+-----------------+---------------------------------+
| ROLE_TEXCOORD | texcoordd, texcoordf, texcoordh |
+-----------------+---------------------------------+
| ROLE_TIMECODE | timecode |
+-----------------+---------------------------------+
| ROLE_TRANSFORM | transform |
+-----------------+---------------------------------+
| ROLE_VECTOR | vectord, vectorf, vectorh |
+-----------------+---------------------------------+
| 4,331 | reStructuredText | 43.659793 | 120 | 0.525745 |
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/tutorial3.rst | .. _ogn_tutorial_abi:
Tutorial 3 - 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.
OgnTutorialABI.ogn
------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.Abi", in its first
version, with a simple description. The single attribute serves mostly to provide a framework for the ABI discussion.
.. literalinclude:: OgnTutorialABI.ogn
:linenos:
:language: json
OgnTutorialABI.cpp
------------------
The *cpp* 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:: OgnTutorialABI.cpp
:linenos:
:language: c++
Node Type Metadata
------------------
This file introduces the *metadata* keyword, whose value is a dictionary of key/value pairs associated with the
node type 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 **initializeType()** method in the node definition.
Exclusions
----------
Note the use of the **exclude** keyword in the .ogn file. This allows you to prevent generation of any of the default
files. In this case, since the ABI is handling everything the Python database will not be able to access the node's
information so it is excluded.
| 1,650 | reStructuredText | 41.333332 | 117 | 0.734545 |
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 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.