file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSwitchToken.rst
.. _omni_graph_action_SwitchToken_1: .. _omni_graph_action_SwitchToken: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Switch On Token :keywords: lang-en omnigraph node graph:action,flowControl threadsafe action switch-token Switch On Token =============== .. <description> Outputs an execution pulse along a branch which matches the input token. For example if inputs:value is set to 'A' it will continue downstream from outputs:outputNN if there is an inputs:branchNN is set to 'A' .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:execIn", "``execution``", "Input execution", "None" "Value (*inputs:value*)", "``token``", "The value to switch on", "" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.SwitchToken" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Switch On Token" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnSwitchTokenDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnClosing.rst
.. _omni_graph_action_OnClosing_1: .. _omni_graph_action_OnClosing: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Closing :keywords: lang-en omnigraph node graph:action,event threadsafe compute-on-request action on-closing On Closing ========== .. <description> Executes an output execution when the USD stage is about to be closed. Note that only simple necessary actions should be taken during closing since the application is in the process of cleaning up the existing state and some systems may be in a transitional state .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Closing (*outputs:execOut*)", "``execution``", "The execution output", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnClosing" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On Closing" "Categories", "graph:action,event" "Generated Class Name", "OgnOnClosingDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnce.rst
.. _omni_graph_action_Once_1: .. _omni_graph_action_Once: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Once :keywords: lang-en omnigraph node graph:action,flowControl threadsafe action once Once ==== .. <description> Controls flow of execution by passing input through differently on the first time .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:execIn", "``execution``", "Input execution", "None" "inputs:reset", "``execution``", "Resets the gate state to closed. The next execIn impulse will pass the gate.", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:after", "``execution``", "Executes after the first time", "None" "outputs:once", "``execution``", "Executes the first time (or the first time after a 'reset'.", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.Once" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Once" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnOnceDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnCustomEvent.rst
.. _omni_graph_action_OnCustomEvent_2: .. _omni_graph_action_OnCustomEvent: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Custom Event :keywords: lang-en omnigraph node graph:action,event compute-on-request action on-custom-event On Custom Event =============== .. <description> Event node which fires when the specified custom event is sent. This node is used in combination with SendCustomEvent .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Event Name (*inputs:eventName*)", "``token``", "The name of the custom event", "" "", "*literalOnly*", "1", "" "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Bundle (*outputs:bundle*)", "``bundle``", "Bundle received with the event", "None" "Received (*outputs:execOut*)", "``execution``", "Executes when the event is received", "None" "Path (*outputs:path*)", "``token``", "The path associated with the received custom event", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnCustomEvent" "Version", "2" "Extension", "omni.graph.action" "Has State?", "True" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On Custom Event" "Categories", "graph:action,event" "Generated Class Name", "OgnOnCustomEventDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnCounter.rst
.. _omni_graph_action_Counter_1: .. _omni_graph_action_Counter: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Counter :keywords: lang-en omnigraph node graph:action,function threadsafe action counter Counter ======= .. <description> This node counts the number of times it is computed since being reset .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None" "Reset (*inputs:reset*)", "``execution``", "Reset the internal counter", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Count (*outputs:count*)", "``int``", "The count value", "None" "Execute Out (*outputs:execOut*)", "``execution``", "The output execution", "None" State ----- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "state:count", "``int``", "The counter state", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.Counter" "Version", "1" "Extension", "omni.graph.action" "Has State?", "True" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Counter" "Categories", "graph:action,function" "Generated Class Name", "OgnCounterDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnObjectChange.rst
.. _omni_graph_action_OnObjectChange_4: .. _omni_graph_action_OnObjectChange: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On USD Object Change :keywords: lang-en omnigraph node graph:action,event threadsafe action on-object-change On USD Object Change ==================== .. <description> Executes an output execution pulse when the watched USD Object changes .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Property Name (*inputs:name*)", "``token``", "The name of the property to watch if prim input is set", "None" "", "*literalOnly*", "1", "" "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True" "", "*literalOnly*", "1", "" "Path (*inputs:path*)", "``path``", "The path of object of interest (property or prim). If the prim input has a target, this is ignored", "None" "", "*literalOnly*", "1", "" "Prim (*inputs:prim*)", "``target``", "The prim of interest. If this has a target, the path input will be ignored", "None" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Changed (*outputs:changed*)", "``execution``", "The execution output", "None" "Property Name (*outputs:propertyName*)", "``token``", "The name of the property that changed", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnObjectChange" "Version", "4" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On USD Object Change" "Categories", "graph:action,event" "Generated Class Name", "OgnOnObjectChangeDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnFlipFlop.rst
.. _omni_graph_action_FlipFlop_1: .. _omni_graph_action_FlipFlop: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Flip Flop :keywords: lang-en omnigraph node graph:action,flowControl threadsafe action flip-flop Flip Flop ========= .. <description> This node alternates activating its outputs, starting with A .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Execute A (*outputs:a*)", "``execution``", "Executed on the 1st and odd numbered triggers", "None" "Execute B (*outputs:b*)", "``execution``", "Executed on the even number triggers", "None" "Is A (*outputs:isA*)", "``bool``", "Set to true when a is activated", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.FlipFlop" "Version", "1" "Extension", "omni.graph.action" "Icon", "ogn/icons/omni.graph.action.FlipFlop.svg" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Flip Flop" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnFlipFlopDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnCountdown.rst
.. _omni_graph_action_Countdown_1: .. _omni_graph_action_Countdown: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Countdown :keywords: lang-en omnigraph node graph:action,flowControl action countdown Countdown ========= .. <description> Delays for a number of updates (the duration) while firing output tick activations with a given period. When the countdown is complete it triggers the finished output. The first compute does not generate a tick output. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:duration", "``int``", "The duration of the delay in ticks", "5" "inputs:execIn", "``execution``", "The input execution", "None" "inputs:period", "``int``", "The period of the pulse in ticks", "1" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:alpha", "``float``", "normalized progress in the range IE 'tickValue'/'duration'", "None" "outputs:finished", "``execution``", "Triggered after duration ticks is finished", "None" "outputs:tick", "``execution``", "Triggered every 'period' ticks", "None" "outputs:tickValue", "``int``", "The current tick value in the range [1, duration]", "None" State ----- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "state:count", "``int``", "The number of ticks elapsed, the first tick is 0", "-1" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.Countdown" "Version", "1" "Extension", "omni.graph.action" "Has State?", "True" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Countdown" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnCountdownDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnBranch.rst
.. _omni_graph_action_Branch_1: .. _omni_graph_action_Branch: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Branch :keywords: lang-en omnigraph node graph:action,flowControl threadsafe action branch Branch ====== .. <description> Outputs an execution pulse along a branch based on a boolean condition .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Condition (*inputs:condition*)", "``bool``", "The boolean condition which determines the output direction", "False" "inputs:execIn", "``execution``", "Input execution", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "False (*outputs:execFalse*)", "``execution``", "The output path when condition is False", "None" "True (*outputs:execTrue*)", "``execution``", "The output path when condition is True", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.Branch" "Version", "1" "Extension", "omni.graph.action" "Icon", "ogn/icons/omni.graph.action.Branch.svg" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Branch" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnBranchDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnMouseInput.rst
.. _omni_graph_action_OnMouseInput_1: .. _omni_graph_action_OnMouseInput: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Mouse Input :keywords: lang-en omnigraph node graph:action,input:mouse threadsafe compute-on-request action on-mouse-input On Mouse Input ============== .. <description> Event node which fires when a mouse event occurs. You can choose which mouse element this node reacts to. When mouse element is chosen to be a button, the only meaningful outputs are: outputs:pressed, outputs:released and outputs:isPressed. When scroll or move events are chosen, the only meaningful outputs are: outputs:valueChanged and outputs:value. You can choose to output normalized or pixel coordinates of the mouse. Pixel coordinates are the absolute position of the mouse cursor in pixel unit. The original point is the upper left corner. The minimum value is 0, and the maximum value depends on the size of the window. Normalized coordinates are the relative position of the mouse cursor to the window. The value is always between 0 and 1. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Mouse Element (*inputs:mouseElement*)", "``token``", "The event to trigger the downstream execution ", "Left Button" "", "*displayGroup*", "parameters", "" "", "*literalOnly*", "1", "" "", "*allowedTokens*", "Left Button,Middle Button,Right Button,Normalized Move,Pixel Move,Scroll", "" "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:isPressed", "``bool``", "True if the mouse button was pressed, False if it was released or mouse element is not related to a button", "None" "Pressed (*outputs:pressed*)", "``execution``", "Executes when mouse button was pressed. Will not execute on move or scroll events", "None" "Released (*outputs:released*)", "``execution``", "Executes when mouse button was released. Will not execute on move or scroll events", "None" "Delta Value (*outputs:value*)", "``float[2]``", "The meaning of this output depends on Event In. Normalized Move: will output the normalized coordinates of mouse, each element of the vector is in the range of [0, 1] Pixel Move: will output the absolute coordinates of mouse, each vector is in the range of [0, pixel width/height of the window] Scroll: will output the change of scroll value Otherwise: will output [0,0]", "None" "Moved (*outputs:valueChanged*)", "``execution``", "Executes when user moves the cursor or scrolls the cursor. Will not execute on button events", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnMouseInput" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On Mouse Input" "Categories", "graph:action,input:mouse" "Generated Class Name", "OgnOnMouseInputDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnImpulseEvent.rst
.. _omni_graph_action_OnImpulseEvent_2: .. _omni_graph_action_OnImpulseEvent: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Impulse Event :keywords: lang-en omnigraph node graph:action,event threadsafe compute-on-request action on-impulse-event On Impulse Event ================ .. <description> Triggers the output execution once when state is set .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Trigger (*outputs:execOut*)", "``execution``", "The execution output", "None" State ----- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "state:enableImpulse", "``bool``", "When true, execute output once and reset to false", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.OnImpulseEvent" "Version", "2" "Extension", "omni.graph.action" "Has State?", "True" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "On Impulse Event" "Categories", "graph:action,event" "Generated Class Name", "OgnOnImpulseEventDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSyncGate.rst
.. _omni_graph_action_SyncGate_1: .. _omni_graph_action_SyncGate: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sync Gate :keywords: lang-en omnigraph node graph:action,flowControl threadsafe action sync-gate Sync Gate ========= .. <description> This node triggers when all its input executions have triggered successively at the same synchronization value. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None" "Sync (*inputs:syncValue*)", "``uint64``", "Value of the synchronization reference.", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Execute Out (*outputs:execOut*)", "``execution``", "The output execution", "None" "Sync (*outputs:syncValue*)", "``uint64``", "Value of the synchronization reference.", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.action.SyncGate" "Version", "1" "Extension", "omni.graph.action" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Sync Gate" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnSyncGateDatabase" "Python Module", "omni.graph.action"
omniverse-code/kit/exts/omni.graph.action/PACKAGE-LICENSES/omni.graph.action-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.graph.action/config/extension.toml
[package] title = "OmniGraph Action Graph" version = "1.31.1" category = "Graph" feature = true # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" # Path (relative to the root) of the main documentation file. readme = "docs/README.md" changelog = "docs/CHANGELOG.md" description = "Contains nodes for Omnigraph Action Graphs." repository = "" keywords = ["omnigraph", "nodes", "action"] # Main module for the Python interface [[python.module]] name = "omni.graph.action" # Watch the .ogn files for hot reloading (only works for Python files) [fswatcher.patterns] include = ["*.ogn", "*.py"] exclude = ["Ogn*Database.py"] # Other extensions that need to load before this one [dependencies] "omni.usd" = { version = "1.4.8" } "omni.kit.async_engine" = {} "omni.kit.commands" = {} "omni.graph" = {} "omni.graph.ui" = { optional = true } "omni.graph.tools" = {} "omni.kit.stage_templates" = {} "omni.kit.pipapi" = {} "omni.kit.window.filepicker" = { optional = true } [[native.plugin]] path = "bin/*.plugin" recursive = false # numpy is used by tests [python.pipapi] requirements = ["numpy"] # SWIPAT filed under: http://nvbugs/3193231 [[test]] timeout = 300 stdoutFailPatterns.exclude = [ # Exclude carb.events leak that only shows up locally "*[Error] [carb.events.plugin]*PooledAllocator*", ] dependencies = [ # Required for gamepad node test "omni.appwindow", # Convenience for tests "omni.graph.nodes", "omni.inspect" ] [documentation] deps = [ ["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include OGN nodes until that workflow is moved ["omni.ui", "_build/docs/omni.ui/latest"], # ui_nodes.md references ] pages = [ "docs/Overview.md", "docs/ui_nodes.md", "docs/CHANGELOG.md", ]
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/__init__.py
"""Action Graph Functionality""" # Required to be able to instantiate the object types import omni.core from ._impl.extension import _PublicExtension # noqa: F401 # Interface from the ABI bindings from ._omni_graph_action import get_interface
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnGateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.Gate This node controls a flow of execution based on the state of its gate. The gate can be opened or closed by execution pulses sent to the gate controls """ 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 OgnGateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.Gate Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.enter inputs.startClosed inputs.toggle Outputs: outputs.exit """ # 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:enter', 'execution', 0, 'Enter', 'Incoming execution flow controlled by the gate', {}, True, None, False, ''), ('inputs:startClosed', 'bool', 0, 'Start Closed', 'If true the gate will start in a closed state', {}, True, False, False, ''), ('inputs:toggle', 'execution', 0, 'Toggle', 'The gate is opened or closed', {}, True, None, False, ''), ('outputs:exit', 'execution', 0, 'Exit', 'The enter pulses will be passed to this output if the gate is open', {}, 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.enter = og.AttributeRole.EXECUTION role_data.inputs.toggle = og.AttributeRole.EXECUTION role_data.outputs.exit = og.AttributeRole.EXECUTION 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 enter(self): data_view = og.AttributeValueHelper(self._attributes.enter) return data_view.get() @enter.setter def enter(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.enter) data_view = og.AttributeValueHelper(self._attributes.enter) data_view.set(value) @property def startClosed(self): data_view = og.AttributeValueHelper(self._attributes.startClosed) return data_view.get() @startClosed.setter def startClosed(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.startClosed) data_view = og.AttributeValueHelper(self._attributes.startClosed) data_view.set(value) @property def toggle(self): data_view = og.AttributeValueHelper(self._attributes.toggle) return data_view.get() @toggle.setter def toggle(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.toggle) data_view = og.AttributeValueHelper(self._attributes.toggle) 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 exit(self): data_view = og.AttributeValueHelper(self._attributes.exit) return data_view.get() @exit.setter def exit(self, value): data_view = og.AttributeValueHelper(self._attributes.exit) 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 = OgnGateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnGateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnGateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnBranchDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.Branch Outputs an execution pulse along a branch based on a boolean condition """ 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 OgnBranchDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.Branch Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.condition inputs.execIn Outputs: outputs.execFalse outputs.execTrue """ # 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:condition', 'bool', 0, 'Condition', 'The boolean condition which determines the output direction', {}, True, False, False, ''), ('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''), ('outputs:execFalse', 'execution', 0, 'False', 'The output path when condition is False', {}, True, None, False, ''), ('outputs:execTrue', 'execution', 0, 'True', 'The output path when condition is True', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.outputs.execFalse = og.AttributeRole.EXECUTION role_data.outputs.execTrue = og.AttributeRole.EXECUTION 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 condition(self): data_view = og.AttributeValueHelper(self._attributes.condition) return data_view.get() @condition.setter def condition(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.condition) data_view = og.AttributeValueHelper(self._attributes.condition) data_view.set(value) @property def execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) 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 execFalse(self): data_view = og.AttributeValueHelper(self._attributes.execFalse) return data_view.get() @execFalse.setter def execFalse(self, value): data_view = og.AttributeValueHelper(self._attributes.execFalse) data_view.set(value) @property def execTrue(self): data_view = og.AttributeValueHelper(self._attributes.execTrue) return data_view.get() @execTrue.setter def execTrue(self, value): data_view = og.AttributeValueHelper(self._attributes.execTrue) 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 = OgnBranchDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnBranchDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnBranchDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnMouseInputDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnMouseInput Event node which fires when a mouse event occurs. You can choose which mouse element this node reacts to. When mouse element is chosen to be a button, the only meaningful outputs are: outputs:pressed, outputs:released and outputs:isPressed. When scroll or move events are chosen, the only meaningful outputs are: outputs:valueChanged and outputs:value. You can choose to output normalized or pixel coordinates of the mouse. Pixel coordinates are the absolute position of the mouse cursor in pixel unit. The original point is the upper left corner. The minimum value is 0, and the maximum value depends on the size of the window. Normalized coordinates are the relative position of the mouse cursor to the window. The value is always between 0 and 1. """ 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 OgnOnMouseInputDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnMouseInput Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.mouseElement inputs.onlyPlayback Outputs: outputs.isPressed outputs.pressed outputs.released outputs.value outputs.valueChanged Predefined Tokens: tokens.LeftButton tokens.MiddleButton tokens.RightButton tokens.NormalizedMove tokens.PixelMove tokens.Scroll """ # 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:mouseElement', 'token', 0, 'Mouse Element', 'The event to trigger the downstream execution ', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Button,Middle Button,Right Button,Normalized Move,Pixel Move,Scroll', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftButton": "Left Button", "MiddleButton": "Middle Button", "RightButton": "Right Button", "NormalizedMove": "Normalized Move", "PixelMove": "Pixel Move", "Scroll": "Scroll"}', ogn.MetadataKeys.DEFAULT: '"Left Button"'}, True, "Left Button", False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:isPressed', 'bool', 0, None, 'True if the mouse button was pressed, False if it was released or mouse element is not related to a button', {}, True, None, False, ''), ('outputs:pressed', 'execution', 0, 'Pressed', 'Executes when mouse button was pressed. Will not execute on move or scroll events', {}, True, None, False, ''), ('outputs:released', 'execution', 0, 'Released', 'Executes when mouse button was released. Will not execute on move or scroll events', {}, True, None, False, ''), ('outputs:value', 'float2', 0, 'Delta Value', 'The meaning of this output depends on Event In.\nNormalized Move: will output the normalized coordinates of mouse, each element of the vector is in the range of [0, 1]\nPixel Move: will output the absolute coordinates of mouse, each vector is in the range of [0, pixel width/height of the window]\nScroll: will output the change of scroll value\nOtherwise: will output [0,0]', {}, True, None, False, ''), ('outputs:valueChanged', 'execution', 0, 'Moved', 'Executes when user moves the cursor or scrolls the cursor. Will not execute on button events', {}, True, None, False, ''), ]) class tokens: LeftButton = "Left Button" MiddleButton = "Middle Button" RightButton = "Right Button" NormalizedMove = "Normalized Move" PixelMove = "Pixel Move" Scroll = "Scroll" @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.pressed = og.AttributeRole.EXECUTION role_data.outputs.released = og.AttributeRole.EXECUTION role_data.outputs.valueChanged = og.AttributeRole.EXECUTION 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 mouseElement(self): data_view = og.AttributeValueHelper(self._attributes.mouseElement) return data_view.get() @mouseElement.setter def mouseElement(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.mouseElement) data_view = og.AttributeValueHelper(self._attributes.mouseElement) data_view.set(value) @property def onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) 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 isPressed(self): data_view = og.AttributeValueHelper(self._attributes.isPressed) return data_view.get() @isPressed.setter def isPressed(self, value): data_view = og.AttributeValueHelper(self._attributes.isPressed) data_view.set(value) @property def pressed(self): data_view = og.AttributeValueHelper(self._attributes.pressed) return data_view.get() @pressed.setter def pressed(self, value): data_view = og.AttributeValueHelper(self._attributes.pressed) data_view.set(value) @property def released(self): data_view = og.AttributeValueHelper(self._attributes.released) return data_view.get() @released.setter def released(self, value): data_view = og.AttributeValueHelper(self._attributes.released) data_view.set(value) @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) @property def valueChanged(self): data_view = og.AttributeValueHelper(self._attributes.valueChanged) return data_view.get() @valueChanged.setter def valueChanged(self, value): data_view = og.AttributeValueHelper(self._attributes.valueChanged) 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 = OgnOnMouseInputDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnMouseInputDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnMouseInputDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnImpulseEventDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnImpulseEvent Triggers the output execution once when state is set """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnImpulseEventDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnImpulseEvent Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.onlyPlayback Outputs: outputs.execOut State: state.enableImpulse """ # 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:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:execOut', 'execution', 0, 'Trigger', 'The execution output', {}, True, None, False, ''), ('state:enableImpulse', 'bool', 0, None, 'When true, execute output once and reset to false', {}, 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.execOut = og.AttributeRole.EXECUTION 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 onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) 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 execOut(self): data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): data_view = og.AttributeValueHelper(self._attributes.execOut) 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) @property def enableImpulse(self): data_view = og.AttributeValueHelper(self._attributes.enableImpulse) return data_view.get() @enableImpulse.setter def enableImpulse(self, value): data_view = og.AttributeValueHelper(self._attributes.enableImpulse) 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 = OgnOnImpulseEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnImpulseEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnImpulseEventDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnStageEventDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnStageEvent Executes when the specified Stage Event occurs. Stage Events are emitted when certain USD stage-related actions are performed by the system: Saved: USD file saved. Selection Changed: USD Prim selection has changed. Hierarchy Changed: USD stage hierarchy has changed, e.g. a prim is added, deleted or moved. OmniGraph Start Play: OmniGraph started OmniGraph Stop Play: OmniGraph stopped Simulation Start Play: Simulation started Simulation Stop Play: Simulation stopped Animation Start Play: Animation playback has started Animation Stop Play: Animation playback has stopped """ 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 OgnOnStageEventDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnStageEvent Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.eventName inputs.onlyPlayback Outputs: outputs.execOut Predefined Tokens: tokens.Saved tokens.SelectionChanged tokens.HierarchyChanged tokens.OmniGraphStart tokens.OmniGraphStop tokens.SimulationStart tokens.SimulationStop tokens.AnimationStart tokens.AnimationStop """ # 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:eventName', 'token', 0, None, 'The event of interest', {ogn.MetadataKeys.ALLOWED_TOKENS: 'Saved,Selection Changed,Hierarchy Changed,OmniGraph Start Play,OmniGraph Stop Play,Simulation Start Play,Simulation Stop Play,Animation Start Play,Animation Stop Play', 'default': 'Animation Start Play', 'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"Saved": "Saved", "SelectionChanged": "Selection Changed", "HierarchyChanged": "Hierarchy Changed", "OmniGraphStart": "OmniGraph Start Play", "OmniGraphStop": "OmniGraph Stop Play", "SimulationStart": "Simulation Start Play", "SimulationStop": "Simulation Stop Play", "AnimationStart": "Animation Start Play", "AnimationStop": "Animation Stop Play"}'}, True, "", False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:execOut', 'execution', 0, None, 'The execution output', {}, True, None, False, ''), ]) class tokens: Saved = "Saved" SelectionChanged = "Selection Changed" HierarchyChanged = "Hierarchy Changed" OmniGraphStart = "OmniGraph Start Play" OmniGraphStop = "OmniGraph Stop Play" SimulationStart = "Simulation Start Play" SimulationStop = "Simulation Stop Play" AnimationStart = "Animation Start Play" AnimationStop = "Animation Stop Play" @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.execOut = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"eventName", "onlyPlayback", "_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.eventName, self._attributes.onlyPlayback] self._batchedReadValues = ["", True] @property def eventName(self): return self._batchedReadValues[0] @eventName.setter def eventName(self, value): self._batchedReadValues[0] = value @property def onlyPlayback(self): return self._batchedReadValues[1] @onlyPlayback.setter def onlyPlayback(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 = {"execOut", "_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 execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = 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 = OgnOnStageEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnStageEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnStageEventDatabase.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(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.action.OnStageEvent' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnOnStageEventDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnOnStageEventDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnOnStageEventDatabase(node) try: compute_function = getattr(OgnOnStageEventDatabase.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 OgnOnStageEventDatabase.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): OgnOnStageEventDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnOnStageEventDatabase.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(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnOnStageEventDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnOnStageEventDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnOnStageEventDatabase.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(OgnOnStageEventDatabase.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.action") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On Stage Event") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Executes when the specified Stage Event occurs. Stage Events are emitted when certain USD stage-related actions are performed by the system:\n Saved: USD file saved.\n Selection Changed: USD Prim selection has changed.\n Hierarchy Changed: USD stage hierarchy has changed, e.g. a prim is added, deleted or moved.\n OmniGraph Start Play: OmniGraph started\n OmniGraph Stop Play: OmniGraph stopped\n Simulation Start Play: Simulation started\n Simulation Stop Play: Simulation stopped\n Animation Start Play: Animation playback has started\n Animation Stop Play: Animation playback has stopped") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.compute_rule = og.eComputeRule.E_ON_REQUEST OgnOnStageEventDatabase.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(OgnOnStageEventDatabase.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): OgnOnStageEventDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnOnStageEventDatabase.abi, 3) @staticmethod def deregister(): og.deregister_node_type("omni.graph.action.OnStageEvent")
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnForEachDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.ForEach Executes the a loop body once for each element in the input array. The finished output is executed after all iterations are complete """ 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 OgnForEachDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.ForEach Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.arrayIn inputs.execIn Outputs: outputs.arrayIndex outputs.element outputs.finished outputs.loopBody """ # 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:arrayIn', 'bool[],colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],double[2][],double[3][],double[4][],double[],float[2][],float[3][],float[4][],float[],frame[4][],half[2][],half[3][],half[4][],half[],int64[],int[2][],int[3][],int[4][],int[],matrixd[3][],matrixd[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],quatd[4][],quatf[4][],quath[4][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],timecode[],token[],transform[4][],uchar[],uint64[],uint[],vectord[3][],vectorf[3][],vectorh[3][]', 1, 'Input Array', 'The array to loop over', {}, True, None, False, ''), ('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''), ('outputs:arrayIndex', 'int', 0, None, 'The current or last index visited', {}, True, None, False, ''), ('outputs:element', 'bool,colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'The current or last element of the array visited', {}, True, None, False, ''), ('outputs:finished', 'execution', 0, None, 'Executed when the loop is finished', {}, True, None, False, ''), ('outputs:loopBody', 'execution', 0, None, 'Executed for each element of the 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.inputs.execIn = og.AttributeRole.EXECUTION role_data.outputs.finished = og.AttributeRole.EXECUTION role_data.outputs.loopBody = og.AttributeRole.EXECUTION 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 arrayIn(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.arrayIn""" return og.RuntimeAttribute(self._attributes.arrayIn.get_attribute_data(), self._context, True) @arrayIn.setter def arrayIn(self, value_to_set: Any): """Assign another attribute's value to outputs.arrayIn""" if isinstance(value_to_set, og.RuntimeAttribute): self.arrayIn.value = value_to_set.value else: self.arrayIn.value = value_to_set @property def execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) 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 arrayIndex(self): data_view = og.AttributeValueHelper(self._attributes.arrayIndex) return data_view.get() @arrayIndex.setter def arrayIndex(self, value): data_view = og.AttributeValueHelper(self._attributes.arrayIndex) data_view.set(value) @property def element(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute outputs.element""" return og.RuntimeAttribute(self._attributes.element.get_attribute_data(), self._context, False) @element.setter def element(self, value_to_set: Any): """Assign another attribute's value to outputs.element""" if isinstance(value_to_set, og.RuntimeAttribute): self.element.value = value_to_set.value else: self.element.value = value_to_set @property def finished(self): data_view = og.AttributeValueHelper(self._attributes.finished) return data_view.get() @finished.setter def finished(self, value): data_view = og.AttributeValueHelper(self._attributes.finished) data_view.set(value) @property def loopBody(self): data_view = og.AttributeValueHelper(self._attributes.loopBody) return data_view.get() @loopBody.setter def loopBody(self, value): data_view = og.AttributeValueHelper(self._attributes.loopBody) 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 = OgnForEachDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnForEachDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnForEachDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnCustomEventDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnCustomEvent Event node which fires when the specified custom event is sent. This node is used in combination with SendCustomEvent """ 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 OgnOnCustomEventDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnCustomEvent Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.eventName inputs.onlyPlayback Outputs: outputs.bundle outputs.execOut outputs.path """ # 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:eventName', 'token', 0, 'Event Name', 'The name of the custom event', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, "", False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:bundle', 'bundle', 0, 'Bundle', 'Bundle received with the event', {}, True, None, False, ''), ('outputs:execOut', 'execution', 0, 'Received', 'Executes when the event is received', {}, True, None, False, ''), ('outputs:path', 'token', 0, 'Path', 'The path associated with the received custom event', {}, 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 role_data.outputs.execOut = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"eventName", "onlyPlayback", "_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.eventName, self._attributes.onlyPlayback] self._batchedReadValues = ["", True] @property def eventName(self): return self._batchedReadValues[0] @eventName.setter def eventName(self, value): self._batchedReadValues[0] = value @property def onlyPlayback(self): return self._batchedReadValues[1] @onlyPlayback.setter def onlyPlayback(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 = {"execOut", "path", "_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.__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 @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value @property def path(self): value = self._batchedWriteValues.get(self._attributes.path) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.path) return data_view.get() @path.setter def path(self, value): self._batchedWriteValues[self._attributes.path] = 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 = OgnOnCustomEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnCustomEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnCustomEventDatabase.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(OgnOnCustomEventDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.action.OnCustomEvent' @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 = OgnOnCustomEventDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnOnCustomEventDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnOnCustomEventDatabase(node) try: compute_function = getattr(OgnOnCustomEventDatabase.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 OgnOnCustomEventDatabase.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): OgnOnCustomEventDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnOnCustomEventDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnOnCustomEventDatabase.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(OgnOnCustomEventDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnOnCustomEventDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnOnCustomEventDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnOnCustomEventDatabase.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(OgnOnCustomEventDatabase.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.action") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On Custom Event") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Event node which fires when the specified custom event is sent. This node is used in combination with SendCustomEvent") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.compute_rule = og.eComputeRule.E_ON_REQUEST OgnOnCustomEventDatabase.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(OgnOnCustomEventDatabase.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): OgnOnCustomEventDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnOnCustomEventDatabase.abi, 2) @staticmethod def deregister(): og.deregister_node_type("omni.graph.action.OnCustomEvent")
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnObjectChangeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnObjectChange Executes an output execution pulse when the watched USD Object changes """ import usdrt import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnObjectChangeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnObjectChange Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.name inputs.onlyPlayback inputs.path inputs.prim Outputs: outputs.changed outputs.propertyName """ # 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:name', 'token', 0, 'Property Name', 'The name of the property to watch if prim input is set', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, False, None, False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:path', 'path', 0, 'Path', 'The path of object of interest (property or prim). If the prim input has a target, this is ignored', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, False, None, True, 'Use prim input instead'), ('inputs:prim', 'target', 0, 'Prim', 'The prim of interest. If this has a target, the path input will be ignored', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, False, [], False, ''), ('outputs:changed', 'execution', 0, 'Changed', 'The execution output', {}, True, None, False, ''), ('outputs:propertyName', 'token', 0, 'Property Name', 'The name of the property that changed', {}, 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.path = og.AttributeRole.PATH role_data.inputs.prim = og.AttributeRole.TARGET role_data.outputs.changed = og.AttributeRole.EXECUTION 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 name(self): data_view = og.AttributeValueHelper(self._attributes.name) return data_view.get() @name.setter def name(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.name) data_view = og.AttributeValueHelper(self._attributes.name) data_view.set(value) @property def onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) data_view.set(value) @property def path(self): data_view = og.AttributeValueHelper(self._attributes.path) return data_view.get() @path.setter def path(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.path) data_view = og.AttributeValueHelper(self._attributes.path) data_view.set(value) self.path_size = data_view.get_array_size() @property def prim(self): data_view = og.AttributeValueHelper(self._attributes.prim) return data_view.get() @prim.setter def prim(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.prim) data_view = og.AttributeValueHelper(self._attributes.prim) data_view.set(value) self.prim_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._batchedWriteValues = { } @property def changed(self): data_view = og.AttributeValueHelper(self._attributes.changed) return data_view.get() @changed.setter def changed(self, value): data_view = og.AttributeValueHelper(self._attributes.changed) data_view.set(value) @property def propertyName(self): data_view = og.AttributeValueHelper(self._attributes.propertyName) return data_view.get() @propertyName.setter def propertyName(self, value): data_view = og.AttributeValueHelper(self._attributes.propertyName) 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 = OgnOnObjectChangeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnObjectChangeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnObjectChangeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnVariableChangeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnVariableChange Executes an output execution pulse when the chosen variable changes """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnVariableChangeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnVariableChange Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.onlyPlayback inputs.variableName Outputs: outputs.changed """ # 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:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:variableName', 'token', 0, 'Variable Name', 'The name of the graph variable to use.', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, "", False, ''), ('outputs:changed', 'execution', 0, 'Changed', 'The execution output', {}, 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.changed = og.AttributeRole.EXECUTION 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 onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) data_view.set(value) @property def variableName(self): data_view = og.AttributeValueHelper(self._attributes.variableName) return data_view.get() @variableName.setter def variableName(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.variableName) data_view = og.AttributeValueHelper(self._attributes.variableName) 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 changed(self): data_view = og.AttributeValueHelper(self._attributes.changed) return data_view.get() @changed.setter def changed(self, value): data_view = og.AttributeValueHelper(self._attributes.changed) 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 = OgnOnVariableChangeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnVariableChangeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnVariableChangeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnKeyboardInputDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnKeyboardInput Event node which fires when a keyboard event occurs. The event can be a combination of keys, containing key modifiers of ctrl, alt and shift, and a normal key of any key. keyIn. For key combinations, the press event requires all keys to be pressed, with the normal key pressed last. The release event is only triggered once when one of the chosen keys released after pressed event happens. For example: if the combination is ctrl-shift-D, the pressed event happens once right after D is pressed while both ctrl and shit are held. And the release event happens only once when the user releases any key of ctrl, shift and D while holding them. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnKeyboardInputDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnKeyboardInput Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.altIn inputs.ctrlIn inputs.keyIn inputs.onlyPlayback inputs.shiftIn Outputs: outputs.isPressed outputs.keyOut outputs.pressed outputs.released Predefined Tokens: tokens.A tokens.B tokens.C tokens.D tokens.E tokens.F tokens.G tokens.H tokens.I tokens.J tokens.K tokens.L tokens.M tokens.N tokens.O tokens.P tokens.Q tokens.R tokens.S tokens.T tokens.U tokens.V tokens.W tokens.X tokens.Y tokens.Z tokens.Apostrophe tokens.Backslash tokens.Backspace tokens.CapsLock tokens.Comma tokens.Del tokens.Down tokens.End tokens.Enter tokens.Equal tokens.Escape tokens.F1 tokens.F10 tokens.F11 tokens.F12 tokens.F2 tokens.F3 tokens.F4 tokens.F5 tokens.F6 tokens.F7 tokens.F8 tokens.F9 tokens.GraveAccent tokens.Home tokens.Insert tokens.Key0 tokens.Key1 tokens.Key2 tokens.Key3 tokens.Key4 tokens.Key5 tokens.Key6 tokens.Key7 tokens.Key8 tokens.Key9 tokens.Left tokens.LeftAlt tokens.LeftBracket tokens.LeftControl tokens.LeftShift tokens.LeftSuper tokens.Menu tokens.Minus tokens.NumLock tokens.Numpad0 tokens.Numpad1 tokens.Numpad2 tokens.Numpad3 tokens.Numpad4 tokens.Numpad5 tokens.Numpad6 tokens.Numpad7 tokens.Numpad8 tokens.Numpad9 tokens.NumpadAdd tokens.NumpadDel tokens.NumpadDivide tokens.NumpadEnter tokens.NumpadEqual tokens.NumpadMultiply tokens.NumpadSubtract tokens.PageDown tokens.PageUp tokens.Pause tokens.Period tokens.PrintScreen tokens.Right tokens.RightAlt tokens.RightBracket tokens.RightControl tokens.RightShift tokens.RightSuper tokens.ScrollLock tokens.Semicolon tokens.Slash tokens.Space tokens.Tab tokens.Up """ # 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:altIn', 'bool', 0, 'Alt', 'When true, the node will check with a key modifier Alt', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, False, False, ''), ('inputs:ctrlIn', 'bool', 0, 'Ctrl', 'When true, the node will check with a key modifier Control', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, False, False, ''), ('inputs:keyIn', 'token', 0, 'Key In', 'The key to trigger the downstream execution ', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,Apostrophe,Backslash,Backspace,CapsLock,Comma,Del,Down,End,Enter,Equal,Escape,F1,F10,F11,F12,F2,F3,F4,F5,F6,F7,F8,F9,GraveAccent,Home,Insert,Key0,Key1,Key2,Key3,Key4,Key5,Key6,Key7,Key8,Key9,Left,LeftAlt,LeftBracket,LeftControl,LeftShift,LeftSuper,Menu,Minus,NumLock,Numpad0,Numpad1,Numpad2,Numpad3,Numpad4,Numpad5,Numpad6,Numpad7,Numpad8,Numpad9,NumpadAdd,NumpadDel,NumpadDivide,NumpadEnter,NumpadEqual,NumpadMultiply,NumpadSubtract,PageDown,PageUp,Pause,Period,PrintScreen,Right,RightAlt,RightBracket,RightControl,RightShift,RightSuper,ScrollLock,Semicolon,Slash,Space,Tab,Up', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Apostrophe", "Backslash", "Backspace", "CapsLock", "Comma", "Del", "Down", "End", "Enter", "Equal", "Escape", "F1", "F10", "F11", "F12", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "GraveAccent", "Home", "Insert", "Key0", "Key1", "Key2", "Key3", "Key4", "Key5", "Key6", "Key7", "Key8", "Key9", "Left", "LeftAlt", "LeftBracket", "LeftControl", "LeftShift", "LeftSuper", "Menu", "Minus", "NumLock", "Numpad0", "Numpad1", "Numpad2", "Numpad3", "Numpad4", "Numpad5", "Numpad6", "Numpad7", "Numpad8", "Numpad9", "NumpadAdd", "NumpadDel", "NumpadDivide", "NumpadEnter", "NumpadEqual", "NumpadMultiply", "NumpadSubtract", "PageDown", "PageUp", "Pause", "Period", "PrintScreen", "Right", "RightAlt", "RightBracket", "RightControl", "RightShift", "RightSuper", "ScrollLock", "Semicolon", "Slash", "Space", "Tab", "Up"]', ogn.MetadataKeys.DEFAULT: '"A"'}, True, "A", False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:shiftIn', 'bool', 0, 'Shift', 'When true, the node will check with a key modifier Shift', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, False, False, ''), ('outputs:isPressed', 'bool', 0, None, 'True if the key was pressed, False if it was released', {}, True, None, False, ''), ('outputs:keyOut', 'token', 0, 'Key Out', 'The key that was pressed or released', {}, True, None, False, ''), ('outputs:pressed', 'execution', 0, 'Pressed', 'Executes when key was pressed', {}, True, None, False, ''), ('outputs:released', 'execution', 0, 'Released', 'Executes when key was released', {}, True, None, False, ''), ]) class tokens: A = "A" B = "B" C = "C" D = "D" E = "E" F = "F" G = "G" H = "H" I = "I" J = "J" K = "K" L = "L" M = "M" N = "N" O = "O" P = "P" Q = "Q" R = "R" S = "S" T = "T" U = "U" V = "V" W = "W" X = "X" Y = "Y" Z = "Z" Apostrophe = "Apostrophe" Backslash = "Backslash" Backspace = "Backspace" CapsLock = "CapsLock" Comma = "Comma" Del = "Del" Down = "Down" End = "End" Enter = "Enter" Equal = "Equal" Escape = "Escape" F1 = "F1" F10 = "F10" F11 = "F11" F12 = "F12" F2 = "F2" F3 = "F3" F4 = "F4" F5 = "F5" F6 = "F6" F7 = "F7" F8 = "F8" F9 = "F9" GraveAccent = "GraveAccent" Home = "Home" Insert = "Insert" Key0 = "Key0" Key1 = "Key1" Key2 = "Key2" Key3 = "Key3" Key4 = "Key4" Key5 = "Key5" Key6 = "Key6" Key7 = "Key7" Key8 = "Key8" Key9 = "Key9" Left = "Left" LeftAlt = "LeftAlt" LeftBracket = "LeftBracket" LeftControl = "LeftControl" LeftShift = "LeftShift" LeftSuper = "LeftSuper" Menu = "Menu" Minus = "Minus" NumLock = "NumLock" Numpad0 = "Numpad0" Numpad1 = "Numpad1" Numpad2 = "Numpad2" Numpad3 = "Numpad3" Numpad4 = "Numpad4" Numpad5 = "Numpad5" Numpad6 = "Numpad6" Numpad7 = "Numpad7" Numpad8 = "Numpad8" Numpad9 = "Numpad9" NumpadAdd = "NumpadAdd" NumpadDel = "NumpadDel" NumpadDivide = "NumpadDivide" NumpadEnter = "NumpadEnter" NumpadEqual = "NumpadEqual" NumpadMultiply = "NumpadMultiply" NumpadSubtract = "NumpadSubtract" PageDown = "PageDown" PageUp = "PageUp" Pause = "Pause" Period = "Period" PrintScreen = "PrintScreen" Right = "Right" RightAlt = "RightAlt" RightBracket = "RightBracket" RightControl = "RightControl" RightShift = "RightShift" RightSuper = "RightSuper" ScrollLock = "ScrollLock" Semicolon = "Semicolon" Slash = "Slash" Space = "Space" Tab = "Tab" Up = "Up" @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.pressed = og.AttributeRole.EXECUTION role_data.outputs.released = og.AttributeRole.EXECUTION 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 altIn(self): data_view = og.AttributeValueHelper(self._attributes.altIn) return data_view.get() @altIn.setter def altIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.altIn) data_view = og.AttributeValueHelper(self._attributes.altIn) data_view.set(value) @property def ctrlIn(self): data_view = og.AttributeValueHelper(self._attributes.ctrlIn) return data_view.get() @ctrlIn.setter def ctrlIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.ctrlIn) data_view = og.AttributeValueHelper(self._attributes.ctrlIn) data_view.set(value) @property def keyIn(self): data_view = og.AttributeValueHelper(self._attributes.keyIn) return data_view.get() @keyIn.setter def keyIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.keyIn) data_view = og.AttributeValueHelper(self._attributes.keyIn) data_view.set(value) @property def onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) data_view.set(value) @property def shiftIn(self): data_view = og.AttributeValueHelper(self._attributes.shiftIn) return data_view.get() @shiftIn.setter def shiftIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.shiftIn) data_view = og.AttributeValueHelper(self._attributes.shiftIn) 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 isPressed(self): data_view = og.AttributeValueHelper(self._attributes.isPressed) return data_view.get() @isPressed.setter def isPressed(self, value): data_view = og.AttributeValueHelper(self._attributes.isPressed) data_view.set(value) @property def keyOut(self): data_view = og.AttributeValueHelper(self._attributes.keyOut) return data_view.get() @keyOut.setter def keyOut(self, value): data_view = og.AttributeValueHelper(self._attributes.keyOut) data_view.set(value) @property def pressed(self): data_view = og.AttributeValueHelper(self._attributes.pressed) return data_view.get() @pressed.setter def pressed(self, value): data_view = og.AttributeValueHelper(self._attributes.pressed) data_view.set(value) @property def released(self): data_view = og.AttributeValueHelper(self._attributes.released) return data_view.get() @released.setter def released(self, value): data_view = og.AttributeValueHelper(self._attributes.released) 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 = OgnOnKeyboardInputDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnKeyboardInputDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnKeyboardInputDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnPlaybackTickDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnPlaybackTick Executes an output execution pulse during playback """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnPlaybackTickDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnPlaybackTick Class Members: node: Node being evaluated Attribute Value Properties: Outputs: outputs.deltaSeconds outputs.frame outputs.tick outputs.time """ # 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([ ('outputs:deltaSeconds', 'double', 0, 'Delta Seconds', 'The number of seconds elapsed since the last update', {}, True, None, False, ''), ('outputs:frame', 'double', 0, 'Frame', 'The global playback time in frames, equivalent to (time * fps)', {}, True, None, False, ''), ('outputs:tick', 'execution', 0, 'Tick', 'The execution output', {}, True, None, False, ''), ('outputs:time', 'double', 0, 'Time', 'The global playback time in seconds', {}, 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.tick = og.AttributeRole.EXECUTION 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 = [] 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 deltaSeconds(self): data_view = og.AttributeValueHelper(self._attributes.deltaSeconds) return data_view.get() @deltaSeconds.setter def deltaSeconds(self, value): data_view = og.AttributeValueHelper(self._attributes.deltaSeconds) data_view.set(value) @property def frame(self): data_view = og.AttributeValueHelper(self._attributes.frame) return data_view.get() @frame.setter def frame(self, value): data_view = og.AttributeValueHelper(self._attributes.frame) data_view.set(value) @property def tick(self): data_view = og.AttributeValueHelper(self._attributes.tick) return data_view.get() @tick.setter def tick(self, value): data_view = og.AttributeValueHelper(self._attributes.tick) data_view.set(value) @property def time(self): data_view = og.AttributeValueHelper(self._attributes.time) return data_view.get() @time.setter def time(self, value): data_view = og.AttributeValueHelper(self._attributes.time) 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 = OgnOnPlaybackTickDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnPlaybackTickDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnPlaybackTickDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnMessageBusEventDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnMessageBusEvent Event node which fires when the specified event is popped from the App Message Bus. Carb events can be sent with Python: msg = carb.events.type_from_string('my_event_name') omni.kit.app.get_app().get_message_bus_event_stream().push(msg, payload={'arg1': 42}) The event payload data will be copied in to matching dynamic output attributes if they exist. In the previous example, 42 would be copied to outputs:arg1 if possible """ 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 OgnOnMessageBusEventDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnMessageBusEvent Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.eventName inputs.onlyPlayback Outputs: outputs.execOut """ # 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:eventName', 'token', 0, 'Event Name', 'The name of the custom event', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, "", False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:execOut', 'execution', 0, 'Received', 'Executes when the event is received', {}, 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.execOut = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"eventName", "onlyPlayback", "_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.eventName, self._attributes.onlyPlayback] self._batchedReadValues = ["", True] @property def eventName(self): return self._batchedReadValues[0] @eventName.setter def eventName(self, value): self._batchedReadValues[0] = value @property def onlyPlayback(self): return self._batchedReadValues[1] @onlyPlayback.setter def onlyPlayback(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 = {"execOut", "_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 execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = 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 = OgnOnMessageBusEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnMessageBusEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnMessageBusEventDatabase.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(OgnOnMessageBusEventDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.action.OnMessageBusEvent' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnOnMessageBusEventDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnOnMessageBusEventDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnOnMessageBusEventDatabase(node) try: compute_function = getattr(OgnOnMessageBusEventDatabase.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 OgnOnMessageBusEventDatabase.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): OgnOnMessageBusEventDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnOnMessageBusEventDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnOnMessageBusEventDatabase.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(OgnOnMessageBusEventDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnOnMessageBusEventDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnOnMessageBusEventDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnOnMessageBusEventDatabase.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(OgnOnMessageBusEventDatabase.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.action") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On MessageBus Event") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Event node which fires when the specified event is popped from the App Message Bus. Carb events can be sent with Python: msg = carb.events.type_from_string('my_event_name') omni.kit.app.get_app().get_message_bus_event_stream().push(msg, payload={'arg1': 42}) The event payload data will be copied in to matching dynamic output attributes if they exist. In the previous example, 42 would be copied to outputs:arg1 if possible") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.compute_rule = og.eComputeRule.E_ON_REQUEST OgnOnMessageBusEventDatabase.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(OgnOnMessageBusEventDatabase.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): OgnOnMessageBusEventDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnOnMessageBusEventDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.action.OnMessageBusEvent")
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnCountdownDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.Countdown Delays for a number of updates (the duration) while firing output tick activations with a given period. When the countdown is complete it triggers the finished output. The first compute does not generate a tick output. """ 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 OgnCountdownDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.Countdown Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.duration inputs.execIn inputs.period Outputs: outputs.alpha outputs.finished outputs.tick outputs.tickValue State: state.count """ # 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:duration', 'int', 0, None, 'The duration of the delay in ticks', {ogn.MetadataKeys.DEFAULT: '5'}, True, 5, False, ''), ('inputs:execIn', 'execution', 0, None, 'The input execution', {}, True, None, False, ''), ('inputs:period', 'int', 0, None, 'The period of the pulse in ticks', {ogn.MetadataKeys.DEFAULT: '1'}, True, 1, False, ''), ('outputs:alpha', 'float', 0, None, "normalized progress in the range IE 'tickValue'/'duration'", {}, True, None, False, ''), ('outputs:finished', 'execution', 0, None, 'Triggered after duration ticks is finished', {}, True, None, False, ''), ('outputs:tick', 'execution', 0, None, "Triggered every 'period' ticks", {}, True, None, False, ''), ('outputs:tickValue', 'int', 0, None, 'The current tick value in the range [1, duration]', {}, True, None, False, ''), ('state:count', 'int', 0, None, 'The number of ticks elapsed, the first tick is 0', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, 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.execIn = og.AttributeRole.EXECUTION role_data.outputs.finished = og.AttributeRole.EXECUTION role_data.outputs.tick = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"duration", "execIn", "period", "_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.duration, self._attributes.execIn, self._attributes.period] self._batchedReadValues = [5, None, 1] @property def duration(self): return self._batchedReadValues[0] @duration.setter def duration(self, value): self._batchedReadValues[0] = value @property def execIn(self): return self._batchedReadValues[1] @execIn.setter def execIn(self, value): self._batchedReadValues[1] = value @property def period(self): return self._batchedReadValues[2] @period.setter def period(self, value): self._batchedReadValues[2] = 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 = {"alpha", "finished", "tick", "tickValue", "_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 alpha(self): value = self._batchedWriteValues.get(self._attributes.alpha) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.alpha) return data_view.get() @alpha.setter def alpha(self, value): self._batchedWriteValues[self._attributes.alpha] = value @property def finished(self): value = self._batchedWriteValues.get(self._attributes.finished) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.finished) return data_view.get() @finished.setter def finished(self, value): self._batchedWriteValues[self._attributes.finished] = value @property def tick(self): value = self._batchedWriteValues.get(self._attributes.tick) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.tick) return data_view.get() @tick.setter def tick(self, value): self._batchedWriteValues[self._attributes.tick] = value @property def tickValue(self): value = self._batchedWriteValues.get(self._attributes.tickValue) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.tickValue) return data_view.get() @tickValue.setter def tickValue(self, value): self._batchedWriteValues[self._attributes.tickValue] = 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) @property def count(self): data_view = og.AttributeValueHelper(self._attributes.count) return data_view.get() @count.setter def count(self, value): data_view = og.AttributeValueHelper(self._attributes.count) 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 = OgnCountdownDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnCountdownDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnCountdownDatabase.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(OgnCountdownDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.action.Countdown' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnCountdownDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnCountdownDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnCountdownDatabase(node) try: compute_function = getattr(OgnCountdownDatabase.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 OgnCountdownDatabase.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): OgnCountdownDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnCountdownDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnCountdownDatabase.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(OgnCountdownDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnCountdownDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnCountdownDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnCountdownDatabase.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(OgnCountdownDatabase.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.action") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Countdown") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,flowControl") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Delays for a number of updates (the duration) while firing output tick activations with a given period. When the countdown is complete it triggers the finished output. The first compute does not generate a tick output.") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnCountdownDatabase.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(OgnCountdownDatabase.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): OgnCountdownDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnCountdownDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.action.Countdown")
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnGamepadInputDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnGamepadInput Event node which fires when a gamepad event occurs. This node only capture events on buttons, excluding triggers and sticks """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnGamepadInputDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnGamepadInput Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gamepadElementIn inputs.gamepadId inputs.onlyPlayback Outputs: outputs.isPressed outputs.pressed outputs.released Predefined Tokens: tokens.FaceButtonBottom tokens.FaceButtonRight tokens.FaceButtonLeft tokens.FaceButtonTop tokens.LeftShoulder tokens.RightShoulder tokens.SpecialLeft tokens.SpecialRight tokens.LeftStickButton tokens.RightStickButton tokens.DpadUp tokens.DpadRight tokens.DpadDown tokens.DpadLeft """ # 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:gamepadElementIn', 'token', 0, 'Gamepad Element In', 'The gamepad button to trigger the downstream execution.', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Face Button Bottom,Face Button Right,Face Button Left,Face Button Top,Left Shoulder,Right Shoulder,Special Left,Special Right,Left Stick Button,Right Stick Button,D-Pad Up,D-Pad Right,D-Pad Down,D-Pad Left', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"FaceButtonBottom": "Face Button Bottom", "FaceButtonRight": "Face Button Right", "FaceButtonLeft": "Face Button Left", "FaceButtonTop": "Face Button Top", "LeftShoulder": "Left Shoulder", "RightShoulder": "Right Shoulder", "SpecialLeft": "Special Left", "SpecialRight": "Special Right", "LeftStickButton": "Left Stick Button", "RightStickButton": "Right Stick Button", "DpadUp": "D-Pad Up", "DpadRight": "D-Pad Right", "DpadDown": "D-Pad Down", "DpadLeft": "D-Pad Left"}', ogn.MetadataKeys.DEFAULT: '"Face Button Bottom"'}, True, "Face Button Bottom", False, ''), ('inputs:gamepadId', 'uint', 0, 'Gamepad ID', 'Gamepad id number starting from 0. Each gamepad will be registered automatically with an unique ID monotonically increasing in the order they are connected.\nIf gamepad is disconnected, the ID assigned to the remaining gamepad will be adjusted accordingly so the IDs are always continues and start from 0\nChange this value to a non-existing ID will result an error prompt in the console and the node will not listen to any gamepad input.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:isPressed', 'bool', 0, None, 'True if the gamepad button was pressed, False if it was released', {}, True, None, False, ''), ('outputs:pressed', 'execution', 0, 'Pressed', 'Executes when gamepad element was pressed', {}, True, None, False, ''), ('outputs:released', 'execution', 0, 'Released', 'Executes when gamepad element was released', {}, True, None, False, ''), ]) class tokens: FaceButtonBottom = "Face Button Bottom" FaceButtonRight = "Face Button Right" FaceButtonLeft = "Face Button Left" FaceButtonTop = "Face Button Top" LeftShoulder = "Left Shoulder" RightShoulder = "Right Shoulder" SpecialLeft = "Special Left" SpecialRight = "Special Right" LeftStickButton = "Left Stick Button" RightStickButton = "Right Stick Button" DpadUp = "D-Pad Up" DpadRight = "D-Pad Right" DpadDown = "D-Pad Down" DpadLeft = "D-Pad Left" @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.pressed = og.AttributeRole.EXECUTION role_data.outputs.released = og.AttributeRole.EXECUTION 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 gamepadElementIn(self): data_view = og.AttributeValueHelper(self._attributes.gamepadElementIn) return data_view.get() @gamepadElementIn.setter def gamepadElementIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gamepadElementIn) data_view = og.AttributeValueHelper(self._attributes.gamepadElementIn) data_view.set(value) @property def gamepadId(self): data_view = og.AttributeValueHelper(self._attributes.gamepadId) return data_view.get() @gamepadId.setter def gamepadId(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gamepadId) data_view = og.AttributeValueHelper(self._attributes.gamepadId) data_view.set(value) @property def onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) 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 isPressed(self): data_view = og.AttributeValueHelper(self._attributes.isPressed) return data_view.get() @isPressed.setter def isPressed(self, value): data_view = og.AttributeValueHelper(self._attributes.isPressed) data_view.set(value) @property def pressed(self): data_view = og.AttributeValueHelper(self._attributes.pressed) return data_view.get() @pressed.setter def pressed(self, value): data_view = og.AttributeValueHelper(self._attributes.pressed) data_view.set(value) @property def released(self): data_view = og.AttributeValueHelper(self._attributes.released) return data_view.get() @released.setter def released(self, value): data_view = og.AttributeValueHelper(self._attributes.released) 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 = OgnOnGamepadInputDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnGamepadInputDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnGamepadInputDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnSendCustomEventDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.SendCustomEvent Sends a custom event, which will asynchronously trigger any OnCustomEvent nodes which are listening for the same eventName """ 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 OgnSendCustomEventDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.SendCustomEvent Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.bundle inputs.eventName inputs.execIn inputs.path Outputs: outputs.execOut """ # 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, 'Bundle', 'Bundle to be sent with the event', {}, False, None, False, ''), ('inputs:eventName', 'token', 0, 'Event Name', 'The name of the custom event', {}, True, "", False, ''), ('inputs:execIn', 'execution', 0, None, 'Input Execution', {}, True, None, False, ''), ('inputs:path', 'token', 0, 'Path', 'The path associated with the event', {}, True, "", False, ''), ('outputs:execOut', 'execution', 0, None, 'Output Execution', {}, 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.inputs.execIn = og.AttributeRole.EXECUTION role_data.outputs.execOut = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"eventName", "execIn", "path", "_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, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [self._attributes.eventName, self._attributes.execIn, self._attributes.path] self._batchedReadValues = ["", None, ""] @property def bundle(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.bundle""" return self.__bundles.bundle @property def eventName(self): return self._batchedReadValues[0] @eventName.setter def eventName(self, value): self._batchedReadValues[0] = value @property def execIn(self): return self._batchedReadValues[1] @execIn.setter def execIn(self, value): self._batchedReadValues[1] = value @property def path(self): return self._batchedReadValues[2] @path.setter def path(self, value): self._batchedReadValues[2] = 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 = {"execOut", "_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 execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = 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 = OgnSendCustomEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSendCustomEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSendCustomEventDatabase.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(OgnSendCustomEventDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.action.SendCustomEvent' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnSendCustomEventDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnSendCustomEventDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnSendCustomEventDatabase(node) try: compute_function = getattr(OgnSendCustomEventDatabase.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 OgnSendCustomEventDatabase.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): OgnSendCustomEventDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnSendCustomEventDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnSendCustomEventDatabase.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(OgnSendCustomEventDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnSendCustomEventDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnSendCustomEventDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnSendCustomEventDatabase.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(OgnSendCustomEventDatabase.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.action") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Send Custom Event") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Sends a custom event, which will asynchronously trigger any OnCustomEvent nodes which are listening for the same eventName") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnSendCustomEventDatabase.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(OgnSendCustomEventDatabase.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): OgnSendCustomEventDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnSendCustomEventDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.action.SendCustomEvent")
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnLoadedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnLoaded Triggers the output on the first update of the graph after it is created or loaded. This will run before any other event node, and will only run once after this node is created. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnLoadedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnLoaded Class Members: node: Node being evaluated Attribute Value Properties: Outputs: outputs.execOut """ # 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([ ('outputs:execOut', 'execution', 0, None, 'Executes after graph creation or loading', {}, 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.execOut = og.AttributeRole.EXECUTION 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 = [] 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 execOut(self): data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): data_view = og.AttributeValueHelper(self._attributes.execOut) 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 = OgnOnLoadedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnLoadedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnLoadedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnSyncGateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.SyncGate This node triggers when all its input executions have triggered successively at the same synchronization value. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSyncGateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.SyncGate Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.syncValue Outputs: outputs.execOut outputs.syncValue """ # 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:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''), ('inputs:syncValue', 'uint64', 0, 'Sync', 'Value of the synchronization reference.', {}, True, 0, False, ''), ('outputs:execOut', 'execution', 0, 'Execute Out', 'The output execution', {}, True, None, False, ''), ('outputs:syncValue', 'uint64', 0, 'Sync', 'Value of the synchronization reference.', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.outputs.execOut = og.AttributeRole.EXECUTION 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) data_view.set(value) @property def syncValue(self): data_view = og.AttributeValueHelper(self._attributes.syncValue) return data_view.get() @syncValue.setter def syncValue(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.syncValue) data_view = og.AttributeValueHelper(self._attributes.syncValue) 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 execOut(self): data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): data_view = og.AttributeValueHelper(self._attributes.execOut) data_view.set(value) @property def syncValue(self): data_view = og.AttributeValueHelper(self._attributes.syncValue) return data_view.get() @syncValue.setter def syncValue(self, value): data_view = og.AttributeValueHelper(self._attributes.syncValue) 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 = OgnSyncGateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSyncGateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSyncGateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnMultisequenceDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.Multisequence Outputs an execution pulse along each of its N outputs in sequence. For every single input execution pulse, each and every output will be exclusively enabled in order. """ 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 OgnMultisequenceDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.Multisequence Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn Outputs: outputs.output0 """ # 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:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''), ('outputs:output0', 'execution', 0, None, 'Output execution', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.outputs.output0 = og.AttributeRole.EXECUTION 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) 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 output0(self): data_view = og.AttributeValueHelper(self._attributes.output0) return data_view.get() @output0.setter def output0(self, value): data_view = og.AttributeValueHelper(self._attributes.output0) 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 = OgnMultisequenceDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnMultisequenceDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnMultisequenceDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnDelayDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.Delay This node suspends the graph for a period of time before continuing. This node, and nodes upstream of this node are locked for the duration of the delay, which means any subsequent executions will be ignored. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnDelayDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.Delay Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.duration inputs.execIn Outputs: outputs.finished """ # 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:duration', 'double', 0, 'Duration', 'The duration of the delay (Seconds)', {}, True, 0.0, False, ''), ('inputs:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''), ('outputs:finished', 'execution', 0, 'Finished', 'Triggered when the delay is finished', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.outputs.finished = og.AttributeRole.EXECUTION 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 duration(self): data_view = og.AttributeValueHelper(self._attributes.duration) return data_view.get() @duration.setter def duration(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.duration) data_view = og.AttributeValueHelper(self._attributes.duration) data_view.set(value) @property def execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) 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 finished(self): data_view = og.AttributeValueHelper(self._attributes.finished) return data_view.get() @finished.setter def finished(self, value): data_view = og.AttributeValueHelper(self._attributes.finished) 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 = OgnDelayDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnDelayDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnDelayDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnCounterDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.Counter This node counts the number of times it is computed since being reset """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnCounterDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.Counter Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.reset Outputs: outputs.count outputs.execOut State: state.count """ # 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:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''), ('inputs:reset', 'execution', 0, 'Reset', 'Reset the internal counter', {}, True, None, False, ''), ('outputs:count', 'int', 0, 'Count', 'The count value', {}, True, None, False, ''), ('outputs:execOut', 'execution', 0, 'Execute Out', 'The output execution', {}, True, None, False, ''), ('state:count', 'int', 0, None, 'The counter state', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.inputs.reset = og.AttributeRole.EXECUTION role_data.outputs.execOut = og.AttributeRole.EXECUTION 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) 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): if self._setting_locked: raise og.ReadOnlyError(self._attributes.reset) data_view = og.AttributeValueHelper(self._attributes.reset) 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 count(self): data_view = og.AttributeValueHelper(self._attributes.count) return data_view.get() @count.setter def count(self, value): data_view = og.AttributeValueHelper(self._attributes.count) data_view.set(value) @property def execOut(self): data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): data_view = og.AttributeValueHelper(self._attributes.execOut) 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) @property def count(self): data_view = og.AttributeValueHelper(self._attributes.count) return data_view.get() @count.setter def count(self, value): data_view = og.AttributeValueHelper(self._attributes.count) 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 = OgnCounterDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnCounterDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnCounterDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnSetPrimActiveDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.SetPrimActive Set a Prim active or not in the stage. """ import usdrt import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSetPrimActiveDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.SetPrimActive Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.active inputs.execIn inputs.prim inputs.primTarget Outputs: outputs.execOut """ # 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:active', 'bool', 0, None, 'Wheter to set the prim active or not', {}, True, False, False, ''), ('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''), ('inputs:prim', 'path', 0, 'Prim Path', 'The prim to be (de)activated', {}, True, "", True, 'Use the primTarget input instead'), ('inputs:primTarget', 'target', 0, 'Prim', 'The prim to be (de)activated', {}, True, [], False, ''), ('outputs:execOut', 'execution', 0, 'Execute Out', 'The output execution', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.inputs.prim = og.AttributeRole.PATH role_data.inputs.primTarget = og.AttributeRole.TARGET role_data.outputs.execOut = og.AttributeRole.EXECUTION 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 active(self): data_view = og.AttributeValueHelper(self._attributes.active) return data_view.get() @active.setter def active(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.active) data_view = og.AttributeValueHelper(self._attributes.active) data_view.set(value) @property def execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) data_view.set(value) @property def prim(self): data_view = og.AttributeValueHelper(self._attributes.prim) return data_view.get() @prim.setter def prim(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.prim) data_view = og.AttributeValueHelper(self._attributes.prim) data_view.set(value) self.prim_size = data_view.get_array_size() @property def primTarget(self): data_view = og.AttributeValueHelper(self._attributes.primTarget) return data_view.get() @primTarget.setter def primTarget(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.primTarget) data_view = og.AttributeValueHelper(self._attributes.primTarget) data_view.set(value) self.primTarget_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._batchedWriteValues = { } @property def execOut(self): data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): data_view = og.AttributeValueHelper(self._attributes.execOut) 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 = OgnSetPrimActiveDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSetPrimActiveDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSetPrimActiveDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnSwitchTokenDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.SwitchToken Outputs an execution pulse along a branch which matches the input token. For example if inputs:value is set to 'A' it will continue downstream from outputs:outputNN if there is an inputs:branchNN is set to 'A' """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSwitchTokenDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.SwitchToken Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.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:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''), ('inputs:value', 'token', 0, 'Value', 'The value to switch on', {}, True, "", 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.execIn = og.AttributeRole.EXECUTION 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) data_view.set(value) @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 = { } 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 = OgnSwitchTokenDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSwitchTokenDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSwitchTokenDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnSequenceDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.Sequence Outputs an execution pulse along output A and B in sequence """ 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 OgnSequenceDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.Sequence Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn Outputs: outputs.a outputs.b """ # 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:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''), ('outputs:a', 'execution', 0, 'A', 'The first output path', {}, True, None, False, ''), ('outputs:b', 'execution', 0, 'B', 'The second outputs path', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.outputs.a = og.AttributeRole.EXECUTION role_data.outputs.b = og.AttributeRole.EXECUTION 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) 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(self): data_view = og.AttributeValueHelper(self._attributes.a) return data_view.get() @a.setter def a(self, value): 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): data_view = og.AttributeValueHelper(self._attributes.b) 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 = OgnSequenceDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSequenceDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSequenceDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnTickNDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.TickN Delays for a number of updates while firing output tick activations with a given period """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import traceback import sys class OgnTickNDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.TickN Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.duration inputs.execIn inputs.period Outputs: outputs.finished outputs.tick """ # 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:duration', 'int', 0, None, 'The duration of the delay in ticks', {}, True, 0, False, ''), ('inputs:execIn', 'execution', 0, None, 'The input execution', {}, True, None, False, ''), ('inputs:period', 'int', 0, None, 'The period of the pulse in ticks', {ogn.MetadataKeys.DEFAULT: '1'}, True, 1, False, ''), ('outputs:finished', 'execution', 0, None, 'Triggered when the delay is finished', {}, True, None, False, ''), ('outputs:tick', 'execution', 0, None, 'Triggered every period ticks', {}, 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.execIn = og.Database.ROLE_EXECUTION role_data.outputs.finished = og.Database.ROLE_EXECUTION role_data.outputs.tick = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"duration", "execIn", "period", "_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.duration, self._attributes.execIn, self._attributes.period] self._batchedReadValues = [0, None, 1] @property def duration(self): return self._batchedReadValues[0] @duration.setter def duration(self, value): self._batchedReadValues[0] = value @property def execIn(self): return self._batchedReadValues[1] @execIn.setter def execIn(self, value): self._batchedReadValues[1] = value @property def period(self): return self._batchedReadValues[2] @period.setter def period(self, value): self._batchedReadValues[2] = 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 = {"finished", "tick", "_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 finished(self): value = self._batchedWriteValues.get(self._attributes.finished) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.finished) return data_view.get() @finished.setter def finished(self, value): self._batchedWriteValues[self._attributes.finished] = value @property def tick(self): value = self._batchedWriteValues.get(self._attributes.tick) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.tick) return data_view.get() @tick.setter def tick(self, value): self._batchedWriteValues[self._attributes.tick] = 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 = OgnTickNDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnTickNDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnTickNDatabase.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(OgnTickNDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.action.TickN' @staticmethod def compute(context, node): try: per_node_data = OgnTickNDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnTickNDatabase(node) per_node_data['_db'] = db except: db = OgnTickNDatabase(node) try: compute_function = getattr(OgnTickNDatabase.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 OgnTickNDatabase.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): OgnTickNDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnTickNDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnTickNDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnTickNDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnTickNDatabase.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(OgnTickNDatabase.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.action") node_type.set_metadata(ogn.MetadataKeys.HIDDEN, "true") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "TickN") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "internal:test") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Delays for a number of updates while firing output tick activations with a given period") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests,usd,docs") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnTickNDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnTickNDatabase.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 GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnTickNDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnTickNDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.action.TickN")
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnceDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.Once Controls flow of execution by passing input through differently on the first time """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnceDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.Once Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.reset Outputs: outputs.after outputs.once """ # 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:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''), ('inputs:reset', 'execution', 0, None, 'Resets the gate state to closed. The next execIn impulse will pass the gate.', {}, True, None, False, ''), ('outputs:after', 'execution', 0, None, 'Executes after the first time', {}, True, None, False, ''), ('outputs:once', 'execution', 0, None, "Executes the first time (or the first time after a 'reset'.", {}, 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.execIn = og.AttributeRole.EXECUTION role_data.inputs.reset = og.AttributeRole.EXECUTION role_data.outputs.after = og.AttributeRole.EXECUTION role_data.outputs.once = og.AttributeRole.EXECUTION 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) 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): if self._setting_locked: raise og.ReadOnlyError(self._attributes.reset) data_view = og.AttributeValueHelper(self._attributes.reset) 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 after(self): data_view = og.AttributeValueHelper(self._attributes.after) return data_view.get() @after.setter def after(self, value): data_view = og.AttributeValueHelper(self._attributes.after) data_view.set(value) @property def once(self): data_view = og.AttributeValueHelper(self._attributes.once) return data_view.get() @once.setter def once(self, value): data_view = og.AttributeValueHelper(self._attributes.once) 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 = OgnOnceDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnceDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnceDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnFlipFlopDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.FlipFlop This node alternates activating its outputs, starting with A """ 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 OgnFlipFlopDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.FlipFlop Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn Outputs: outputs.a outputs.b outputs.isA """ # 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:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''), ('outputs:a', 'execution', 0, 'Execute A', 'Executed on the 1st and odd numbered triggers', {}, True, None, False, ''), ('outputs:b', 'execution', 0, 'Execute B', 'Executed on the even number triggers', {}, True, None, False, ''), ('outputs:isA', 'bool', 0, 'Is A', 'Set to true when a is activated', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.outputs.a = og.AttributeRole.EXECUTION role_data.outputs.b = og.AttributeRole.EXECUTION 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) 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(self): data_view = og.AttributeValueHelper(self._attributes.a) return data_view.get() @a.setter def a(self, value): 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): data_view = og.AttributeValueHelper(self._attributes.b) data_view.set(value) @property def isA(self): data_view = og.AttributeValueHelper(self._attributes.isA) return data_view.get() @isA.setter def isA(self, value): data_view = og.AttributeValueHelper(self._attributes.isA) 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 = OgnFlipFlopDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnFlipFlopDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnFlipFlopDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnAddPrimRelationshipDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.AddPrimRelationship Adds a target path to a relationship property. If the relationship property does not exist it will be created. Duplicate targets will not be added. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnAddPrimRelationshipDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.AddPrimRelationship Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.name inputs.path inputs.target Outputs: outputs.isSuccessful """ # 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:execIn', 'execution', 0, None, 'The input execution port.', {}, True, None, False, ''), ('inputs:name', 'token', 0, 'Relationship Name', 'Name of the relationship property.', {}, True, "", False, ''), ('inputs:path', 'path', 0, 'Prim Path', 'Path of the prim with the relationship property.', {}, True, "", False, ''), ('inputs:target', 'path', 0, 'Target Path', 'The target path to be added, which may be a prim, attribute or another relationship.', {}, True, "", False, ''), ('outputs:isSuccessful', 'bool', 0, 'Is Successful', 'Whether the node has successfully added the new target to the relationship.', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.inputs.path = og.AttributeRole.PATH role_data.inputs.target = og.AttributeRole.PATH 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) data_view.set(value) @property def name(self): data_view = og.AttributeValueHelper(self._attributes.name) return data_view.get() @name.setter def name(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.name) data_view = og.AttributeValueHelper(self._attributes.name) data_view.set(value) @property def path(self): data_view = og.AttributeValueHelper(self._attributes.path) return data_view.get() @path.setter def path(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.path) data_view = og.AttributeValueHelper(self._attributes.path) data_view.set(value) self.path_size = data_view.get_array_size() @property def target(self): data_view = og.AttributeValueHelper(self._attributes.target) return data_view.get() @target.setter def target(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.target) data_view = og.AttributeValueHelper(self._attributes.target) data_view.set(value) self.target_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._batchedWriteValues = { } @property def isSuccessful(self): data_view = og.AttributeValueHelper(self._attributes.isSuccessful) return data_view.get() @isSuccessful.setter def isSuccessful(self, value): data_view = og.AttributeValueHelper(self._attributes.isSuccessful) 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 = OgnAddPrimRelationshipDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnAddPrimRelationshipDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnAddPrimRelationshipDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnRationalTimeSyncGateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.RationalTimeSyncGate This node triggers when all its input executions have triggered successively at the same rational time. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnRationalTimeSyncGateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.RationalTimeSyncGate Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.rationalTimeDenominator inputs.rationalTimeNumerator Outputs: outputs.execOut outputs.rationalTimeDenominator outputs.rationalTimeNumerator """ # 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:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''), ('inputs:rationalTimeDenominator', 'uint64', 0, 'Sync Denominator', 'Denominator of the synchronization time.', {}, True, 0, False, ''), ('inputs:rationalTimeNumerator', 'int64', 0, 'Sync Numerator', 'Numerator of the synchronization time.', {}, True, 0, False, ''), ('outputs:execOut', 'execution', 0, 'Execute Out', 'The output execution', {}, True, None, False, ''), ('outputs:rationalTimeDenominator', 'uint64', 0, 'Sync Denominator', 'Denominator of the synchronization time.', {}, True, None, False, ''), ('outputs:rationalTimeNumerator', 'int64', 0, 'Sync Numerator', 'Numerator of the synchronization time.', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.outputs.execOut = og.AttributeRole.EXECUTION 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) data_view.set(value) @property def rationalTimeDenominator(self): data_view = og.AttributeValueHelper(self._attributes.rationalTimeDenominator) return data_view.get() @rationalTimeDenominator.setter def rationalTimeDenominator(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rationalTimeDenominator) data_view = og.AttributeValueHelper(self._attributes.rationalTimeDenominator) data_view.set(value) @property def rationalTimeNumerator(self): data_view = og.AttributeValueHelper(self._attributes.rationalTimeNumerator) return data_view.get() @rationalTimeNumerator.setter def rationalTimeNumerator(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rationalTimeNumerator) data_view = og.AttributeValueHelper(self._attributes.rationalTimeNumerator) 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 execOut(self): data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): data_view = og.AttributeValueHelper(self._attributes.execOut) data_view.set(value) @property def rationalTimeDenominator(self): data_view = og.AttributeValueHelper(self._attributes.rationalTimeDenominator) return data_view.get() @rationalTimeDenominator.setter def rationalTimeDenominator(self, value): data_view = og.AttributeValueHelper(self._attributes.rationalTimeDenominator) data_view.set(value) @property def rationalTimeNumerator(self): data_view = og.AttributeValueHelper(self._attributes.rationalTimeNumerator) return data_view.get() @rationalTimeNumerator.setter def rationalTimeNumerator(self, value): data_view = og.AttributeValueHelper(self._attributes.rationalTimeNumerator) 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 = OgnRationalTimeSyncGateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnRationalTimeSyncGateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnRationalTimeSyncGateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnTickDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnTick Executes an output execution pulse at a regular multiple of the refresh rate """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnTickDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnTick Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.framePeriod inputs.onlyPlayback Outputs: outputs.absoluteSimTime outputs.deltaSeconds outputs.frame outputs.isPlaying outputs.tick outputs.time outputs.timeSinceStart State: state.accumulatedSeconds state.frameCount """ # 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:framePeriod', 'uint', 0, 'Update Period (Ticks)', 'The number of updates between each output pulse.\nThe default 0 means every update, 1 means every other update.\nThis can be used to rate-limit updates.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:absoluteSimTime', 'double', 0, 'Absolute Simulation Time (Seconds)', 'The accumulated total of elapsed times between rendered frames', {}, True, None, False, ''), ('outputs:deltaSeconds', 'double', 0, 'Delta (Seconds)', 'The number of seconds elapsed since the last output pulse', {}, True, None, False, ''), ('outputs:frame', 'double', 0, 'Animation Time (Frames)', 'The global animation time in frames, equivalent to (time * fps), during playback', {}, True, None, False, ''), ('outputs:isPlaying', 'bool', 0, 'Is Playing', 'True during global animation timeline playback', {}, True, None, False, ''), ('outputs:tick', 'execution', 0, 'Tick', 'The execution output', {}, True, None, False, ''), ('outputs:time', 'double', 0, 'Animation Time (Seconds)', 'The global animation time in seconds during playback', {}, True, None, False, ''), ('outputs:timeSinceStart', 'double', 0, 'Time Since Start (Seconds)', 'Elapsed time since the App started', {}, True, None, False, ''), ('state:accumulatedSeconds', 'double', 0, None, 'Accumulated time since the last output pulse', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('state:frameCount', 'uint', 0, None, 'Accumulated frames since the last output pulse', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, 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.tick = og.AttributeRole.EXECUTION 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 framePeriod(self): data_view = og.AttributeValueHelper(self._attributes.framePeriod) return data_view.get() @framePeriod.setter def framePeriod(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.framePeriod) data_view = og.AttributeValueHelper(self._attributes.framePeriod) data_view.set(value) @property def onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) 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 absoluteSimTime(self): data_view = og.AttributeValueHelper(self._attributes.absoluteSimTime) return data_view.get() @absoluteSimTime.setter def absoluteSimTime(self, value): data_view = og.AttributeValueHelper(self._attributes.absoluteSimTime) data_view.set(value) @property def deltaSeconds(self): data_view = og.AttributeValueHelper(self._attributes.deltaSeconds) return data_view.get() @deltaSeconds.setter def deltaSeconds(self, value): data_view = og.AttributeValueHelper(self._attributes.deltaSeconds) data_view.set(value) @property def frame(self): data_view = og.AttributeValueHelper(self._attributes.frame) return data_view.get() @frame.setter def frame(self, value): data_view = og.AttributeValueHelper(self._attributes.frame) data_view.set(value) @property def isPlaying(self): data_view = og.AttributeValueHelper(self._attributes.isPlaying) return data_view.get() @isPlaying.setter def isPlaying(self, value): data_view = og.AttributeValueHelper(self._attributes.isPlaying) data_view.set(value) @property def tick(self): data_view = og.AttributeValueHelper(self._attributes.tick) return data_view.get() @tick.setter def tick(self, value): data_view = og.AttributeValueHelper(self._attributes.tick) data_view.set(value) @property def time(self): data_view = og.AttributeValueHelper(self._attributes.time) return data_view.get() @time.setter def time(self, value): data_view = og.AttributeValueHelper(self._attributes.time) data_view.set(value) @property def timeSinceStart(self): data_view = og.AttributeValueHelper(self._attributes.timeSinceStart) return data_view.get() @timeSinceStart.setter def timeSinceStart(self, value): data_view = og.AttributeValueHelper(self._attributes.timeSinceStart) 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) @property def accumulatedSeconds(self): data_view = og.AttributeValueHelper(self._attributes.accumulatedSeconds) return data_view.get() @accumulatedSeconds.setter def accumulatedSeconds(self, value): data_view = og.AttributeValueHelper(self._attributes.accumulatedSeconds) data_view.set(value) @property def frameCount(self): data_view = og.AttributeValueHelper(self._attributes.frameCount) return data_view.get() @frameCount.setter def frameCount(self, value): data_view = og.AttributeValueHelper(self._attributes.frameCount) 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 = OgnOnTickDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnTickDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnTickDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnForLoopDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.ForLoop Executes the a loop body once for each value within a range. When step is positive, the values in the range are determined by the formula: r[i] = start + step*i, i >= 0 & r[i] < stop. When step is negative the constraint is instead r[i] > stop. A step of zero is an error. The break input can be used to break out of the loop before the last index. The finished output is executed after all iterations are complete, or when the loop was broken """ 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 OgnForLoopDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.ForLoop Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.breakLoop inputs.execIn inputs.start inputs.step inputs.stop Outputs: outputs.finished outputs.index outputs.loopBody outputs.value State: state.i """ # 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:breakLoop', 'execution', 0, 'Break', 'Breaks out of the loop when the loop body traversal reaches it', {}, True, None, False, ''), ('inputs:execIn', 'execution', 0, 'In', 'Input execution', {}, True, None, False, ''), ('inputs:start', 'int', 0, 'Start', 'The first value in the range', {}, True, 0, False, ''), ('inputs:step', 'int', 0, 'Step', 'The step size of the range', {ogn.MetadataKeys.DEFAULT: '1'}, True, 1, False, ''), ('inputs:stop', 'int', 0, 'Stop', 'The limiting value of the range', {}, True, 0, False, ''), ('outputs:finished', 'execution', 0, None, 'Executed when the loop is finished', {}, True, None, False, ''), ('outputs:index', 'int', 0, None, 'The current or last index within the range', {}, True, None, False, ''), ('outputs:loopBody', 'execution', 0, None, 'Executed for each index in the range', {}, True, None, False, ''), ('outputs:value', 'int', 0, None, 'The current or last value of the range', {}, True, None, False, ''), ('state:i', 'int', 0, None, 'The next position in the range or -1 when loop is not active', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, 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.breakLoop = og.AttributeRole.EXECUTION role_data.inputs.execIn = og.AttributeRole.EXECUTION role_data.outputs.finished = og.AttributeRole.EXECUTION role_data.outputs.loopBody = og.AttributeRole.EXECUTION 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 breakLoop(self): data_view = og.AttributeValueHelper(self._attributes.breakLoop) return data_view.get() @breakLoop.setter def breakLoop(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.breakLoop) data_view = og.AttributeValueHelper(self._attributes.breakLoop) data_view.set(value) @property def execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) data_view.set(value) @property def start(self): data_view = og.AttributeValueHelper(self._attributes.start) return data_view.get() @start.setter def start(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.start) data_view = og.AttributeValueHelper(self._attributes.start) data_view.set(value) @property def step(self): data_view = og.AttributeValueHelper(self._attributes.step) return data_view.get() @step.setter def step(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.step) data_view = og.AttributeValueHelper(self._attributes.step) data_view.set(value) @property def stop(self): data_view = og.AttributeValueHelper(self._attributes.stop) return data_view.get() @stop.setter def stop(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.stop) data_view = og.AttributeValueHelper(self._attributes.stop) 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 finished(self): data_view = og.AttributeValueHelper(self._attributes.finished) return data_view.get() @finished.setter def finished(self, value): data_view = og.AttributeValueHelper(self._attributes.finished) data_view.set(value) @property def index(self): data_view = og.AttributeValueHelper(self._attributes.index) return data_view.get() @index.setter def index(self, value): data_view = og.AttributeValueHelper(self._attributes.index) data_view.set(value) @property def loopBody(self): data_view = og.AttributeValueHelper(self._attributes.loopBody) return data_view.get() @loopBody.setter def loopBody(self, value): data_view = og.AttributeValueHelper(self._attributes.loopBody) data_view.set(value) @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) @property def i(self): data_view = og.AttributeValueHelper(self._attributes.i) return data_view.get() @i.setter def i(self, value): data_view = og.AttributeValueHelper(self._attributes.i) 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 = OgnForLoopDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnForLoopDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnForLoopDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnClosingDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.OnClosing Executes an output execution when the USD stage is about to be closed. Note that only simple necessary actions should be taken during closing since the application is in the process of cleaning up the existing state and some systems may be in a transitional state """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnClosingDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.OnClosing Class Members: node: Node being evaluated Attribute Value Properties: Outputs: outputs.execOut """ # 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([ ('outputs:execOut', 'execution', 0, 'Closing', 'The execution output', {}, 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.execOut = og.AttributeRole.EXECUTION 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 = [] 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 execOut(self): data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): data_view = og.AttributeValueHelper(self._attributes.execOut) 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 = OgnOnClosingDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnClosingDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnClosingDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnMultigateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.action.Multigate This node cycles through each of its N outputs. On each input, one output will be activated. Outputs will be activated in sequence, eg: 0->1->2->3->4->0->1... """ 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 OgnMultigateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.action.Multigate Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn Outputs: outputs.output0 """ # 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:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''), ('outputs:output0', 'execution', 0, None, 'Output execution', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.outputs.output0 = og.AttributeRole.EXECUTION 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 execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) 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 output0(self): data_view = og.AttributeValueHelper(self._attributes.output0) return data_view.get() @output0.setter def output0(self, value): data_view = og.AttributeValueHelper(self._attributes.output0) 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 = OgnMultigateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnMultigateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnMultigateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnLoaded.cpp
// Copyright (c) 2022-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 <OgnOnLoadedDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnOnLoaded { bool m_triggered {false}; public: static bool compute(OgnOnLoadedDatabase& db) { auto& state = db.internalState<OgnOnLoaded>(); if (!state.m_triggered) { state.m_triggered = true; // This node does nothing but trigger downstream when first computed. When the execution evaluator receives // the first tick event it will ensure that OnLoaded nodes are run before any OnTick or other event node. // It's not possible to encapsulate the OnLoaded logic of the evaluator in this node due to the // special requirement that it run before others that are ready. auto iActionGraph = getInterface(); iActionGraph->setExecutionEnabled(outputs::execOut.token(), db.getInstanceIndex()); } return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSendCustomEvent.ogn
{ "SendCustomEvent": { "description": [ "Sends a custom event, which will asynchronously trigger any OnCustomEvent nodes which are listening for", "the same eventName"], "version": 1, "categories": ["graph:action", "event"], "uiName": "Send Custom Event", "language": "Python", "state": { }, "inputs": { "execIn": { "type": "execution", "description": "Input Execution" }, "eventName": { "type": "token", "description": "The name of the custom event", "uiName": "Event Name" }, "path": { "type": "token", "description": "The path associated with the event", "uiName": "Path" }, "bundle": { "type": "bundle", "description": "Bundle to be sent with the event", "uiName": "Bundle", "optional": "true" } }, "outputs": { "execOut": { "type": "execution", "description": "Output Execution" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSetPrimActive.ogn
{ "SetPrimActive": { "version": 1, "description": [ "Set a Prim active or not in the stage." ], "uiName": "Set Prim Active", "scheduling": [ "usd-write" ], "categories": [ "graph:action", "sceneGraph" ], "inputs": { "execIn": { "type": "execution", "description": "Input execution" }, "prim": { "uiName": "Prim Path", "type": "path", "description": "The prim to be (de)activated", "deprecated": "Use the primTarget input instead" }, "primTarget": { "uiName": "Prim", "type": "target", "description": "The prim to be (de)activated" }, "active": { "type": "bool", "description": "Wheter to set the prim active or not" } }, "outputs": { "execOut": { "type": "execution", "description": "The output execution", "uiName": "Execute Out" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnForLoop.ogn
{ "ForLoop": { "version": 1, "description": [ "Executes the a loop body once for each value within a range.", "When step is positive, the values in the range are determined by the formula:\n", "r[i] = start + step*i, i >= 0 & r[i] < stop.\nWhen step is negative the constraint ", "is instead r[i] > stop. A step of zero is an error.\n", "The break input can be used to break out of the loop before the last index. ", "The finished output is executed after all iterations are complete, or when the loop was broken" ], "categories": ["graph:action","flowControl"], "scheduling": ["threadsafe"], "exclude": ["tests"], "uiName": "For Loop", "tags": ["range"], "icon": { "path": "LoopNodeIcon.svg" }, "state": { "i": { "type": "int", "description": "The next position in the range or -1 when loop is not active", "default": -1 } }, "inputs": { "start": { "type": "int", "description": "The first value in the range", "uiName": "Start" }, "stop": { "type": "int", "description": "The limiting value of the range", "uiName": "Stop" }, "step": { "type": "int", "description": "The step size of the range", "uiName": "Step", "default": 1 }, "execIn": { "type": "execution", "description": "Input execution", "uiName": "In" }, "breakLoop": { "type": "execution", "description": "Breaks out of the loop when the loop body traversal reaches it", "uiName": "Break" } }, "outputs": { "loopBody": { "type": "execution", "description": "Executed for each index in the range" }, "value": { "type": "int", "description": "The current or last value of the range" }, "index": { "type": "int", "description": "The current or last index within the range" }, "finished": { "type": "execution", "description": "Executed when the loop is finished" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnKeyboardInput.cpp
// Copyright (c) 2021-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 "ActionNodeCommon.h" #include <carb/input/IInput.h> #include <carb/input/InputTypes.h> #include <omni/graph/action/IActionGraph.h> #include <omni/kit/IAppWindow.h> #include <OgnOnKeyboardInputDatabase.h> using namespace carb::input; namespace omni { namespace graph { namespace action { constexpr size_t s_numNames = 106; static constexpr std::array<const char*, s_numNames> s_keyNames = { "Unknown", "Space", "Apostrophe", "Comma", "Minus", "Period", "Slash", "Key0", "Key1", "Key2", "Key3", "Key4", "Key5", "Key6", "Key7", "Key8", "Key9", "Semicolon", "Equal", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "LeftBracket", "Backslash", "RightBracket", "GraveAccent", "Escape", "Tab", "Enter", "Backspace", "Insert", "Del", "Right", "Left", "Down", "Up", "PageUp", "PageDown", "Home", "End", "CapsLock", "ScrollLock", "NumLock", "PrintScreen", "Pause", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "Numpad0", "Numpad1", "Numpad2", "Numpad3", "Numpad4", "Numpad5", "Numpad6", "Numpad7", "Numpad8", "Numpad9", "NumpadDel", "NumpadDivide", "NumpadMultiply", "NumpadSubtract", "NumpadAdd", "NumpadEnter", "NumpadEqual", "LeftShift", "LeftControl", "LeftAlt", "LeftSuper", "RightShift", "RightControl", "RightAlt", "RightSuper", "Menu" }; static std::array<NameToken, s_numNames> s_keyTokens; static std::array<NameToken, s_numNames> s_keyTokensLowercase; class OgnOnKeyboardInput { public: SubscriptionId m_keyEventId; // The subscription to the global input event source (one per authoring node) KeyboardEvent m_keyEvent; // The last key event received exec::unstable::Stamp m_keySetStamp; // The stamp set by the authoring node when the even occurs exec::unstable::SyncStamp m_keySetSyncStamp; // The stamp used by each instance static bool onKeyboardEvent(const InputEvent& e, void* userData) { if (e.deviceType != DeviceType::eKeyboard) { return false; } if (e.keyboardEvent.type != KeyboardEventType::eKeyPress && e.keyboardEvent.type != KeyboardEventType::eKeyRelease) return false; NodeHandle nodeHandle = reinterpret_cast<NodeHandle>(userData); auto iNode = carb::getCachedInterface<omni::graph::core::INode>(); NodeObj nodeObj = iNode->getNodeFromHandle(nodeHandle); // Copy the event data and request the next compute() auto& authoringState = OgnOnKeyboardInputDatabase::sInternalState<OgnOnKeyboardInput>(nodeObj, kAuthoringGraphIndex); authoringState.m_keyEvent = e.keyboardEvent; authoringState.m_keySetStamp.next(); iNode->requestCompute(nodeObj); return true; } static void initialize(const GraphContextObj& context, const NodeObj& nodeObj) { // First time look up all the tokens and their lowercase equivalents [[maybe_unused]] static bool callOnce = ([&context] { size_t i = 0; for (const char* name : s_keyNames) { s_keyTokens[i] = context.iToken->getHandle(name); std::string lower(strlen(name), '\0'); std::transform(name, name + strlen(name), lower.begin(), [](unsigned char c) {return ::tolower(c);}); s_keyTokensLowercase[i] = context.iToken->getHandle(lower.c_str()); ++i; } } (), true); omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow(); if (!appWindow) { return; } Keyboard* keyboard = appWindow->getKeyboard(); if (!keyboard) { CARB_LOG_ERROR_ONCE("No Keyboard!"); return; } IInput* input = carb::getCachedInterface<IInput>(); if (!input) { CARB_LOG_ERROR_ONCE("No Input!"); return; } auto& authoringState = OgnOnKeyboardInputDatabase::sInternalState<OgnOnKeyboardInput>(nodeObj, kAuthoringGraphIndex); authoringState.m_keyEventId = input->subscribeToInputEvents((carb::input::InputDevice*)keyboard, kEventTypeAll, onKeyboardEvent, reinterpret_cast<void*>(nodeObj.nodeHandle), kSubscriptionOrderDefault); } static void release(const NodeObj& nodeObj) { auto const& authoringState = OgnOnKeyboardInputDatabase::sInternalState<OgnOnKeyboardInput>(nodeObj, kAuthoringGraphIndex); IInput* input = carb::getCachedInterface<IInput>(); if (!input) return; if (authoringState.m_keyEventId > 0) input->unsubscribeToInputEvents(authoringState.m_keyEventId); } static bool compute(OgnOnKeyboardInputDatabase& db) { if (checkNodeDisabledForOnlyPlay(db)) return true; static const NameToken emptyToken = db.stringToToken(""); auto iActionGraph = getInterface(); auto const& authoringState = OgnOnKeyboardInputDatabase::sInternalState<OgnOnKeyboardInput>(db.abi_node(), kAuthoringGraphIndex); auto& localState = db.internalState<OgnOnKeyboardInput>(); if (localState.m_keySetSyncStamp.makeSync(authoringState.m_keySetStamp)) { const NameToken& keyIn = db.inputs.keyIn(); auto& keyEvent = authoringState.m_keyEvent; size_t keyIndex = static_cast<size_t>(keyEvent.key); if (keyIndex >= s_keyTokens.size()) { db.logError("Invalid Key %zu detected", keyIndex); } else { if (keyIn == emptyToken || keyIn == s_keyTokens[keyIndex] || keyIn == s_keyTokensLowercase[keyIndex]) { // If the keyIn is one of the modifiers, the modifier requirement is always satisfied. // For example: LeftShift. We still want to fire pressed execution when LeftShift is pressed // although there is no modifier requirement And for case Shift-LeftShift, by pressing LeftShift, // the modifier requirement has been satisfied naturally bool shiftSatisfied = (keyEvent.key == KeyboardInput::eLeftShift || keyEvent.key == KeyboardInput::eRightShift) ? true : db.inputs.shiftIn() == static_cast<const bool>(keyEvent.modifiers & kKeyboardModifierFlagShift); bool ctrlSatisfied = (keyEvent.key == KeyboardInput::eLeftControl || keyEvent.key == KeyboardInput::eRightControl) ? true : db.inputs.ctrlIn() == static_cast<const bool>(keyEvent.modifiers & kKeyboardModifierFlagControl); bool altSatisfied = (keyEvent.key == KeyboardInput::eLeftAlt || keyEvent.key == KeyboardInput::eRightAlt) ? true : db.inputs.altIn() == static_cast<const bool>(keyEvent.modifiers & kKeyboardModifierFlagAlt); bool keyModifierConditionSatisfied = shiftSatisfied && ctrlSatisfied && altSatisfied; // Pressed case: all special keys pressed with keyIn last pressed if (keyEvent.type == KeyboardEventType::eKeyPress && keyModifierConditionSatisfied) { iActionGraph->setExecutionEnabled(outputs::pressed.token(), db.getInstanceIndex()); db.outputs.isPressed() = true; } // Release case 1: release keyIn while all other required special keys held else if (keyEvent.type == KeyboardEventType::eKeyRelease && keyModifierConditionSatisfied && db.outputs.isPressed()) { iActionGraph->setExecutionEnabled(outputs::released.token(), db.getInstanceIndex()); db.outputs.isPressed() = false; } db.outputs.keyOut() = keyIn; } // Release case 2: release any one of required special keys while keyIn and other special keys held and // the press key requirements have been met Check isPressed to make sure we only fire released event // once for each pressed event else if (keyEvent.type == KeyboardEventType::eKeyRelease && db.outputs.isPressed()) { if ((db.inputs.ctrlIn() && (keyEvent.key == KeyboardInput::eLeftControl || // check if ctrl required // and ctrl released keyEvent.key == KeyboardInput::eRightControl)) || (db.inputs.shiftIn() && (keyEvent.key == KeyboardInput::eLeftShift || // check if shift required // and shift released keyEvent.key == KeyboardInput::eRightShift)) || (db.inputs.altIn() && (keyEvent.key == KeyboardInput::eLeftAlt || // check if alt required and // alt released keyEvent.key == KeyboardInput::eRightAlt))) { iActionGraph->setExecutionEnabled(outputs::released.token(), db.getInstanceIndex()); db.outputs.isPressed() = false; } } } } return true; } // ---------------------------------------------------------------------------- static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion) { if (oldVersion < newVersion) { INode const* iNode = nodeObj.iNode; if (oldVersion < 2) { // We added allowedTokens to keyIn, so uppercase the given string so that it matches // the upper case allowedToken list auto attrObj = iNode->getAttribute(nodeObj, "inputs:keyIn"); auto attrDataHandle = attrObj.iAttribute->getAttributeDataHandle(attrObj, kAccordingToContextIndex); RawPtr dataPtr{ nullptr }; size_t dataSize{ 0 }; context.iAttributeData->getDataReferenceW(attrDataHandle, context, dataPtr, dataSize); if (dataPtr) { NameToken* tokenData = (NameToken*)dataPtr; NameToken oldKeyIn = *tokenData; char const* oldKeyStr = context.iToken->getText(oldKeyIn); std::string newKeyStr = oldKeyStr; if (newKeyStr.size() >= 1) { if (std::find(begin(s_keyNames), end(s_keyNames), oldKeyStr) == end(s_keyNames)) { newKeyStr[0] = ::toupper(oldKeyStr[0]); if (std::find(begin(s_keyNames), end(s_keyNames), newKeyStr) != end(s_keyNames)) { CARB_LOG_INFO("Updating %s.inputs:keyIn from \"%s\" to \"%s\" to match allowedTokens", iNode->getPrimPath(nodeObj), oldKeyStr, newKeyStr.data()); NameToken const newKeyIn = context.iToken->getHandle(newKeyStr.data()); *tokenData = newKeyIn; } // If we didn't find the upper-cased key we can't do much more. We will rely on runtime // errors to inform the user. } } } } if (oldVersion < 3) { // We added inputs:onlyPlayback default true - to maintain previous behavior we should set this to false const bool val{ false }; nodeObj.iNode->createAttribute(nodeObj, "inputs:onlyPlayback", Type(BaseDataType::eBool), &val, nullptr, kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr); } } return true; } }; REGISTER_OGN_NODE() } // namespace action } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnRationalTimeSyncGate.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 <OgnRationalTimeSyncGateDatabase.h> #include <omni/fabric/RationalTime.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnRationalTimeSyncGate { public: // The current number of accumulated executions. uint32_t m_numAccumulatedExecIn{ 0 }; // The current synchronization value. fabric::RationalTime m_syncValue{ fabric::kInvalidTime }; static bool compute(OgnRationalTimeSyncGateDatabase& db) { auto nodeObj = db.abi_node(); const AttributeObj attr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::execIn.m_token); const auto accumulationThreshold = static_cast<uint32_t>(attr.iAttribute->getUpstreamConnectionCount(attr)); OgnRationalTimeSyncGate& state = db.internalState<OgnRationalTimeSyncGate>(); const fabric::RationalTime syncValue{ db.inputs.rationalTimeNumerator(), db.inputs.rationalTimeDenominator()}; const bool reset = syncValue != state.m_syncValue; state.m_numAccumulatedExecIn = reset ? 1 : std::min(state.m_numAccumulatedExecIn + 1, accumulationThreshold); state.m_syncValue = syncValue; db.outputs.rationalTimeNumerator() = syncValue.numerator; db.outputs.rationalTimeDenominator() = syncValue.denominator; if (state.m_numAccumulatedExecIn >= accumulationThreshold) { auto iActionGraph = getInterface(); iActionGraph->setExecutionEnabled(outputs::execOut.token(), db.getInstanceIndex()); } return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnClosing.ogn
{ "OnClosing": { "version": 1, "description": [ "Executes an output execution when the USD stage is about to be closed.\n", "Note that only simple necessary actions should be taken during closing since the", "application is in the process of cleaning up the existing state and some", "systems may be in a transitional state"], "uiName": "On Closing", "categories": ["graph:action", "event"], "scheduling": ["compute-on-request", "threadsafe"], "inputs": { }, "outputs": { "execOut": { "type": "execution", "description": "The execution output", "uiName": "Closing" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSequence.ogn
{ "Sequence": { "version": 1, "description": "Outputs an execution pulse along output A and B in sequence", "uiName": "Sequence", "metadata": {"hidden": "true"}, "categories": ["graph:action", "flowControl"], "scheduling": ["threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "Input execution" } }, "outputs": { "a": { "type": "execution", "description": "The first output path", "uiName": "A" }, "b": { "type": "execution", "description": "The second outputs path", "uiName": "B" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnBranch.cpp
// Copyright (c) 2021-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 <OgnBranchDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnBranch { public: static bool compute(OgnBranchDatabase& db) { auto iActionGraph = getInterface(); bool condition = db.inputs.condition(); if (condition) iActionGraph->setExecutionEnabled(outputs::execTrue.token(), db.getInstanceIndex()); else iActionGraph->setExecutionEnabled(outputs::execFalse.token(), db.getInstanceIndex()); return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnVariableChange.ogn
{ "OnVariableChange": { "version": 1, "description": "Executes an output execution pulse when the chosen variable changes", "uiName": "On Variable Change", "categories": ["graph:action", "event"], "scheduling": ["threadsafe"], "inputs": { "variableName": { "type": "token", "description": "The name of the graph variable to use.", "uiName": "Variable Name", "metadata": { "literalOnly": "1" } }, "onlyPlayback": { "type": "bool", "description": "When true, the node is only computed while Stage is being played.", "uiName": "Only Simulate On Play", "default": true, "metadata": { "literalOnly": "1" } } }, "outputs": { "changed": { "type": "execution", "description": "The execution output", "uiName": "Changed" } }, "state": { } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnGate.ogn
{ "Gate": { "version": 1, "description": ["This node controls a flow of execution based on the state of its gate.", "The gate can be opened or closed by execution pulses sent to the gate controls" ], "uiName": "Gate", "categories": ["graph:action","flowControl"], "scheduling": ["threadsafe"], "inputs": { "enter": { "type": "execution", "description": "Incoming execution flow controlled by the gate", "uiName": "Enter" }, "toggle": { "type": "execution", "description": "The gate is opened or closed", "uiName": "Toggle" }, "startClosed": { "type": "bool", "description": "If true the gate will start in a closed state", "uiName": "Start Closed" } }, "outputs": { "exit": { "type": "execution", "description": "The enter pulses will be passed to this output if the gate is open", "uiName": "Exit" } }, "tests" : [ { "inputs:enter": 1, "outputs:exit": 1} ] } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnForLoop.cpp
// Copyright (c) 2021-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 <OgnForLoopDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnForLoop { public: static bool compute(OgnForLoopDatabase& db) { auto iActionGraph = getInterface(); bool const isBreakLoop = iActionGraph->getExecutionEnabled(inputs::breakLoop.token(), db.getInstanceIndex()); auto finishLoop = [&db, &iActionGraph]() { db.state.i() = -1; iActionGraph->setExecutionEnabled(outputs::finished.token(), db.getInstanceIndex()); }; if (isBreakLoop) { finishLoop(); return true; } int i = db.state.i(); // no existing loop state, initialize it to zero if (i == -1) i = 0; int step = db.inputs.step(); if (step == 0) { db.logError("Step can not be zero"); return false; } int start = db.inputs.start(); int stop = db.inputs.stop(); int rangeVal = start + step * i; if (step > 0) { if (rangeVal >= stop) { finishLoop(); return true; } } else { if (rangeVal <= stop) { finishLoop(); return true; } } // execute the loop body db.outputs.value() = rangeVal; db.outputs.index() = i; db.state.i() = i + 1; iActionGraph->setExecutionEnabledAndPushed(outputs::loopBody.token(), db.getInstanceIndex()); return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnLoaded.ogn
{ "OnLoaded": { "description": [ "Triggers the output on the first update of the graph after it is created or loaded.", "This will run before any other event node, and will only run once after this", "node is created." ], "version": 1, "uiName": "On Loaded", "categories": ["graph:action", "event"], "scheduling": ["compute-on-request", "threadsafe"], "inputs": { }, "outputs": { "execOut": { "type": "execution", "description": "Executes after graph creation or loading" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnMultigate.cpp
// Copyright (c) 2021-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 <OgnMultigateDatabase.h> #include <carb/extras/StringUtils.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnMultigate { public: // The output that will be activated on the next compute. uint32_t m_nextLevel{ 0 }; static bool setExecutionEnabled(NodeObj nodeObj, const char* attribName, InstanceIndex instIndex) { auto iNode = nodeObj.iNode; if (!iNode->getAttributeExists(nodeObj, attribName)) return false; AttributeObj attrObj = iNode->getAttribute(nodeObj, attribName); auto iActionGraph = getInterface(); iActionGraph->setExecutionEnabled(attrObj.iAttribute->getNameToken(attrObj), instIndex); return true; } static bool compute(OgnMultigateDatabase& db) { OgnMultigate& state = db.internalState<OgnMultigate>(); NodeObj nodeObj = db.abi_node(); auto iNode = nodeObj.iNode; bool hasSetExecution = false; // Set the execution values // lots of room to append digits to the output name std::array<char, 32> outputName; auto formatAttrName = [&outputName](uint32_t n) { carb::extras::formatString(outputName.data(), outputName.size(), "outputs:output%d", n); }; for (uint32_t i = 0;; i++) { formatAttrName(i); if (i == state.m_nextLevel && setExecutionEnabled(nodeObj, outputName.data(), db.getInstanceIndex())) { hasSetExecution = true; } else if (i != state.m_nextLevel && nodeObj.iNode->getAttributeExists(nodeObj, outputName.data())) { // keep looping while we are matching attributes (shouldn't be any holes in the sequence) } else { // Failure if (!hasSetExecution) { // We haven't found the desired output, so we'll reset to 0 formatAttrName(0); setExecutionEnabled(nodeObj, outputName.data(), db.getInstanceIndex()); state.m_nextLevel = 0; } break; } } state.m_nextLevel += 1; return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSequence.cpp
// Copyright (c) 2021-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 <OgnSequenceDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnSequence { public: // Which branch we should take next int m_nextOutput {0}; static bool compute(OgnSequenceDatabase& db) { auto iActionGraph = getInterface(); OgnSequence& state = db.internalState<OgnSequence>(); if (state.m_nextOutput == 0) { iActionGraph->setExecutionEnabledAndPushed(outputs::a.token(), db.getInstanceIndex()); } else { iActionGraph->setExecutionEnabled(outputs::b.token(), db.getInstanceIndex()); } state.m_nextOutput = (state.m_nextOutput + 1) % 2; return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnGamepadInput.ogn
{ "OnGamepadInput": { "description": ["Event node which fires when a gamepad event occurs. This node only capture events on buttons, ", "excluding triggers and sticks"], "version": 1, "uiName": "On Gamepad Input", "categories": ["graph:action", "input:gamepad"], "scheduling": ["compute-on-request"], "exclude": ["tests"], "inputs": { "gamepadId": { "type": "uint", "description": [ "Gamepad id number starting from 0. Each gamepad will be registered automatically with an unique ID monotonically increasing in the order they are connected.", "If gamepad is disconnected, the ID assigned to the remaining gamepad will be adjusted accordingly so the IDs are always continues and start from 0", "Change this value to a non-existing ID will result an error prompt in the console and the node will not listen to any gamepad input." ], "uiName": "Gamepad ID", "default": 0, "metadata": { "literalOnly": "1" } }, "gamepadElementIn": { "type": "token", "description": "The gamepad button to trigger the downstream execution.", "uiName": "Gamepad Element In", "default": "Face Button Bottom", "metadata": { "displayGroup": "parameters", "literalOnly": "1", "allowedTokens": { "FaceButtonBottom": "Face Button Bottom", "FaceButtonRight": "Face Button Right", "FaceButtonLeft": "Face Button Left", "FaceButtonTop": "Face Button Top", "LeftShoulder": "Left Shoulder", "RightShoulder": "Right Shoulder", "SpecialLeft": "Special Left", "SpecialRight": "Special Right", "LeftStickButton": "Left Stick Button", "RightStickButton": "Right Stick Button", "DpadUp": "D-Pad Up", "DpadRight": "D-Pad Right", "DpadDown": "D-Pad Down", "DpadLeft": "D-Pad Left" } } }, "onlyPlayback": { "type": "bool", "description": "When true, the node is only computed while Stage is being played.", "uiName": "Only Simulate On Play", "default": true, "metadata": { "literalOnly": "1" } } }, "outputs": { "pressed": { "type": "execution", "description": "Executes when gamepad element was pressed", "uiName": "Pressed" }, "released": { "type": "execution", "description": "Executes when gamepad element was released", "uiName": "Released" }, "isPressed": { "type": "bool", "description": ["True if the gamepad button was pressed, False if it was released"] } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnce.ogn
{ "Once": { "description": [ "Controls flow of execution by passing input through differently on the first time" ], "version": 1, "uiName": "Once", "categories": ["graph:action", "flowControl"], "scheduling": ["threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "Input execution" }, "reset": { "type": "execution", "description": "Resets the gate state to closed. The next execIn impulse will pass the gate." } }, "outputs": { "once": { "type": "execution", "description": "Executes the first time (or the first time after a 'reset'." }, "after": { "type": "execution", "description": "Executes after the first time" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnMouseInput.ogn
{ "OnMouseInput": { "description": ["Event node which fires when a mouse event occurs.\n", "You can choose which mouse element this node reacts to.", "When mouse element is chosen to be a button, the only meaningful outputs are: outputs:pressed, outputs:released and outputs:isPressed.", "When scroll or move events are chosen, the only meaningful outputs are: outputs:valueChanged and outputs:value.", "You can choose to output normalized or pixel coordinates of the mouse.\n", "Pixel coordinates are the absolute position of the mouse cursor in pixel unit.", "The original point is the upper left corner.", "The minimum value is 0, and the maximum value depends on the size of the window.\n", "Normalized coordinates are the relative position of the mouse cursor to the window.", "The value is always between 0 and 1."], "version": 1, "uiName": "On Mouse Input", "categories": ["graph:action", "input:mouse"], "scheduling": ["compute-on-request", "threadsafe"], "inputs": { "mouseElement": { "type": "token", "description": "The event to trigger the downstream execution ", "uiName": "Mouse Element", "default": "Left Button", "metadata": { "displayGroup": "parameters", "literalOnly": "1", "allowedTokens": { "LeftButton": "Left Button", "MiddleButton": "Middle Button", "RightButton": "Right Button", "NormalizedMove": "Normalized Move", "PixelMove": "Pixel Move", "Scroll": "Scroll" } } }, "onlyPlayback": { "type": "bool", "description": "When true, the node is only computed while Stage is being played.", "uiName": "Only Simulate On Play", "default": true, "metadata": { "literalOnly": "1" } } }, "outputs": { "pressed": { "type": "execution", "description": "Executes when mouse button was pressed. Will not execute on move or scroll events", "uiName": "Pressed" }, "released": { "type": "execution", "description": "Executes when mouse button was released. Will not execute on move or scroll events", "uiName": "Released" }, "valueChanged": { "type": "execution", "description": "Executes when user moves the cursor or scrolls the cursor. Will not execute on button events", "uiName": "Moved" }, "isPressed": { "type": "bool", "description": "True if the mouse button was pressed, False if it was released or mouse element is not related to a button" }, "value": { "type": "float[2]", "description": [ "The meaning of this output depends on Event In.", "Normalized Move: will output the normalized coordinates of mouse, each element of the vector is in the range of [0, 1]", "Pixel Move: will output the absolute coordinates of mouse, each vector is in the range of [0, pixel width/height of the window]", "Scroll: will output the change of scroll value", "Otherwise: will output [0,0]" ], "uiName": "Delta Value" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnce.cpp
// Copyright (c) 2022-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 <OgnOnceDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnOnce { bool m_open {false}; public: static bool compute(OgnOnceDatabase& db) { auto iActionGraph = getInterface(); auto& state = db.internalState<OgnOnce>(); bool isReset = iActionGraph->getExecutionEnabled(inputs::reset.token(), db.getInstanceIndex()); if (isReset) { state.m_open = false; return true; } if (!state.m_open) { state.m_open = true; iActionGraph->setExecutionEnabled(outputs::once.token(), db.getInstanceIndex()); } else { iActionGraph->setExecutionEnabled(outputs::after.token(), db.getInstanceIndex()); } return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnMessageBusEvent.ogn
{ "OnMessageBusEvent": { "description": [ "Event node which fires when the specified event is popped from the App Message Bus.", "Carb events can be sent with Python:", "msg = carb.events.type_from_string('my_event_name')", "omni.kit.app.get_app().get_message_bus_event_stream().push(msg, payload={'arg1': 42})", "The event payload data will be copied in to matching dynamic output attributes if they exist.", "In the previous example, 42 would be copied to outputs:arg1 if possible" ], "version": 1, "uiName": "On MessageBus Event", "categories": ["graph:action", "event"], "scheduling": "compute-on-request", "language": "Python", "state": { }, "inputs": { "eventName": { "type": "token", "description": "The name of the custom event", "uiName": "Event Name", "metadata": { "literalOnly": "1" } }, "onlyPlayback": { "type": "bool", "description": "When true, the node is only computed while Stage is being played.", "uiName": "Only Simulate On Play", "default": true, "metadata": { "literalOnly": "1" } } }, "outputs": { "execOut": { "type": "execution", "description": "Executes when the event is received", "uiName": "Received" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnStageEvent.py
""" This is the implementation of the OGN node defined in OgnOnStageEvent.ogn """ from contextlib import suppress import carb import omni.graph.core as og import omni.kit.app import omni.usd from omni.graph.action import get_interface from omni.graph.action.ogn.OgnOnStageEventDatabase import OgnOnStageEventDatabase # global map of the token to python enum, should match the allowedTokens event_name_to_enum = { "Assets Loaded": omni.usd.StageEventType.ASSETS_LOADED, "Assets Load Aborted": omni.usd.StageEventType.ASSETS_LOAD_ABORTED, "Closed": omni.usd.StageEventType.CLOSED, "Closing": omni.usd.StageEventType.CLOSING, "Gizmo Tracking Changed": omni.usd.StageEventType.GIZMO_TRACKING_CHANGED, "MDL Param Loaded": omni.usd.StageEventType.MDL_PARAM_LOADED, "Opened": omni.usd.StageEventType.OPENED, "Open Failed": omni.usd.StageEventType.OPEN_FAILED, "Saved": omni.usd.StageEventType.SAVED, "Save Failed": omni.usd.StageEventType.SAVE_FAILED, "Selection Changed": omni.usd.StageEventType.SELECTION_CHANGED, "Hierarchy Changed": omni.usd.StageEventType.HIERARCHY_CHANGED, "Settings Loaded": omni.usd.StageEventType.SETTINGS_LOADED, "Settings Saving": omni.usd.StageEventType.SETTINGS_SAVING, "OmniGraph Start Play": omni.usd.StageEventType.OMNIGRAPH_START_PLAY, "OmniGraph Stop Play": omni.usd.StageEventType.OMNIGRAPH_STOP_PLAY, "Simulation Start Play": omni.usd.StageEventType.SIMULATION_START_PLAY, "Simulation Stop Play": omni.usd.StageEventType.SIMULATION_STOP_PLAY, "Animation Start Play": omni.usd.StageEventType.ANIMATION_START_PLAY, "Animation Stop Play": omni.usd.StageEventType.ANIMATION_STOP_PLAY, } class OgnOnStageEventInternalState: """Convenience class for maintaining per-node state information""" def __init__(self): """Instantiate the per-node state information.""" # This subscription object controls the lifetime of our callback, we will clean it up upon release self.sub = None # Set when the callback has triggered self.is_set = False # The last payload received self.payload: carb.dictionary.Item = None # The event_name we used to subscribe self.sub_event_type = "" # The node instance handle self.node = None # Counter to determine when an animation pause was detected self._was_paused = 0 # cache of the int-valued event types self._stop_play_events = [ int(e) for e in ( omni.usd.StageEventType.OMNIGRAPH_STOP_PLAY, omni.usd.StageEventType.SIMULATION_STOP_PLAY, omni.usd.StageEventType.ANIMATION_STOP_PLAY, ) ] self._start_play_events = [ int(e) for e in ( omni.usd.StageEventType.OMNIGRAPH_START_PLAY, omni.usd.StageEventType.SIMULATION_START_PLAY, omni.usd.StageEventType.ANIMATION_START_PLAY, ) ] self._timeline = omni.timeline.get_timeline_interface() def _on_stage_event(self, e: carb.events.IEvent): """The event callback""" if e is None: return # Maintain book-keeping for pause/resume so we can ignore them if e.type in self._stop_play_events: is_stopped = self._timeline.is_stopped() if not is_stopped: # This is actually a PAUSE, because the timeline is not stopped self._was_paused += 1 return elif (e.type in self._start_play_events) and (self._was_paused > 0): # This is actually an UNPAUSE, because we previously detected a PAUSE self._was_paused -= 1 return if e.type != int(self.sub_event_type): return self.is_set = True self.payload = e.payload # Tell the evaluator we need to be computed if self.node.is_valid(): self.node.request_compute() def first_time_subscribe(self, node: og.Node, event_type: omni.usd.StageEventType) -> bool: """Checked call to set up carb subscription Args: node: The node instance event_type: The stage event type Returns: True if we subscribed, False if we are already subscribed """ if self.sub is not None and self.sub_event_type != event_type: # event name changed since we last subscribed, unsubscribe self.sub.unsubscribe() self.sub = None if self.sub is None: # Add a subscription for the given event type. This is a pop subscription, so we expect a 1-frame # lag between send and receive self.sub = ( omni.usd.get_context() .get_stage_event_stream() .create_subscription_to_pop( self._on_stage_event, name=f"omni.graph.action.__onstageevent.{node.node_id()}" ) ) self.sub_event_type = event_type self.node = node return True return False def try_pop_event(self): """Pop the payload of the last event received, or None if there is no event to pop""" if self.is_set: self.is_set = False payload = self.payload self.payload = None return payload return None # ====================================================================== class OgnOnStageEvent: @staticmethod def internal_state(): """Returns an object that will contain per-node state information""" return OgnOnStageEventInternalState() @staticmethod def release(node): # Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing # after the node has been released. with suppress(og.OmniGraphError): state = OgnOnStageEventDatabase.per_node_internal_state(node) if state.sub: state.sub.unsubscribe() state.sub = None @staticmethod def compute(db) -> bool: event_name = db.inputs.eventName if not event_name: return True state = db.internal_state # Check the validity of the input try: event_type = event_name_to_enum[event_name] except KeyError: db.log_error(f"{event_name} is not a recognized Stage Event") return False if state.first_time_subscribe(db.node, event_type): return True payload = state.try_pop_event() # Drop events if we are disabled, unless we are a 'stop' event - this is a special case because STOP only comes # after we are no longer playing. if ( db.inputs.onlyPlayback and (not db.node.get_graph().get_default_graph_context().get_is_playing()) and ( event_type not in ( omni.usd.StageEventType.OMNIGRAPH_STOP_PLAY, omni.usd.StageEventType.SIMULATION_STOP_PLAY, omni.usd.StageEventType.ANIMATION_STOP_PLAY, ) ) ): return True if payload is None: return True get_interface().set_execution_enabled("outputs:execOut") return True # ---------------------------------------------------------------------------- @staticmethod def update_node_version(context: og.GraphContext, node: og.Node, old_version: int, new_version: int): if old_version < new_version and old_version < 2: # We added inputs:onlyPlayback default true - to maintain previous behavior we should set this to false node.create_attribute( "inputs:onlyPlayback", og.Type(og.BaseDataType.BOOL), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, False, ) return True
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnKeyboardInput.ogn
{ "OnKeyboardInput": { "description": [ "Event node which fires when a keyboard event occurs.", "The event can be a combination of keys, containing key modifiers of ctrl, alt and shift, and a normal key of any key. keyIn.\n", "For key combinations, the press event requires all keys to be pressed, with the normal key pressed last.", "The release event is only triggered once when one of the chosen keys released after pressed event happens.\n", "For example: if the combination is ctrl-shift-D, the pressed event happens once right after D is pressed while both ctrl and shit are held.", "And the release event happens only once when the user releases any key of ctrl, shift and D while holding them." ], "version": 3, "uiName": "On Keyboard Input", "categories": ["graph:action", "input:keyboard"], "scheduling": "compute-on-request", "inputs": { "keyIn": { "type": "token", "description": "The key to trigger the downstream execution ", "uiName": "Key In", "default": "A", "metadata": { "displayGroup": "parameters", "literalOnly": "1", "allowedTokens": [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Apostrophe", "Backslash", "Backspace", "CapsLock", "Comma", "Del", "Down", "End", "Enter", "Equal", "Escape", "F1", "F10", "F11", "F12", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "GraveAccent", "Home", "Insert", "Key0", "Key1", "Key2", "Key3", "Key4", "Key5", "Key6", "Key7", "Key8", "Key9", "Left", "LeftAlt", "LeftBracket", "LeftControl", "LeftShift", "LeftSuper", "Menu", "Minus", "NumLock", "Numpad0", "Numpad1", "Numpad2", "Numpad3", "Numpad4", "Numpad5", "Numpad6", "Numpad7", "Numpad8", "Numpad9", "NumpadAdd", "NumpadDel", "NumpadDivide", "NumpadEnter", "NumpadEqual", "NumpadMultiply", "NumpadSubtract", "PageDown", "PageUp", "Pause", "Period", "PrintScreen", "Right", "RightAlt", "RightBracket", "RightControl", "RightShift", "RightSuper", "ScrollLock", "Semicolon", "Slash", "Space", "Tab", "Up" ] } }, "onlyPlayback": { "type": "bool", "description": "When true, the node is only computed while Stage is being played.", "uiName": "Only Simulate On Play", "default": true, "metadata": { "literalOnly": "1" } }, "shiftIn": { "type": "bool", "description": "When true, the node will check with a key modifier Shift", "uiName": "Shift", "metadata": { "literalOnly": "1" } }, "altIn": { "type": "bool", "description": "When true, the node will check with a key modifier Alt", "uiName": "Alt", "metadata": { "literalOnly": "1" } }, "ctrlIn": { "type": "bool", "description": "When true, the node will check with a key modifier Control", "uiName": "Ctrl", "metadata": { "literalOnly": "1" } } }, "outputs": { "keyOut": { "type": "token", "description": "The key that was pressed or released", "uiName": "Key Out" }, "pressed": { "type": "execution", "description": "Executes when key was pressed", "uiName": "Pressed" }, "released": { "type": "execution", "description": "Executes when key was released", "uiName": "Released" }, "isPressed": { "type": "bool", "description": "True if the key was pressed, False if it was released" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnMouseInput.cpp
// Copyright (c) 2021-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 "ActionNodeCommon.h" #include <carb/input/IInput.h> #include <carb/input/InputTypes.h> #include <omni/graph/action/IActionGraph.h> #include <omni/kit/IAppWindow.h> #include <OgnOnMouseInputDatabase.h> #include <thread> using namespace carb::input; namespace omni { namespace graph { namespace action { // Three buttons, normalized or absolute movements and scroll constexpr size_t s_numNames = 6; static std::array<NameToken, s_numNames> s_elementTokens; class OgnOnMouseInput { public: SubscriptionId m_mouseEventSubsId{ 0 }; MouseEvent m_mouseEvent; exec::unstable::Stamp m_elementSetStamp; // The stamp set by the authoring node when the event occurs exec::unstable::SyncStamp m_elementSetSyncStamp; // The stamp used by each instance static bool onMouseEvent(const InputEvent& e, void* userData) { if (e.deviceType != DeviceType::eMouse) { return false; } NodeHandle nodeHandle = reinterpret_cast<NodeHandle>(userData); auto iNode = carb::getCachedInterface<omni::graph::core::INode>(); NodeObj nodeObj = iNode->getNodeFromHandle(nodeHandle); if (!nodeObj.isValid()) return false; auto& authoringState = OgnOnMouseInputDatabase::sInternalState<OgnOnMouseInput>(nodeObj, kAuthoringGraphIndex); authoringState.m_elementSetStamp.next(); authoringState.m_mouseEvent = e.mouseEvent; iNode->requestCompute(nodeObj); return true; } static void initialize(const GraphContextObj& context, const NodeObj& nodeObj) { // First time initialization will fill up the token array [[maybe_unused]] static bool callOnce = ([] { s_elementTokens = { OgnOnMouseInputDatabase::tokens.LeftButton, OgnOnMouseInputDatabase::tokens.MiddleButton, OgnOnMouseInputDatabase::tokens.RightButton, OgnOnMouseInputDatabase::tokens.NormalizedMove, OgnOnMouseInputDatabase::tokens.PixelMove, OgnOnMouseInputDatabase::tokens.Scroll }; } (), true); omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow(); if (!appWindow) return; // TODO: We may want to change the mouse into a camera one instead of appWindow one. Mouse* mouse = appWindow->getMouse(); if (!mouse) return; IInput* input = carb::getCachedInterface<IInput>(); if (!input) return; auto& authoringState = OgnOnMouseInputDatabase::sInternalState<OgnOnMouseInput>(nodeObj, kAuthoringGraphIndex); // Someone will consume the mouse event so cannot subscribe this as the last one. // TODO: Is it good to subscribe this to the front? authoringState.m_mouseEventSubsId = input->subscribeToInputEvents((carb::input::InputDevice*)mouse, kEventTypeAll, onMouseEvent, reinterpret_cast<void*>(nodeObj.nodeHandle), kSubscriptionOrderFirst); } static void release(const NodeObj& nodeObj) { IInput* input = carb::getCachedInterface<IInput>(); if (!input) return; auto const& authoringState = OgnOnMouseInputDatabase::sInternalState<OgnOnMouseInput>(nodeObj, kAuthoringGraphIndex); if (authoringState.m_mouseEventSubsId > 0) { input->unsubscribeToInputEvents(authoringState.m_mouseEventSubsId); } } static bool compute(OgnOnMouseInputDatabase& db) { if (checkNodeDisabledForOnlyPlay(db)) return true; auto const& authoringState = OgnOnMouseInputDatabase::sInternalState<OgnOnMouseInput>(db.abi_node(), kAuthoringGraphIndex); auto& localState = db.internalState<OgnOnMouseInput>(); if (localState.m_elementSetSyncStamp.makeSync(authoringState.m_elementSetStamp)) { NameToken const& elementIn = db.inputs.mouseElement(); size_t const eventIndex = static_cast<size_t>(authoringState.m_mouseEvent.type); bool eventMatched = false; if (eventIndex < 6) // Left/Middle/Right Buttons { eventMatched = s_elementTokens[eventIndex / 2] == elementIn; } else if (eventIndex == 6) // Move { eventMatched = elementIn == db.tokens.NormalizedMove || elementIn == db.tokens.PixelMove; } else if (eventIndex == 7) // Scroll { eventMatched = elementIn == db.tokens.Scroll; } else { db.logError("Invalid Input Event %zu detected", eventIndex); } float* deltaValue = db.outputs.value().data(); carb::Float2 eventValue{ 0.0f, 0.0f }; auto iActionGraph = getInterface(); if (eventMatched) { switch (authoringState.m_mouseEvent.type) { case MouseEventType::eLeftButtonDown: case MouseEventType::eMiddleButtonDown: case MouseEventType::eRightButtonDown: db.outputs.isPressed() = true; iActionGraph->setExecutionEnabled(outputs::pressed.token(), db.getInstanceIndex()); break; case MouseEventType::eLeftButtonUp: case MouseEventType::eMiddleButtonUp: case MouseEventType::eRightButtonUp: db.outputs.isPressed() = false; iActionGraph->setExecutionEnabled(outputs::released.token(), db.getInstanceIndex()); break; case MouseEventType::eMove: db.outputs.isPressed() = false; iActionGraph->setExecutionEnabled(outputs::valueChanged.token(), db.getInstanceIndex()); if (elementIn == db.tokens.NormalizedMove) { eventValue = authoringState.m_mouseEvent.normalizedCoords; } else { eventValue = authoringState.m_mouseEvent.pixelCoords; } break; case MouseEventType::eScroll: db.outputs.isPressed() = false; iActionGraph->setExecutionEnabled(outputs::valueChanged.token(), db.getInstanceIndex()); eventValue = authoringState.m_mouseEvent.scrollDelta; break; default: break; } } deltaValue[0] = eventValue.x; deltaValue[1] = eventValue.y; } return true; } }; REGISTER_OGN_NODE() } // namespace action } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSendCustomEvent.py
""" This is the implementation of the OGN node defined in OgnSendCustomEvent.ogn """ import codecs import pickle import carb.events import omni.kit.app from omni.graph.action import get_interface def registered_event_name(event_name): """Returns the internal name used for the given custom event name""" n = "omni.graph.action." + event_name return carb.events.type_from_string(n) payload_path = "!path" # ====================================================================== class OgnSendCustomEvent: """ This node triggers when the specified message bus event is received """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" event_name = db.inputs.eventName if not event_name: return True path = db.inputs.path input_bundle = db.inputs.bundle reg_event_name = registered_event_name(event_name) message_bus = omni.kit.app.get_app().get_message_bus_event_stream() payload = {} if input_bundle.valid: # Copy the contents of the input bundle into the event dict for attr in input_bundle.attributes: tp = attr.type arg_obj = (tp, attr.value) # Since we are python at both ends, easiest to pickle the attrib values so we # can re-animate them on the other side as_str = codecs.encode(pickle.dumps(arg_obj), "base64").decode() payload[attr.name] = as_str if path: payload[payload_path] = path message_bus.push(reg_event_name, payload=payload) get_interface().set_execution_enabled("outputs:execOut") return True
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnGate.cpp
// Copyright (c) 2021-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 <OgnGateDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { enum GateState { kGateStateClosed = 0, kGateStateOpen = 1, kGateStateUninitialized = 2, }; class OgnGate { public: int m_gate{ kGateStateUninitialized }; static bool compute(OgnGateDatabase& db) { auto iActionGraph = getInterface(); auto& state = db.internalState<OgnGate>(); // On our first ever compute call, initialize the gate state. if (state.m_gate == kGateStateUninitialized) { state.m_gate = db.inputs.startClosed() ? kGateStateClosed : kGateStateOpen; } // In compute one of toggle or enter will be enabled bool isToggle = iActionGraph->getExecutionEnabled(inputs::toggle.token(), db.getInstanceIndex()); if (isToggle) { // toggle the state state.m_gate = (state.m_gate + 1) % 2; } else { if (state.m_gate == kGateStateOpen) iActionGraph->setExecutionEnabled(outputs::exit.token(), db.getInstanceIndex()); } return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnCustomEvent.py
""" This is the implementation of the OGN node defined in OgnOnCustomEvent.ogn """ import codecs import pickle from contextlib import suppress import carb.events import omni.graph.core as og import omni.kit.app from omni.graph.action import get_interface from omni.graph.action.ogn.OgnOnCustomEventDatabase import OgnOnCustomEventDatabase def registered_event_name(event_name): """Returns the internal name used for the given custom event name""" n = "omni.graph.action." + event_name return carb.events.type_from_string(n) payload_path = "!path" class OgnOnCustomEventInternalState: """Convenience class for maintaining per-node state information""" def __init__(self): """Instantiate the per-node state information.""" # This subscription object controls the lifetime of our callback, it will be # cleaned up automatically when our node is destroyed self.sub = None # Set when the callback has triggered self.is_set = False # The last payload received self.payload = None # The event_name we used to subscribe self.sub_event_name = "" # The node instance handle self.node = None def on_event(self, custom_event): """The event callback""" if custom_event is None: return self.is_set = True self.payload = custom_event.payload # Tell the evaluator we need to be computed if self.node.is_valid(): self.node.request_compute() def first_time_subscribe(self, node: og.Node, event_name: str) -> bool: """Checked call to set up carb subscription Args: node: The node instance event_name: The name of the carb event Returns: True if we subscribed, False if we are already subscribed """ if self.sub is not None and self.sub_event_name != event_name: # event name changed since we last subscribed, unsubscribe self.sub.unsubscribe() self.sub = None if self.sub is None: # Add a subscription for the given event name. This is a pop subscription, so we expect a 1-frame # lag between send and receive reg_event_name = registered_event_name(event_name) message_bus = omni.kit.app.get_app().get_message_bus_event_stream() self.sub = message_bus.create_subscription_to_pop_by_type(reg_event_name, self.on_event) self.sub_event_name = event_name self.node = node return True return False def try_pop_event(self): """Pop the payload of the last event received, or None if there is no event to pop""" if self.is_set: self.is_set = False payload = self.payload self.payload = None return payload return None # ====================================================================== class OgnOnCustomEvent: """ This node triggers when the specified message bus event is received """ @staticmethod def internal_state(): """Returns an object that will contain per-node state information""" return OgnOnCustomEventInternalState() @staticmethod def compute(db) -> bool: event_name = db.inputs.eventName if not event_name: return True state = db.internal_state if state.first_time_subscribe(db.node, event_name): return True # Drop events if we are disabled if db.inputs.onlyPlayback and (not db.node.get_graph().get_default_graph_context().get_is_playing()): state.try_pop_event() return True payload = state.try_pop_event() if payload is None: return True # Copy the event dict contents into the output bundle db.outputs.bundle.clear() for name in payload.get_keys(): # Special 'path' entry gets copied to output attrib if name == payload_path: db.outputs.path = payload[name] continue as_str = payload[name] arg_obj = pickle.loads(codecs.decode(as_str.encode(), "base64")) attr_type, attr_value = arg_obj new_attr = db.outputs.bundle.insert((attr_type, name)) new_attr.value = attr_value get_interface().set_execution_enabled("outputs:execOut") return True # ---------------------------------------------------------------------------- @staticmethod def release(node): # Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing # after the node has been released. with suppress(og.OmniGraphError): state = OgnOnCustomEventDatabase.per_node_internal_state(node) if state.sub: state.sub.unsubscribe() state.sub = None # ---------------------------------------------------------------------------- @staticmethod def update_node_version(context: og.GraphContext, node: og.Node, old_version: int, new_version: int): if old_version < new_version and old_version < 2: # We added inputs:onlyPlayback default true - to maintain previous behavior we should set this to false node.create_attribute( "inputs:onlyPlayback", og.Type(og.BaseDataType.BOOL), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, False, ) return True
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnFlipFlop.ogn
{ "FlipFlop": { "version": 1, "description": "This node alternates activating its outputs, starting with A", "uiName": "Flip Flop", "categories": ["graph:action","flowControl"], "scheduling": ["threadsafe"], "exclude": ["tests"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" } }, "outputs": { "a": { "type": "execution", "description": "Executed on the 1st and odd numbered triggers", "uiName": "Execute A" }, "b": { "type": "execution", "description": "Executed on the even number triggers", "uiName": "Execute B" }, "isA": { "type": "bool", "description": "Set to true when a is activated", "uiName": "Is A" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnCountdown.ogn
{ "Countdown": { "version": 1, "description": [ "Delays for a number of updates (the duration) while firing output tick activations with a given period.", "When the countdown is complete it triggers the finished output.", "The first compute does not generate a tick output." ], "uiName": "Countdown", "language": "python", "categories": ["graph:action","flowControl"], "exclude": ["tests"], "inputs": { "execIn": { "type": "execution", "description": "The input execution" }, "duration": { "type": "int", "description": "The duration of the delay in ticks", "default": 5 }, "period": { "type": "int", "description": "The period of the pulse in ticks", "default": 1 } }, "outputs": { "finished": { "type": "execution", "description": "Triggered after duration ticks is finished" }, "tick": { "type": "execution", "description": "Triggered every 'period' ticks" }, "alpha": { "type": "float", "description": "normalized progress in the range IE 'tickValue'/'duration'" }, "tickValue": { "type": "int", "description": "The current tick value in the range [1, duration]" } }, "state": { "count": { "type": "int", "description": "The number of ticks elapsed, the first tick is 0", "default": -1 } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnDelay.cpp
// Copyright (c) 2021-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 <OgnDelayDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { namespace { constexpr double kUninitializedStartTime = -1.; } class OgnDelay { double m_startTime{ kUninitializedStartTime }; // The value of the context time when we started latent state public: static bool compute(OgnDelayDatabase& db) { auto iActionGraph = getInterface(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; auto& state = db.internalState<OgnDelay>(); double startTime = state.m_startTime; double now = iContext->getTimeSinceStart(contextObj); if (state.m_startTime > kUninitializedStartTime) { // We are being polled, check if we have slept long enough double duration = db.inputs.duration(); duration = std::max(duration, 0.); if (now - startTime >= duration) { state.m_startTime = kUninitializedStartTime; iActionGraph->endLatentState(db.getInstanceIndex()); iActionGraph->setExecutionEnabled(outputs::finished.token(), db.getInstanceIndex()); return true; } } else { // This is the first entry, start sleeping state.m_startTime = now; iActionGraph->startLatentState(db.getInstanceIndex()); return true; } // still sleeping return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnAddPrimRelationship.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "OgnAddPrimRelationshipDatabase.h" #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/common.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/relationship.h> #include <pxr/usd/usdUtils/stageCache.h> #include <omni/graph/core/PostUsdInclude.h> #include <algorithm> namespace omni { namespace graph { namespace action { class OgnAddPrimRelationship { public: // Add relationship data on a prim static bool compute(OgnAddPrimRelationshipDatabase& db) { const auto& path = db.inputs.path(); const auto& target = db.inputs.target(); auto& isSuccessful = db.outputs.isSuccessful(); isSuccessful = false; if (!pxr::SdfPath::IsValidPathString(path) || !pxr::SdfPath::IsValidPathString(target)) { return false; } const char* relName = db.tokenToString(db.inputs.name()); if (!relName) { return false; } pxr::SdfPath primPath(path); pxr::SdfPath targetPath(target); long int stageId = db.abi_context().iContext->getStageId(db.abi_context()); pxr::UsdStageRefPtr stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); pxr::UsdPrim prim = stage->GetPrimAtPath(primPath); if (!prim) { return false; } if (pxr::UsdRelationship myRel = prim.CreateRelationship(pxr::TfToken(relName))) { isSuccessful = myRel.AddTarget(targetPath); } return isSuccessful; } }; REGISTER_OGN_NODE() } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnTickN.ogn
{ "TickN": { "version": 1, "description": [ "Delays for a number of updates while firing output tick activations with a given period"], "uiName": "TickN", "language": "python", "categories": "internal:test", "exclude": ["tests", "usd", "docs"], "metadata": {"hidden": "true"}, "inputs": { "execIn": { "type": "execution", "description": "The input execution" }, "duration": { "type": "int", "description": "The duration of the delay in ticks" }, "period": { "type": "int", "description": "The period of the pulse in ticks", "default": 1 } }, "outputs": { "finished": { "type": "execution", "description": "Triggered when the delay is finished" }, "tick": { "type": "execution", "description": "Triggered every period ticks" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnPlaybackTick.cpp
// Copyright (c) 2021-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 <OgnOnPlaybackTickDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnOnPlaybackTick { public: static bool compute(OgnOnPlaybackTickDatabase& db) { const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; if (!iContext->getIsPlaying(contextObj)) { return true; } db.outputs.time() = iContext->getTime(contextObj); db.outputs.deltaSeconds() = iContext->getElapsedTime(contextObj); db.outputs.frame() = iContext->getFrame(contextObj); auto iActionGraph = getInterface(); iActionGraph->setExecutionEnabled(outputs::tick.token(), db.getInstanceIndex()); return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnAddPrimRelationship.ogn
{ "AddPrimRelationship": { "version": 1, "description": [ "Adds a target path to a relationship property.", "If the relationship property does not exist it will be created.", "Duplicate targets will not be added."], "uiName": "Add Prim Relationship", "categories": ["sceneGraph"], "scheduling": ["usd-write"], "inputs": { "execIn": { "type": "execution", "description": "The input execution port." }, "name": { "type": "token", "description": "Name of the relationship property.", "uiName": "Relationship Name" }, "path": { "type": "path", "description": "Path of the prim with the relationship property.", "uiName": "Prim Path" }, "target": { "type": "path", "description": "The target path to be added, which may be a prim, attribute or another relationship.", "uiName": "Target Path" } }, "outputs": { "isSuccessful": { "type": "bool", "description": "Whether the node has successfully added the new target to the relationship.", "uiName": "Is Successful" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnMultisequence.cpp
// Copyright (c) 2022-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 <OgnMultisequenceDatabase.h> #include <carb/extras/StringUtils.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnMultisequence { public: static bool setExecutionEnabled(NodeObj nodeObj, const char* attribName, bool andPushed, InstanceIndex instIndex) { auto iNode = nodeObj.iNode; if (!iNode->getAttributeExists(nodeObj, attribName)) return false; AttributeObj attrObj = iNode->getAttribute(nodeObj, attribName); auto iActionGraph = getInterface(); if (andPushed) iActionGraph->setExecutionEnabledAndPushed(attrObj.iAttribute->getNameToken(attrObj), instIndex); else iActionGraph->setExecutionEnabled(attrObj.iAttribute->getNameToken(attrObj), instIndex); return true; } // Which branch we should take next uint32_t m_nextOutput {0}; static bool compute(OgnMultisequenceDatabase& db) { OgnMultisequence& state = db.internalState<OgnMultisequence>(); NodeObj nodeObj = db.abi_node(); // Set the execution values uint32_t executionIndex = 0; // lots of room to append digits to the output name std::array<char, 32> outputName; auto formatAttrName = [&outputName](uint32_t n) { carb::extras::formatString(outputName.data(), outputName.size(), "outputs:output%d", n); }; for (uint32_t i = 0;; ++i) { formatAttrName(i); if (i == state.m_nextOutput && setExecutionEnabled(nodeObj, outputName.data(), true, db.getInstanceIndex())) { executionIndex = i; } else if (i != state.m_nextOutput && nodeObj.iNode->getAttributeExists(nodeObj, outputName.data())) { // keep looping while we are matching attributes (shouldn't be any holes in the sequence) } else { // Check for end of sequence if (executionIndex == i - 1) { formatAttrName(executionIndex); setExecutionEnabled(nodeObj, outputName.data(), false, db.getInstanceIndex()); state.m_nextOutput = 0; } else { ++state.m_nextOutput; } break; } } return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSetPrimActive.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. #include "OgnSetPrimActiveDatabase.h" #include <omni/graph/action/IActionGraph.h> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usdUtils/stageCache.h> #include <omni/graph/core/PostUsdInclude.h> #include <omni/fabric/FabricUSD.h> namespace omni { namespace graph { namespace action { class OgnSetPrimActive { public: // ---------------------------------------------------------------------------- static bool compute(OgnSetPrimActiveDatabase& db) { PXR_NS::SdfPath sdfPath; if(db.inputs.primTarget().size() == 0) { const auto& primPath = db.inputs.prim(); if (pxr::SdfPath::IsValidPathString(primPath)) { sdfPath = pxr::SdfPath(primPath); } else { return true; } } else { if(db.inputs.primTarget().size() > 1) db.logWarning("Only one prim target is supported, the rest will be ignored"); sdfPath = omni::fabric::toSdfPath(db.inputs.primTarget()[0]); } // Find our stage const GraphContextObj& context = db.abi_context(); long stageId = context.iContext->getStageId(context); auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); if (!stage) { db.logError("Could not find USD stage %ld", stageId); return false; } pxr::UsdPrim targetPrim = stage->GetPrimAtPath(sdfPath); if (!targetPrim) { db.logError("Could not find prim \"%s\" in USD stage", sdfPath.GetText()); return false; } bool ok = targetPrim.SetActive(db.inputs.active()); if (ok) { auto iActionGraph = getInterface(); iActionGraph->setExecutionEnabled(outputs::execOut.token(), db.getInstanceIndex()); return true; } db.logError("Failed to set %s active state", sdfPath.GetText()); return false; } }; REGISTER_OGN_NODE() } // namespace action } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnBranch.ogn
{ "Branch": { "version": 1, "description": "Outputs an execution pulse along a branch based on a boolean condition", "uiName": "Branch", "categories": ["graph:action","flowControl"], "scheduling": ["threadsafe"], "inputs": { "condition": { "type": "bool", "description": "The boolean condition which determines the output direction", "uiName": "Condition" }, "execIn": { "type": "execution", "description": "Input execution" } }, "outputs": { "execTrue": { "type": "execution", "description": "The output path when condition is True", "uiName": "True" }, "execFalse": { "type": "execution", "description": "The output path when condition is False", "uiName": "False" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnTickN.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from dataclasses import dataclass import omni.graph.core as og # Set True to enable verbose debugging prints to console DEBUG_PRINT = False # ============================================================================================================== @dataclass class OgnTickNState: count: int # -------------------------------------------------------------------------------------------------------------- class OgnTickN: @staticmethod def internal_state(): """Returns an object that will contain per-node state information""" return OgnTickNState(-1) @staticmethod def compute(db) -> bool: def print_state(state_string: str): print(f"{db.node.get_prim_path()} {state_string}") count = db.internal_state.count count += 1 if count == 0: _ = DEBUG_PRINT and print_state("START") finished, tick = og.ExecutionAttributeState.LATENT_PUSH, og.ExecutionAttributeState.DISABLED else: duration = db.inputs.duration if duration < count: # Finished finished, tick = og.ExecutionAttributeState.LATENT_FINISH, og.ExecutionAttributeState.DISABLED count = -1 _ = DEBUG_PRINT and print_state("FINISHED") else: # Still ticking finished = og.ExecutionAttributeState.DISABLED if (count % db.inputs.period) == 0: # noqa: S001 tick = og.ExecutionAttributeState.ENABLED else: tick = og.ExecutionAttributeState.DISABLED _ = DEBUG_PRINT and print_state("TICK") # Write outputs db.outputs.finished = finished db.outputs.tick = tick db.internal_state.count = count return True
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnCountdown.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.graph.core as og # Set True to enable verbose debugging prints to console DEBUG_PRINT = False # ============================================================================================================== class OgnCountdown: @staticmethod def initialize(_, node): og.Controller.attribute("state:count", node).set(-1) @staticmethod def compute(db) -> bool: def print_state(state_string: str): print(f"{db.node.get_prim_path()} {state_string}") count = db.state.count duration = db.inputs.duration count += 1 tick_value = 1 alpha = 0 if count == 0: if DEBUG_PRINT: print_state("START") finished, tick = og.ExecutionAttributeState.LATENT_PUSH, og.ExecutionAttributeState.DISABLED else: if duration < count: # Finished finished, tick = og.ExecutionAttributeState.LATENT_FINISH, og.ExecutionAttributeState.DISABLED tick_value = count - 1 alpha = 1.0 count = -1 if DEBUG_PRINT: print_state("FINISHED") else: # Still ticking finished = og.ExecutionAttributeState.DISABLED tick_value = count alpha = count / max(duration, 1) period = db.inputs.period if (period == 0) or ((count % db.inputs.period) == 0): # noqa: S001 tick = og.ExecutionAttributeState.ENABLED else: tick = og.ExecutionAttributeState.DISABLED if DEBUG_PRINT: print_state("TICK") # Write outputs db.outputs.finished = finished db.outputs.tick = tick db.state.count = count db.outputs.alpha = alpha db.outputs.tickValue = tick_value return True
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnCounter.ogn
{ "Counter": { "version": 1, "description": "This node counts the number of times it is computed since being reset", "uiName": "Counter", "categories": ["graph:action", "function"], "scheduling": ["threadsafe"], "exclude": ["tests"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "reset": { "type": "execution", "description": "Reset the internal counter", "uiName": "Reset" } }, "outputs": { "count": { "type": "int", "description": "The count value", "uiName": "Count" }, "execOut": { "type": "execution", "description": "The output execution", "uiName": "Execute Out" } }, "state": { "count": { "type": "int", "description": "The counter state" } }, "tests" : [ {"outputs:count": 1, "state_set:count": 0, "inputs:execIn": 1}, {"outputs:count": 2, "state_set:count": 1, "inputs:execIn": 1}, {"outputs:count": 0, "state_set:count": 1, "inputs:execIn": 0, "inputs:reset": 1, "state_get:count": 0} ] } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnCustomEvent.ogn
{ "OnCustomEvent": { "description": [ "Event node which fires when the specified custom event is sent.", "This node is used in combination with SendCustomEvent"], "version": 2, "uiName": "On Custom Event", "categories": ["graph:action", "event"], "scheduling": "compute-on-request", "language": "Python", "state": { }, "inputs": { "eventName": { "type": "token", "description": "The name of the custom event", "uiName": "Event Name", "metadata": { "literalOnly": "1" } }, "onlyPlayback": { "type": "bool", "description": "When true, the node is only computed while Stage is being played.", "uiName": "Only Simulate On Play", "default": true, "metadata": { "literalOnly": "1" } } }, "outputs": { "path": { "type": "token", "description": "The path associated with the received custom event", "uiName": "Path" }, "bundle": { "type": "bundle", "description": "Bundle received with the event", "uiName": "Bundle" }, "execOut": { "type": "execution", "description": "Executes when the event is received", "uiName": "Received" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnClosing.cpp
// Copyright (c) 2022-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 <OgnOnClosingDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnOnClosing { public: static bool compute(OgnOnClosingDatabase& db) { auto iActionGraph = getInterface(); // This node does nothing but trigger downstream when computed. When the execution evaluator receives the // pre-detach event it will ensure that only OnClosing nodes will be evaluated before cleaning up the graph. // It's not possible to encapsulate the closing logic of the evaluator in this node due to the // special requirement that other event nodes be disabled, which only applies to this one case. // (We don't want OnTick running during the closing). iActionGraph->setExecutionEnabled(outputs::execOut.token(), db.getInstanceIndex()); return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnMessageBusEvent.py
""" This is the implementation of the OGN node defined in OgnOnMessageBusEvent.ogn """ from contextlib import suppress from typing import Optional import carb import carb.dictionary import carb.events import numpy as np import omni.graph.core as og import omni.kit.app from omni.graph.action import get_interface from omni.graph.action.ogn.OgnOnMessageBusEventDatabase import OgnOnMessageBusEventDatabase class OgnOnMessageBusEventInternalState: """Convenience class for maintaining per-node state information""" def __init__(self): # This subscription object controls the lifetime of our callback, it will be # cleaned up automatically when our node is destroyed self.sub: carb.events.ISubscription = None # Set when the callback has triggered self.is_set = False # The last payload received self.payload: carb.dictionary.Item = None # The event_name we used to subscribe self.sub_event_name = "" # The node instance handle self.node: og.Node = None def on_event(self, custom_event: carb.events.IEvent): if custom_event is None: return self.is_set = True self.payload = custom_event.payload # Tell the evaluator we need to be computed if self.node.is_valid(): self.node.request_compute() def first_time_subscribe(self, node: og.Node, event_name: str) -> bool: """Checked call to set up carb subscription Args: node: The node instance event_name: The name of the carb event Returns: True if we subscribed, False if we are already subscribed """ if self.sub is not None and self.sub_event_name != event_name: # event name changed since we last subscribed, unsubscribe self.sub.unsubscribe() self.sub = None if self.sub is None: # Add a subscription for the given event name. This is a pop subscription, so we expect a 1-frame # lag between send and receive reg_event_name = carb.events.type_from_string(event_name) message_bus = omni.kit.app.get_app().get_message_bus_event_stream() self.sub = message_bus.create_subscription_to_pop_by_type(reg_event_name, self.on_event) self.sub_event_name = event_name self.node = node return True return False def try_pop_event(self) -> Optional[carb.dictionary.Item]: """Pop the payload of the last event received, or None if there is no event to pop""" if self.is_set: self.is_set = False payload = self.payload self.payload = None return payload return None # ====================================================================== class OgnOnMessageBusEvent: """ This node triggers when the specified message bus event is received """ @staticmethod def internal_state(): """Returns an object that will contain per-node state information""" return OgnOnMessageBusEventInternalState() @staticmethod def compute(db) -> bool: event_name = db.inputs.eventName if not event_name: return True state = db.internal_state if state.first_time_subscribe(db.node, event_name): return True # Drop events if we are disabled if db.inputs.onlyPlayback and (not db.node.get_graph().get_default_graph_context().get_is_playing()): state.try_pop_event() return True payload = state.try_pop_event() if payload is None: return True node: og.Node = db.node # Copy the event dict contents into dynamic attributes if they exist for key in payload.get_keys(): attr_name = f"outputs:{key}" if not node.get_attribute_exists(attr_name): continue attrib = node.get_attribute(attr_name) if attrib: value = payload[key] og_type: og.Type = attrib.get_resolved_type() is_array = og_type.array_depth > 0 is_tuple = og_type.tuple_count > 1 is_matrix = is_tuple and ( og_type.role in (og.AttributeRole.FRAME, og.AttributeRole.MATRIX, og.AttributeRole.TRANSFORM) ) if is_array: if is_matrix: dim = 2 if og_type.tuple_count == 4 else 3 if og_type.tuple_count == 9 else 4 value = np.array(value).reshape((-1, dim, dim)) elif is_tuple: dim = og_type.tuple_count value = np.array(value).reshape((-1, dim)) elif is_matrix: dim = 2 if og_type.tuple_count == 4 else 3 if og_type.tuple_count == 9 else 4 value = np.array(value).reshape((dim, dim)) try: og.Controller.set(attrib, value) except TypeError as exc: db.log_error(f"Failed to copy payload data {key} to attribute {attr_name}:\n{exc}") return False get_interface().set_execution_enabled("outputs:execOut") return True # ---------------------------------------------------------------------------- @staticmethod def release(node): # Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing # after the node has been released. with suppress(og.OmniGraphError): state = OgnOnMessageBusEventDatabase.per_node_internal_state(node) if state.sub: state.sub.unsubscribe() state.sub = None
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnStageEvent.ogn
{ "OnStageEvent": { "version": 3, "description": [ "Executes when the specified Stage Event occurs. Stage Events are emitted when certain", "USD stage-related actions are performed by the system:\n", "Saved: USD file saved.\n", "Selection Changed: USD Prim selection has changed.\n", "Hierarchy Changed: USD stage hierarchy has changed, e.g. a prim is added, deleted or moved.\n", "OmniGraph Start Play: OmniGraph started\n", "OmniGraph Stop Play: OmniGraph stopped\n", "Simulation Start Play: Simulation started\n", "Simulation Stop Play: Simulation stopped\n", "Animation Start Play: Animation playback has started\n", "Animation Stop Play: Animation playback has stopped" ], "uiName": "On Stage Event", "language": "Python", "categories": ["graph:action", "event"], "scheduling": "compute-on-request", "state": { }, "inputs": { "eventName": { "type": "token", "description": "The event of interest", "metadata": { "allowedTokens": { "Saved": "Saved", "SelectionChanged": "Selection Changed", "HierarchyChanged": "Hierarchy Changed", "OmniGraphStart": "OmniGraph Start Play", "OmniGraphStop": "OmniGraph Stop Play", "SimulationStart": "Simulation Start Play", "SimulationStop": "Simulation Stop Play", "AnimationStart": "Animation Start Play", "AnimationStop": "Animation Stop Play" }, "default": "Animation Start Play", "displayGroup": "parameters", "literalOnly": "1" } }, "onlyPlayback": { "type": "bool", "description": "When true, the node is only computed while Stage is being played.", "uiName": "Only Simulate On Play", "default": true, "metadata": { "literalOnly": "1" } } }, "outputs": { "execOut": { "type": "execution", "description": "The execution output" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnImpulseEvent.cpp
// Copyright (c) 2021-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 <OgnOnImpulseEventDatabase.h> #include <omni/graph/action/IActionGraph.h> #include "ActionNodeCommon.h" namespace omni { namespace graph { namespace action { class OgnOnImpulseEvent { public: // ---------------------------------------------------------------------------- // Called by OG when our state attrib changes. static void onValueChanged(const AttributeObj& attrObj, const void* userData) { // state::enableImpulse has changed, so we need to compute ASAP NodeObj nodeObj = attrObj.iAttribute->getNode(attrObj); nodeObj.iNode->requestCompute(nodeObj); } // ---------------------------------------------------------------------------- static void initialize(const GraphContextObj& context, const NodeObj& nodeObj) { AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, state::enableImpulse.m_token); attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true); } // ---------------------------------------------------------------------------- static bool compute(OgnOnImpulseEventDatabase& db) { if (checkNodeDisabledForOnlyPlay(db)) return true; bool enableImpulse = db.state.enableImpulse(); if (enableImpulse) { auto iActionGraph = getInterface(); iActionGraph->setExecutionEnabled(outputs::execOut.token(), db.getInstanceIndex()); db.state.enableImpulse() = false; } return true; } // ---------------------------------------------------------------------------- static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion) { if (oldVersion < newVersion) { if (oldVersion < 2) { // We added inputs:onlyPlayback default true - to maintain previous behavior we should set this to false const bool val{ false }; nodeObj.iNode->createAttribute(nodeObj, "inputs:onlyPlayback", Type(BaseDataType::eBool), &val, nullptr, kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr); } return true; } return false; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnCounter.cpp
// Copyright (c) 2022-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 "OgnCounterDatabase.h" #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnCounter { public: static bool compute(OgnCounterDatabase& db) { auto iActionGraph = getInterface(); bool isReset = iActionGraph->getExecutionEnabled(inputs::reset.token(), omni::graph::core::kAccordingToContextIndex); if (isReset) { db.state.count() = 0; } else { db.state.count() = db.state.count() + 1; } db.outputs.count() = db.state.count(); iActionGraph->setExecutionEnabled(outputs::execOut.token(), db.getInstanceIndex()); return true; } }; REGISTER_OGN_NODE() } // namespace action } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnForEach.cpp
// Copyright (c) 2022-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 <OgnForEachDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnForEach { public: size_t m_arrayIndex {0}; static bool compute(OgnForEachDatabase& db) { auto iActionGraph = getInterface(); auto const& arrayIn = db.inputs.arrayIn(); size_t const arrayLen = arrayIn.size(); auto& state = db.internalState<OgnForEach>(); if (state.m_arrayIndex >= arrayLen) { iActionGraph->setExecutionEnabled(outputs::finished.token(), db.getInstanceIndex()); state.m_arrayIndex = 0; return true; } size_t currentIndex = state.m_arrayIndex++; iActionGraph->setExecutionEnabledAndPushed(outputs::loopBody.token(), db.getInstanceIndex()); db.outputs.arrayIndex() = static_cast<int>(currentIndex); ConstRawPtr arrayAttribPtr{nullptr}; size_t arraySize{0}; arrayIn.rawData(arrayAttribPtr, arraySize); // arrayAttribPtr is a pointer to the attribute data, the data being an array of something, // so we need to deref that pointer to get the pointer to the actual data. ConstRawPtr arrayData = *(ConstRawPtr*)arrayAttribPtr; auto& element = db.outputs.element(); // Ensure output attribute is writable uint8_t* out{ nullptr }; void** outPtr = (void**)(&out); auto hdl = element.abi_handle(); db.abi_context().iAttributeData->getDataW(outPtr, db.abi_context(), &hdl, 1); if (!outPtr) { db.logError("Could not make writable output"); return false; } // Determine the size of the element to copy const IAttributeType& iAttributeType = *carb::getCachedInterface<IAttributeType>(); Type const type = element.type(); size_t strideBytes = iAttributeType.baseDataSize(type) * type.componentCount; size_t offsetBytes = currentIndex * strideBytes; memcpy(out, arrayData + offsetBytes, strideBytes); return true; } static void onConnectionTypeResolve(const NodeObj& node) { auto const arrayIn = node.iNode->getAttributeByToken(node, inputs::arrayIn.token()); auto const element = node.iNode->getAttributeByToken(node, outputs::element.token()); auto const arrayInType = arrayIn.iAttribute->getResolvedType(arrayIn); auto const elementType = element.iAttribute->getResolvedType(element); if (elementType.baseType == BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { arrayIn, element }; std::array<uint8_t, 2> tupleCounts { arrayInType.componentCount, arrayInType.componentCount }; // value type can not be an array because we don't support arrays-of-arrays std::array<uint8_t, 2> arrayDepths { 1, 0 }; std::array<AttributeRole, 2> rolesBuf { arrayInType.role, // Copy the attribute role from the array type to the value type AttributeRole::eUnknown }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } // namespace action } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnRationalTimeSyncGate.ogn
{ "RationalTimeSyncGate": { "version": 1, "description": ["This node triggers when all its input executions have triggered successively at the same rational time."], "uiName": "Rational Sync Gate", "categories": ["graph:action","flowControl"], "scheduling": ["threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "rationalTimeNumerator": { "type": "int64", "description": "Numerator of the synchronization time.", "uiName": "Sync Numerator" }, "rationalTimeDenominator": { "type": "uint64", "description": "Denominator of the synchronization time.", "uiName": "Sync Denominator" } }, "outputs": { "execOut": { "type": "execution", "description": "The output execution", "uiName": "Execute Out" }, "rationalTimeNumerator": { "type": "int64", "description": "Numerator of the synchronization time.", "uiName": "Sync Numerator" }, "rationalTimeDenominator": { "type": "uint64", "description": "Denominator of the synchronization time.", "uiName": "Sync Denominator" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSwitchToken.cpp
// Copyright (c) 2022-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 <OgnSwitchTokenDatabase.h> #include <carb/events/EventsUtils.h> #include <carb/extras/StringUtils.h> #include <cstring> #include <omni/graph/action/IActionGraph.h> static constexpr size_t kMaxAttrNameLen{ 17 }; static constexpr char k3Dots[] = "..."; namespace omni { namespace graph { namespace action { using namespace omni::fabric; using namespace carb::events; class OgnSwitchToken { carb::ObjectPtr<ISubscription> m_nodeChangedSub; // ---------------------------------------------------------------------------- static AttributeObj getCorrespondingOutputAttrib(NodeObj nodeObj, char const* branchName) { char buffer[32]; char const* suffix = branchName + std::strlen("inputs:branch"); (void) carb::extras::formatString(buffer, sizeof(buffer), "outputs:output%s", suffix); AttributeObj outputAttrObj = nodeObj.iNode->getAttribute(nodeObj, buffer); if (!outputAttrObj.isValid()) throw std::runtime_error(formatString("Could not find attribute %s", buffer)); return outputAttrObj; } // ---------------------------------------------------------------------------- // Return a shorter version of the given string with ... in the middle static std::array<char, kMaxAttrNameLen + 1> ellipsisStr(char const* val, size_t valLen) { constexpr size_t snipSize{ (kMaxAttrNameLen - 3 / 2) }; std::array<char, kMaxAttrNameLen + 1> uiLabel{}; auto writeIter = std::copy(val, val + snipSize, uiLabel.begin()); writeIter = std::copy(k3Dots, k3Dots + 3, writeIter); std::copy(val + valLen - snipSize, val + valLen, writeIter); return uiLabel; } // ---------------------------------------------------------------------------- static void onValueChanged(const AttributeObj& attrObj, const void* userData) { // Get the new value NodeObj nodeObj = attrObj.iAttribute->getNode(attrObj); if (nodeObj.nodeHandle == kInvalidNodeHandle) return; auto graphObj = nodeObj.iNode->getGraph(nodeObj); if (!graphObj.isValid()) return; auto context = graphObj.iGraph->getDefaultGraphContext(graphObj); if (!context.isValid()) return; std::string name = attrObj.iAttribute->getName(attrObj); if (name.size() < 14) return; char const* suffix = name.data() + 13; auto const* pBranchVal = getDataR<NameToken>( context, attrObj.iAttribute->getConstAttributeDataHandle(attrObj, kAccordingToContextIndex)); if (!pBranchVal) return; Token branchTok{*pBranchVal}; if (!branchTok.size()) return; // Set metadata on corresponding output attrib try { AttributeObj outputAttrObj = getCorrespondingOutputAttrib(nodeObj, name.c_str()); char const* branchVal = branchTok.getText(); size_t const branchValLen = strlen(branchVal); if (branchValLen > kMaxAttrNameLen) { // Too long - instead use middle-ellipsis auto uiLabel = ellipsisStr(branchVal, branchValLen); outputAttrObj.iAttribute->setMetadata(outputAttrObj, kOgnMetadataUiName, uiLabel.data()); } else outputAttrObj.iAttribute->setMetadata(outputAttrObj, kOgnMetadataUiName, branchTok.getText()); } catch (std::exception const& ex) { nodeObj.iNode->logComputeMessageOnInstance(nodeObj, kAuthoringGraphIndex, ogn::Severity::eError, ex.what()); } } public: // ---------------------------------------------------------------------------- static void initialize(const GraphContextObj& context, const NodeObj& nodeObj) { auto& state = OgnSwitchTokenDatabase::sInternalState<OgnSwitchToken>(nodeObj); // Callback anytime an attribute is added to this node so we can monitor value changed state.m_nodeChangedSub = carb::events::createSubscriptionToPop( nodeObj.iNode->getEventStream(nodeObj).get(), [nodeObj](carb::events::IEvent* e) { switch (static_cast<INodeEvent>(e->type)) { case INodeEvent::eCreateAttribute: { carb::dictionary::IDictionary* iDict = carb::dictionary::getCachedDictionaryInterface(); auto name = iDict->get<char const*>(e->payload, "attribute"); if (name && std::strstr(name, "inputs:branch") == name) { AttributeObj attribObj = nodeObj.iNode->getAttribute(nodeObj, name); if (attribObj.isValid()) { attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, false); } } } default: break; } }); // Hook up all the existing attributes to value changed callback size_t nAttribs = nodeObj.iNode->getAttributeCount(nodeObj); if (!nAttribs) return; std::vector<AttributeObj> allAttribs; allAttribs.resize(nAttribs); nodeObj.iNode->getAttributes(nodeObj, allAttribs.data(), nAttribs); for (auto& attribObj : allAttribs) { char const* name = attribObj.iAttribute->getName(attribObj); if (name && std::strstr(name, "inputs:branch") == name) { attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, false); } } } // ---------------------------------------------------------------------------- static bool compute(OgnSwitchTokenDatabase& db) { NodeObj nodeObj = db.abi_node(); GraphContextObj context = db.abi_context(); NameToken const value = db.inputs.value(); auto iNode = nodeObj.iNode; GraphObj graphObj = iNode->getGraph(nodeObj); // Check which branch matches the input value size_t nAttribs = nodeObj.iNode->getAttributeCount(nodeObj); if (!nAttribs) return false; std::vector<AttributeObj> allAttribs; allAttribs.resize(nAttribs); nodeObj.iNode->getAttributes(nodeObj, allAttribs.data(), nAttribs); for (auto& attribObj : allAttribs) { char const* name = attribObj.iAttribute->getName(attribObj); if (name && std::strstr(name, "inputs:branch") == name) { auto const* pBranchVal = getDataR<NameToken>(context, attribObj.iAttribute->getConstAttributeDataHandle(attribObj, db.getInstanceIndex())); if (value == *pBranchVal) { try { AttributeObj outputAttrObj = getCorrespondingOutputAttrib(nodeObj, name); auto iActionGraph = getInterface(); iActionGraph->setExecutionEnabled(outputAttrObj.iAttribute->getNameToken(outputAttrObj), db.getInstanceIndex()); } catch (std::exception const& ex) { db.logError(ex.what()); return false; } break; } } } return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnVariableChange.cpp
// Copyright (c) 2022-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 <OgnOnVariableChangeDatabase.h> #include <omni/graph/action/IActionGraph.h> #include <omni/graph/core/ogn/string.h> #include "ActionNodeCommon.h" namespace omni { namespace graph { namespace action { using namespace omni::graph::core; using omni::graph::core::ogn::VariableAttribute; // unnamed namespace to avoid multiple declaration when linking namespace { bool compareAndCacheVariables(VariableAttribute var, std::vector<uint8_t>& cachedVariable, Type& cachedType) { if (!var.isValid()) return true; RawPtr varValuePtr{ nullptr }; size_t size{ 0 }; if (cachedType.arrayDepth > 0) { // for arrays, raw data returns the pointer to the base address of the array and the size of the pointer var.rawData(varValuePtr, size); if (varValuePtr) { // var.size() is the number of elements. size = var.size() * var.type().baseTypeSize(); varValuePtr = *reinterpret_cast<RawPtr*>(varValuePtr); } } else { var.rawData(varValuePtr, size); } if (!varValuePtr) size = 0; if ((cachedType != var.type()) || (size != cachedVariable.size()) || (memcmp(cachedVariable.data(), varValuePtr, size) != 0)) { cachedType = var.type(); cachedVariable.resize(size); memcpy(cachedVariable.data(), varValuePtr, size); return false; } return true; } } // namespace class OgnOnVariableChange { std::vector<uint8_t> m_cachedVariable{}; Type m_cachedType{}; public: // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { AttributeObj attrObj = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::variableName.m_token); attrObj.iAttribute->registerValueChangedCallback(attrObj, onValueChanged, true); } // ---------------------------------------------------------------------------- // Called by OG when the value of the variableName changes static void onValueChanged(AttributeObj const& attrObj, void const* userData) { auto nodeObj = attrObj.iAttribute->getNode(attrObj); if (nodeObj.nodeHandle == kInvalidNodeHandle) return; NodeObj node = attrObj.iAttribute->getNode(attrObj); GraphObj graph = node.iNode->getGraph(nodeObj); size_t instCount = graph.iGraph->getInstanceCount(graph); //instanced or not if (instCount == 0) { auto& state = OgnOnVariableChangeDatabase::sInternalState<OgnOnVariableChange>(nodeObj, kAuthoringGraphIndex); state.m_cachedVariable.clear(); state.m_cachedType = Type(); } else { for (size_t idx = 0; idx < instCount; ++idx) { auto& state = OgnOnVariableChangeDatabase::sInternalState<OgnOnVariableChange>(nodeObj, {idx}); state.m_cachedVariable.clear(); state.m_cachedType = Type(); } } } static bool compute(OgnOnVariableChangeDatabase& db) { if (checkNodeDisabledForOnlyPlay(db)) return true; auto& state = db.internalState<OgnOnVariableChange>(); auto var = db.getVariable(db.inputs.variableName()); auto& cachedVariable = state.m_cachedVariable; auto& cachedType = state.m_cachedType; bool isClean = (cachedVariable.size() != 0); bool isSame = compareAndCacheVariables(var, cachedVariable, cachedType); if (isClean && !isSame) { auto iActionGraph = getInterface(); iActionGraph->setExecutionEnabled(outputs::changed.token(), db.getInstanceIndex()); } return true; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnTick.ogn
{ "OnTick": { "version": 1, "description": "Executes an output execution pulse at a regular multiple of the refresh rate", "uiName": "On Tick", "categories": ["graph:action", "event"], "scheduling": ["threadsafe"], "inputs": { "framePeriod": { "type": "uint", "description": [ "The number of updates between each output pulse.", "The default 0 means every update, 1 means every other update.", "This can be used to rate-limit updates." ], "default": 0, "uiName": "Update Period (Ticks)", "metadata": { "literalOnly": "1" } }, "onlyPlayback": { "type": "bool", "description": "When true, the node is only computed while Stage is being played.", "uiName": "Only Simulate On Play", "default": true, "metadata": { "literalOnly": "1" } } }, "outputs": { "tick": { "type": "execution", "description": "The execution output", "uiName": "Tick" }, "isPlaying": { "type": "bool", "description": "True during global animation timeline playback", "uiName": "Is Playing" }, "deltaSeconds": { "type": "double", "description": "The number of seconds elapsed since the last output pulse", "uiName": "Delta (Seconds)" }, "timeSinceStart": { "type": "double", "description": "Elapsed time since the App started", "uiName": "Time Since Start (Seconds)" }, "time": { "type": "double", "description": "The global animation time in seconds during playback", "uiName": "Animation Time (Seconds)" }, "frame": { "type": "double", "description": "The global animation time in frames, equivalent to (time * fps), during playback", "uiName": "Animation Time (Frames)" }, "absoluteSimTime": { "type": "double", "description": "The accumulated total of elapsed times between rendered frames", "uiName": "Absolute Simulation Time (Seconds)" } }, "state": { "frameCount": { "type": "uint", "description": "Accumulated frames since the last output pulse", "default": 0 }, "accumulatedSeconds": { "type": "double", "description": "Accumulated time since the last output pulse", "default": 0 } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnObjectChange.cpp
// Copyright (c) 2021-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. // // clang-format off #include "UsdPCH.h" // clang-format on #include <OgnOnObjectChangeDatabase.h> #include "ActionNodeCommon.h" #include <omni/graph/action/IActionGraph.h> #include <omni/fabric/FabricUSD.h> #include <omni/graph/core/ArrayWrapper.h> // clang-format off #include <omni/usd/UsdContext.h> // clang-format on #include <mutex> namespace omni { namespace graph { namespace action { using namespace omni::graph::core; // The idea here is that each node instance will register as a notice listener when it's compute is called if the path // input has changed, or they haven't registered before. The watched path needs to be verified every compute because // input could be changing at any point. The listener must always be revoked in `release`. Any changes since the last // compute() will trigger the output exection. // class UsdNoticeListener; using UsdNoticeListenerRefPtr = pxr::TfRefPtr<UsdNoticeListener>; using UsdNoticeListenerWeakPtr = pxr::TfWeakPtr<UsdNoticeListener>; // Derive from Ref and Weak bases so that we don't crash during `release` (and we delete the listener) from a // different thread than the notices are being sent on. Instead we just decref the listener so that the internal // weak pointer will keep it alive until notice sending is completed class UsdNoticeListener : public pxr::TfRefBase, public pxr::TfWeakBase { public: enum class WatchType { eInvalid, ePrim, ePrimProperty }; static UsdNoticeListenerRefPtr New(long stageId) { return pxr::TfCreateRefPtr(new UsdNoticeListener(stageId)); } ~UsdNoticeListener() { pxr::TfNotice::Revoke(m_registerKey); } void registerForPath(pxr::SdfPath path, UsdNoticeListenerRefPtr ptr) { // Ensure our dirty flag isn't still set { const std::lock_guard<std::mutex> lock(m_noticeMutex); m_watchedPath = path; m_isDirty = false; m_noticedName = pxr::TfToken(); } // If we are given an empty path we can revoke if (path.IsEmpty()) { if (m_registerKey.IsValid()) pxr::TfNotice::Revoke(m_registerKey); return; } // Determine if the path actually exists on the stage m_watchType = WatchType::eInvalid; if (path.IsPrimPath()) { pxr::UsdPrim prim = m_stage->GetPrimAtPath(path); if (!prim) return; m_watchType = WatchType::ePrim; } else if (path.IsPrimPropertyPath()) { pxr::UsdProperty prop = m_stage->GetPropertyAtPath(path); if (!prop) return; m_watchType = WatchType::ePrimProperty; } // Register ourselves if (!m_registerKey.IsValid()) m_registerKey = pxr::TfNotice::Register(UsdNoticeListenerWeakPtr(ptr), &UsdNoticeListener::Handle); } void Handle(const class pxr::UsdNotice::ObjectsChanged& objectsChanged) { // If already dirty, don't worry about it if (m_isDirty) return; if(m_stage != objectsChanged.GetStage()) return; switch (m_watchType) { case WatchType::ePrim: { pxr::UsdPrim prim = m_stage->GetPrimAtPath(m_watchedPath); if (prim) { for (const auto& path : objectsChanged.GetChangedInfoOnlyPaths()) { const pxr::SdfPath& changePath = path.GetPrimPath(); if (m_stage->GetPrimAtPath(changePath) == prim) { const std::lock_guard<std::mutex> lock(m_noticeMutex); m_noticedName = path.GetNameToken(); m_isDirty = true; break; } } } break; } case WatchType::ePrimProperty: { pxr::UsdProperty prop = m_stage->GetPropertyAtPath(m_watchedPath); if (prop) { if (objectsChanged.AffectedObject(prop)) { const std::lock_guard<std::mutex> lock(m_noticeMutex); m_noticedName = m_watchedPath.GetNameToken(); m_isDirty = true; } } break; } case WatchType::eInvalid: break; } } pxr::UsdStageRefPtr m_stage; pxr::TfNotice::Key m_registerKey; pxr::SdfPath m_watchedPath; WatchType m_watchType{ WatchType::eInvalid }; bool m_isDirty{ false }; pxr::TfToken m_noticedName; std::mutex m_noticeMutex; private: UsdNoticeListener(long stageId) { m_stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); if (!m_stage) { CARB_LOG_ERROR("Could not find USD stage"); return; } } }; // ============================================================================ class OgnOnObjectChange { public: UsdNoticeListenerRefPtr m_listener{ nullptr }; static bool compute(OgnOnObjectChangeDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); if (checkNodeDisabledForOnlyPlay(db)) return true; pxr::SdfPath watchedPath = toSdfPath(db.inputs.prim.firstOrDefault()); if (!watchedPath.IsEmpty()) { auto name = db.inputs.name(); if (name != omni::fabric::kUninitializedToken) { auto nameToken = toTfToken(name); watchedPath = watchedPath.AppendProperty(nameToken); } } if (watchedPath.IsEmpty()) { auto const& path = db.inputs.path(); if (!pxr::SdfPath::IsValidPathString(path)) { if (!path.empty()) { db.logError("Invalid path %s", path.data()); return false; } } else watchedPath = pxr::SdfPath(path); } auto& state = db.internalState<OgnOnObjectChange>(); auto processChange = [&]() -> pxr::TfToken { // Find the listener for this node, or create one if it doesn't exist if (!state.m_listener) { long stageId = db.abi_context().iContext->getStageId(db.abi_context()); state.m_listener = UsdNoticeListener::New(stageId); state.m_listener->registerForPath(watchedPath, state.m_listener); return pxr::TfToken(); } if (state.m_listener->m_watchedPath != watchedPath) { // re-register for the new path state.m_listener->registerForPath(watchedPath, state.m_listener); return pxr::TfToken(); } { const std::lock_guard<std::mutex> lock(state.m_listener->m_noticeMutex); if (std::exchange(state.m_listener->m_isDirty, false)) { return state.m_listener->m_noticedName; } } return pxr::TfToken(); }; auto changed = processChange(); if (!changed.IsEmpty()) { auto iActionGraph = getInterface(); iActionGraph->setExecutionEnabled(outputs::changed.token(), db.getInstanceIndex()); db.outputs.propertyName() = omni::fabric::asInt(changed); } return true; } // ---------------------------------------------------------------------------- static void release(const NodeObj& nodeObj) { auto& state = OgnOnObjectChangeDatabase::sInternalState<OgnOnObjectChange>(nodeObj); state.m_listener.Reset(); } // ---------------------------------------------------------------------------- static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion) { if (oldVersion < newVersion) { if (oldVersion < 2) { // We added inputs:onlyPlayback default true - to maintain previous behavior we should set this to false const bool val{ false }; nodeObj.iNode->createAttribute(nodeObj, "inputs:onlyPlayback", Type(BaseDataType::eBool), &val, nullptr, kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr); } return true; } return false; } }; REGISTER_OGN_NODE() } // action } // graph } // omni
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnPlaybackTick.ogn
{ "OnPlaybackTick": { "version": 1, "description": "Executes an output execution pulse during playback", "uiName": "On Playback Tick", "categories": ["graph:action", "event"], "scheduling": ["threadsafe"], "inputs": { }, "outputs": { "tick": { "type": "execution", "description": "The execution output", "uiName": "Tick" }, "deltaSeconds": { "type": "double", "description": "The number of seconds elapsed since the last update", "uiName": "Delta Seconds" }, "time": { "type": "double", "description": "The global playback time in seconds", "uiName": "Time" }, "frame": { "type": "double", "description": "The global playback time in frames, equivalent to (time * fps)", "uiName": "Frame" } } } }
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnTick.cpp
// Copyright (c) 2021-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 <OgnOnTickDatabase.h> #include <omni/graph/action/IActionGraph.h> namespace omni { namespace graph { namespace action { class OgnOnTick { public: static size_t computeVectorized(OgnOnTickDatabase& db, size_t count) { auto iActionGraph = getInterface(); const auto& contextObj = db.abi_context(); const IGraphContext* const iContext = contextObj.iContext; bool isPlaying = iContext->getIsPlaying(contextObj); auto elapsed = iContext->getElapsedTime(contextObj); auto const t = iContext->getTime(contextObj); auto const f = iContext->getFrame(contextObj); auto const ts = iContext->getTimeSinceStart(contextObj); auto const ast = iContext->getAbsoluteSimTime(contextObj); auto onlyPlayback = db.inputs.onlyPlayback.vectorized(count); auto framePeriod = db.inputs.framePeriod.vectorized(count); auto isPlayingOut = db.outputs.isPlaying.vectorized(count); auto time = db.outputs.time.vectorized(count); auto frame = db.outputs.frame.vectorized(count); auto timeSinceStart = db.outputs.timeSinceStart.vectorized(count); auto absoluteSimTime = db.outputs.absoluteSimTime.vectorized(count); auto deltaSeconds = db.outputs.deltaSeconds.vectorized(count); auto accumulatedSeconds = db.state.accumulatedSeconds.vectorized(count); auto frameCount = db.state.frameCount.vectorized(count); for (size_t idx = 0; idx < count; ++idx) { if (onlyPlayback[idx] && !isPlaying) { accumulatedSeconds[idx] = 0; frameCount[idx] = 0; continue; } ++frameCount[idx]; accumulatedSeconds[idx] += elapsed; if (frameCount[idx] > framePeriod[idx]) { frameCount[idx] = 0; deltaSeconds[idx] = accumulatedSeconds[idx]; accumulatedSeconds[idx] = 0; isPlayingOut[idx] = isPlaying; time[idx] = t; frame[idx] = f; timeSinceStart[idx] = ts; absoluteSimTime[idx] = ast; iActionGraph->setExecutionEnabled(outputs::tick.token(), db.getInstanceIndex() + idx); } } return count; } }; REGISTER_OGN_NODE() } // action } // graph } // omni