file_path
stringlengths 32
153
| content
stringlengths 0
3.14M
|
---|---|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnMultisequence.ogn | {
"Multisequence": {
"version": 1,
"description": [
"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."
],
"uiName": "Sequence",
"categories": ["graph:action", "flowControl"],
"scheduling": ["threadsafe"],
"inputs": {
"execIn": {
"type": "execution",
"description": "The input execution",
"uiName": "Execute In"
}
},
"outputs": {
"output0": {
"type": "execution",
"description": "Output execution"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnFlipFlop.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 <OgnFlipFlopDatabase.h>
#include <omni/graph/action/IActionGraph.h>
namespace omni
{
namespace graph
{
namespace action
{
class OgnFlipFlop
{
public:
// The flip-flop cycles output activation between 2 outputs
static constexpr size_t kNumLevels = 2;
// The output that will be activated on the next compute. 0 == A, 1 == B
int m_nextLevel{ 0 };
static bool compute(OgnFlipFlopDatabase& db)
{
auto iActionGraph = getInterface();
OgnFlipFlop& state = db.internalState<OgnFlipFlop>();
if (state.m_nextLevel == 0)
{
iActionGraph->setExecutionEnabled(outputs::a.token(), db.getInstanceIndex());
db.outputs.isA() = true;
}
else
{
iActionGraph->setExecutionEnabled(outputs::b.token(), db.getInstanceIndex());
db.outputs.isA() = false;
}
state.m_nextLevel = (state.m_nextLevel + 1) % kNumLevels;
return true;
}
};
REGISTER_OGN_NODE()
} // action
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSyncGate.ogn | {
"SyncGate": {
"version": 1,
"description": ["This node triggers when all its input executions have triggered successively at the same synchronization value."],
"uiName": "Sync Gate",
"categories": ["graph:action","flowControl"],
"scheduling": ["threadsafe"],
"inputs": {
"execIn": {
"type": "execution",
"description": "The input execution",
"uiName": "Execute In"
},
"syncValue": {
"type": "uint64",
"description": "Value of the synchronization reference.",
"uiName": "Sync"
}
},
"outputs": {
"execOut": {
"type": "execution",
"description": "The output execution",
"uiName": "Execute Out"
},
"syncValue": {
"type": "uint64",
"description": "Value of the synchronization reference.",
"uiName": "Sync"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/ActionNodeCommon.h | // Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
namespace omni
{
namespace graph
{
namespace action
{
/**
* Checks if the node with `inputs:onlyPlayback` should be disabled, because playback is not happening.
*
* @param[in] db The node OGN Database object
* @return true if the node should be disabled
*/
template<typename NodeDb>
bool checkNodeDisabledForOnlyPlay(NodeDb const& db)
{
return db.inputs.onlyPlayback() && (not db.abi_context().iContext->getIsPlaying(db.abi_context()));
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSyncGate.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 <OgnSyncGateDatabase.h>
#include <omni/graph/action/IActionGraph.h>
namespace omni
{
namespace graph
{
namespace action
{
class OgnSyncGate
{
public:
// The current number of accumulated executions.
uint32_t m_numAccumulatedExecIn{ 0 };
// The current synchronization value.
uint64_t m_syncValue{ 0 };
static bool compute(OgnSyncGateDatabase& 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));
OgnSyncGate& state = db.internalState<OgnSyncGate>();
const bool reset = db.inputs.syncValue() != state.m_syncValue;
state.m_numAccumulatedExecIn = reset ? 1 : std::min(state.m_numAccumulatedExecIn + 1, accumulationThreshold);
db.outputs.syncValue() = state.m_syncValue = db.inputs.syncValue();
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/OgnOnObjectChange.ogn | {
"OnObjectChange": {
"version": 4,
"description": "Executes an output execution pulse when the watched USD Object changes",
"uiName": "On USD Object Change",
"categories": ["graph:action", "event"],
"scheduling": ["threadsafe"],
"inputs": {
"path": {
"type": "path",
"description": "The path of object of interest (property or prim). If the prim input has a target, this is ignored",
"uiName": "Path",
"optional": true,
"deprecated": "Use prim input instead",
"metadata": {
"literalOnly": "1"
}
},
"prim": {
"type": "target",
"description": "The prim of interest. If this has a target, the path input will be ignored",
"uiName": "Prim",
"optional": true,
"metadata": {
"literalOnly": "1"
}
},
"name": {
"type": "token",
"description": "The name of the property to watch if prim input is set",
"uiName": "Property Name",
"optional": true,
"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"
},
"propertyName": {
"type": "token",
"description": "The name of the property that changed",
"uiName": "Property Name"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnMultigate.ogn | {
"Multigate": {
"version": 1,
"description": [
"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..."
],
"uiName": "Multigate",
"categories": ["graph:action","flowControl"],
"scheduling": ["threadsafe"],
"inputs": {
"execIn": {
"type": "execution",
"description": "The input execution",
"uiName": "Execute In"
}
},
"outputs": {
"output0": {
"type": "execution",
"description": "Output execution"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnGamepadInput.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 "ActionNodeCommon.h"
#include <carb/input/IInput.h>
#include <carb/input/InputTypes.h>
#include <omni/graph/action/IActionGraph.h>
#include <omni/kit/IAppWindow.h>
#include <OgnOnGamepadInputDatabase.h>
#include <atomic>
using namespace carb::input;
namespace omni
{
namespace graph
{
namespace action
{
// This is different from carb::input::GamepadInput::eCount by 10 because we don't allow joysticks and triggers input.
constexpr auto s_firstEventWeCareAbout = carb::input::GamepadInput::eA;
constexpr size_t s_numNames = size_t(carb::input::GamepadInput::eCount) - size_t(s_firstEventWeCareAbout);
static std::array<NameToken, s_numNames> s_elementTokens;
class OgnOnGamepadInput
{
public:
// Assume a zero subsId means not registered
SubscriptionId m_gamepadConnectionSubsId{ 0 };
SubscriptionId m_elementEventSubsId{ 0 };
GamepadEvent m_elementEvent;
std::atomic<bool> m_requestedRegistrationInCompute{ false }; // Dirty flag to ask compute() to potentially subscribe
// to the new gamepad if needed
exec::unstable::Stamp m_elementSetStamp; // The stamp set by the authoring node when the even occurs
exec::unstable::SyncStamp m_elementSetSyncStamp; // The stamp used by each instance
static bool trySwitchGamepadSubscription(const size_t newGamepadId, const NodeObj& nodeObj)
{
IInput* input = carb::getCachedInterface<IInput>();
if (!input)
return false;
auto& state = OgnOnGamepadInputDatabase::sInternalState<OgnOnGamepadInput>(nodeObj, kAuthoringGraphIndex);
omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow();
if (!appWindow)
{
return false;
}
Gamepad* gamepad = appWindow->getGamepad(newGamepadId);
if (!gamepad)
{
CARB_LOG_WARN_ONCE("The new gamepad ID is not associated with any gamepad");
if (state.m_elementEventSubsId > 0)
{
input->unsubscribeToInputEvents(state.m_elementEventSubsId);
}
state.m_elementEventSubsId = 0;
return false;
}
if (state.m_elementEventSubsId > 0)
{
input->unsubscribeToInputEvents(state.m_elementEventSubsId);
}
state.m_elementEventSubsId =
input->subscribeToInputEvents((carb::input::InputDevice*)gamepad, kEventTypeAll, onGamepadEvent,
reinterpret_cast<void*>(nodeObj.nodeHandle), kSubscriptionOrderDefault);
return true;
}
static bool onGamepadEvent(const InputEvent& e, void* userData)
{
if (e.deviceType != DeviceType::eGamepad)
{
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;
// Copy the event data and request the next compute()
auto& authoringState =
OgnOnGamepadInputDatabase::sInternalState<OgnOnGamepadInput>(nodeObj, kAuthoringGraphIndex);
authoringState.m_elementSetStamp.next();
authoringState.m_elementEvent = e.gamepadEvent;
iNode->requestCompute(nodeObj);
return true;
}
static void onGamepadIdChanged(const AttributeObj& attrObj, const void* value)
{
NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) };
if (nodeObj.nodeHandle == kInvalidNodeHandle)
return;
GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) };
if (graphObj.graphHandle == kInvalidGraphHandle)
return;
GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) };
if (context.contextHandle == kInvalidGraphContextHandle)
return;
ConstAttributeDataHandle attributeDataHandle =
attrObj.iAttribute->getConstAttributeDataHandle(attrObj, kAccordingToContextIndex);
const uint32_t gamepadId = *getDataR<uint32_t>(context, attributeDataHandle);
// Change subscription target
trySwitchGamepadSubscription(gamepadId, nodeObj);
}
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 = ([] {
s_elementTokens = {
OgnOnGamepadInputDatabase::tokens.FaceButtonBottom,
OgnOnGamepadInputDatabase::tokens.FaceButtonRight,
OgnOnGamepadInputDatabase::tokens.FaceButtonLeft,
OgnOnGamepadInputDatabase::tokens.FaceButtonTop,
OgnOnGamepadInputDatabase::tokens.LeftShoulder,
OgnOnGamepadInputDatabase::tokens.RightShoulder,
OgnOnGamepadInputDatabase::tokens.SpecialLeft,
OgnOnGamepadInputDatabase::tokens.SpecialRight,
OgnOnGamepadInputDatabase::tokens.LeftStickButton,
OgnOnGamepadInputDatabase::tokens.RightStickButton,
OgnOnGamepadInputDatabase::tokens.DpadUp,
OgnOnGamepadInputDatabase::tokens.DpadRight,
OgnOnGamepadInputDatabase::tokens.DpadDown,
OgnOnGamepadInputDatabase::tokens.DpadLeft
};
} (), true);
// Get the default or stored gamepad ID when creating new nodes or loading a saved file
auto gamepadIdAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::gamepadId.token());
IInput* input = carb::getCachedInterface<IInput>();
if (!input)
return; // Happens normally in headless
auto& authoringState =
OgnOnGamepadInputDatabase::sInternalState<OgnOnGamepadInput>(nodeObj, kAuthoringGraphIndex);
authoringState.m_requestedRegistrationInCompute.store(true);
gamepadIdAttr.iAttribute->registerValueChangedCallback(gamepadIdAttr, onGamepadIdChanged, true);
// This will allow user to connect gamepad after specifying gamepad ID
authoringState.m_gamepadConnectionSubsId = input->subscribeToGamepadConnectionEvents(
[](const carb::input::GamepadConnectionEvent& evt, void* userData)
{
NodeHandle nodeHandle = reinterpret_cast<NodeHandle>(userData);
auto iNode = carb::getCachedInterface<omni::graph::core::INode>();
NodeObj nodeObj = iNode->getNodeFromHandle(nodeHandle);
auto& state = OgnOnGamepadInputDatabase::sInternalState<OgnOnGamepadInput>(nodeObj);
state.m_requestedRegistrationInCompute.store(true);
// Since the subscription depends on another GamepadConnectionEvents in IAppWindwImplCommon, and we
// cannot assume the execution order
iNode->requestCompute(nodeObj);
},
reinterpret_cast<void*>(nodeObj.nodeHandle));
}
static void release(const NodeObj& nodeObj)
{
auto& authoringState = OgnOnGamepadInputDatabase::sInternalState<OgnOnGamepadInput>(nodeObj);
IInput* input = carb::getCachedInterface<IInput>();
if (!input)
return;
if (authoringState.m_elementEventSubsId > 0)
{
input->unsubscribeToInputEvents(authoringState.m_elementEventSubsId);
}
if (authoringState.m_gamepadConnectionSubsId > 0)
{
input->unsubscribeToGamepadConnectionEvents(authoringState.m_gamepadConnectionSubsId);
}
}
static bool compute(OgnOnGamepadInputDatabase& db)
{
auto& authoringState =
OgnOnGamepadInputDatabase::sInternalState<OgnOnGamepadInput>(db.abi_node(), kAuthoringGraphIndex);
auto& localState = db.internalState<OgnOnGamepadInput>();
// Retry subscribe gamepad when new gamepad is connected
if (authoringState.m_requestedRegistrationInCompute.exchange(false))
{
trySwitchGamepadSubscription(db.inputs.gamepadId(), db.abi_node());
}
if (checkNodeDisabledForOnlyPlay(db))
return true;
if (localState.m_elementSetSyncStamp.makeSync(authoringState.m_elementSetStamp))
{
NameToken const& gamepadElementIn = db.inputs.gamepadElementIn();
// Offset the index by 10 since we excluded the joysticks and triggers.
if (size_t(authoringState.m_elementEvent.input) < size_t(s_firstEventWeCareAbout))
return true;
size_t elementIndex = size_t(authoringState.m_elementEvent.input) - size_t(s_firstEventWeCareAbout);
if (elementIndex >= s_elementTokens.size())
{
db.logError("Invalid Key %d detected", authoringState.m_elementEvent.input);
return false;
}
auto iActionGraph = getInterface();
if (gamepadElementIn == s_elementTokens[elementIndex])
{
if (authoringState.m_elementEvent.value == 1)
{
iActionGraph->setExecutionEnabled(outputs::pressed.token(), omni::graph::core::kAccordingToContextIndex);
db.outputs.isPressed() = true;
}
else
{
iActionGraph->setExecutionEnabled(outputs::released.token(), omni::graph::core::kAccordingToContextIndex);
db.outputs.isPressed() = false;
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
} // namespace action
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnImpulseEvent.ogn | {
"OnImpulseEvent": {
"version": 2,
"description": "Triggers the output execution once when state is set",
"uiName": "On Impulse Event",
"categories": ["graph:action", "event"],
"scheduling": ["compute-on-request", "threadsafe"],
"inputs": {
"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",
"uiName": "Trigger"
}
},
"state": {
"enableImpulse": {
"type": "bool",
"description": "When true, execute output once and reset to false"
}
},
"tests": [
{
"outputs:execOut": 0,
"state_set:enableImpulse": false,
"state_get:enableImpulse": false
},
{
"inputs:onlyPlayback": false,
"outputs:execOut": 1,
"state_set:enableImpulse": true,
"state_get:enableImpulse": false
}
]
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnDelay.ogn | {
"Delay": {
"version": 1,
"description": [
"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."
],
"uiName": "Delay",
"categories": ["graph:action", "time"],
"scheduling": ["threadsafe"],
"exclude": ["tests"],
"inputs": {
"execIn": {
"type": "execution",
"description": "The input execution",
"uiName": "Execute In"
},
"duration": {
"type": "double",
"description": "The duration of the delay (Seconds)",
"uiName": "Duration"
}
},
"outputs": {
"finished": {
"type": "execution",
"description": "Triggered when the delay is finished",
"uiName": "Finished"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSwitchToken.ogn | {
"SwitchToken": {
"version": 1,
"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'"
],
"uiName": "Switch On Token",
"categories": ["graph:action","flowControl"],
"scheduling": ["threadsafe"],
"inputs": {
"value": {
"type": "token",
"description": "The value to switch on",
"uiName": "Value"
},
"execIn": {
"type": "execution",
"description": "Input execution"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnForEach.ogn | {
"ForEach": {
"version": 1,
"description": [
"Executes the a loop body once for each element in the input array.",
"The finished output is executed after all iterations are complete"
],
"categories": ["graph:action","flowControl"],
"scheduling": ["threadsafe"],
"uiName": "For Each Loop",
"icon": {
"path": "LoopNodeIcon.svg"
},
"inputs": {
"arrayIn": {
"type": ["arrays", "bool[]"],
"description": "The array to loop over",
"$required": true,
"uiName": "Input Array"
},
"execIn": {
"type": "execution",
"description": "Input execution"
}
},
"outputs": {
"loopBody": {
"type": "execution",
"description": "Executed for each element of the array"
},
"element": {
"type": ["array_elements", "bool"],
"description": "The current or last element of the array visited"
},
"arrayIndex": {
"type": "int",
"description": "The current or last index visited"
},
"finished": {
"type": "execution",
"description": "Executed when the loop is finished"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnBranch.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnBranchDatabase import OgnBranchDatabase
test_file_name = "OgnBranchTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_Branch")
database = OgnBranchDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:condition"))
attribute = test_node.get_attribute("inputs:condition")
db_value = database.inputs.condition
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("outputs:execFalse"))
attribute = test_node.get_attribute("outputs:execFalse")
db_value = database.outputs.execFalse
self.assertTrue(test_node.get_attribute_exists("outputs:execTrue"))
attribute = test_node.get_attribute("outputs:execTrue")
db_value = database.outputs.execTrue
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnStageEvent.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnStageEventDatabase import OgnOnStageEventDatabase
test_file_name = "OgnOnStageEventTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnStageEvent")
database = OgnOnStageEventDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 3)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:eventName"))
attribute = test_node.get_attribute("inputs:eventName")
db_value = database.inputs.eventName
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:onlyPlayback"))
attribute = test_node.get_attribute("inputs:onlyPlayback")
db_value = database.inputs.onlyPlayback
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnSwitchToken.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnSwitchTokenDatabase import OgnSwitchTokenDatabase
test_file_name = "OgnSwitchTokenTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_SwitchToken")
database = OgnSwitchTokenDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:value"))
attribute = test_node.get_attribute("inputs:value")
db_value = database.inputs.value
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnVariableChange.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnVariableChangeDatabase import OgnOnVariableChangeDatabase
test_file_name = "OgnOnVariableChangeTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnVariableChange")
database = OgnOnVariableChangeDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:onlyPlayback"))
attribute = test_node.get_attribute("inputs:onlyPlayback")
db_value = database.inputs.onlyPlayback
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:variableName"))
attribute = test_node.get_attribute("inputs:variableName")
db_value = database.inputs.variableName
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:changed"))
attribute = test_node.get_attribute("outputs:changed")
db_value = database.outputs.changed
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnGate.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'inputs': [
['inputs:enter', 1, False],
],
'outputs': [
['outputs:exit', 1, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_action_Gate", "omni.graph.action.Gate", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.action.Gate User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_action_Gate","omni.graph.action.Gate", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.action.Gate User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_action_Gate", "omni.graph.action.Gate", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.action.Gate User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.action.ogn.OgnGateDatabase import OgnGateDatabase
test_file_name = "OgnGateTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_Gate")
database = OgnGateDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:enter"))
attribute = test_node.get_attribute("inputs:enter")
db_value = database.inputs.enter
self.assertTrue(test_node.get_attribute_exists("inputs:startClosed"))
attribute = test_node.get_attribute("inputs:startClosed")
db_value = database.inputs.startClosed
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:toggle"))
attribute = test_node.get_attribute("inputs:toggle")
db_value = database.inputs.toggle
self.assertTrue(test_node.get_attribute_exists("outputs:exit"))
attribute = test_node.get_attribute("outputs:exit")
db_value = database.outputs.exit
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnDelay.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
import os
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnDelayDatabase import OgnDelayDatabase
test_file_name = "OgnDelayTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_Delay")
database = OgnDelayDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:duration"))
attribute = test_node.get_attribute("inputs:duration")
db_value = database.inputs.duration
expected_value = 0.0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("outputs:finished"))
attribute = test_node.get_attribute("outputs:finished")
db_value = database.outputs.finished
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnTick.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnTickDatabase import OgnOnTickDatabase
test_file_name = "OgnOnTickTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnTick")
database = OgnOnTickDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:framePeriod"))
attribute = test_node.get_attribute("inputs:framePeriod")
db_value = database.inputs.framePeriod
expected_value = 0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:onlyPlayback"))
attribute = test_node.get_attribute("inputs:onlyPlayback")
db_value = database.inputs.onlyPlayback
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:absoluteSimTime"))
attribute = test_node.get_attribute("outputs:absoluteSimTime")
db_value = database.outputs.absoluteSimTime
self.assertTrue(test_node.get_attribute_exists("outputs:deltaSeconds"))
attribute = test_node.get_attribute("outputs:deltaSeconds")
db_value = database.outputs.deltaSeconds
self.assertTrue(test_node.get_attribute_exists("outputs:frame"))
attribute = test_node.get_attribute("outputs:frame")
db_value = database.outputs.frame
self.assertTrue(test_node.get_attribute_exists("outputs:isPlaying"))
attribute = test_node.get_attribute("outputs:isPlaying")
db_value = database.outputs.isPlaying
self.assertTrue(test_node.get_attribute_exists("outputs:tick"))
attribute = test_node.get_attribute("outputs:tick")
db_value = database.outputs.tick
self.assertTrue(test_node.get_attribute_exists("outputs:time"))
attribute = test_node.get_attribute("outputs:time")
db_value = database.outputs.time
self.assertTrue(test_node.get_attribute_exists("outputs:timeSinceStart"))
attribute = test_node.get_attribute("outputs:timeSinceStart")
db_value = database.outputs.timeSinceStart
self.assertTrue(test_node.get_attribute_exists("state:accumulatedSeconds"))
attribute = test_node.get_attribute("state:accumulatedSeconds")
db_value = database.state.accumulatedSeconds
self.assertTrue(test_node.get_attribute_exists("state:frameCount"))
attribute = test_node.get_attribute("state:frameCount")
db_value = database.state.frameCount
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnCounter.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
import os
class TestOgn(ogts.OmniGraphTestCase):
async def test_generated(self):
test_data = [{'inputs': [['inputs:execIn', 1, False]], 'outputs': [['outputs:count', 1, False]], 'state_set': [['state:count', 0, False]]}, {'inputs': [['inputs:execIn', 1, False]], 'outputs': [['outputs:count', 2, False]], 'state_set': [['state:count', 1, False]]}, {'inputs': [['inputs:execIn', 0, False], ['inputs:reset', 1, False]], 'outputs': [['outputs:count', 0, False]], 'state_set': [['state:count', 1, False]], 'state_get': [['state:count', 0, False]]}]
test_node = None
test_graph = None
for i, test_run in enumerate(test_data):
inputs = test_run.get('inputs', [])
outputs = test_run.get('outputs', [])
state_set = test_run.get('state_set', [])
state_get = test_run.get('state_get', [])
setup = test_run.get('setup', None)
if setup is None or setup:
await omni.usd.get_context().new_stage_async()
test_graph = None
elif not setup:
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test")
if setup:
(test_graph, test_nodes, _, _) = og.Controller.edit("/TestGraph", setup)
self.assertTrue(test_nodes)
test_node = test_nodes[0]
elif setup is None:
if test_graph is None:
test_graph = og.Controller.create_graph("/TestGraph")
self.assertTrue(test_graph is not None and test_graph.is_valid())
test_node = og.Controller.create_node(
("TestNode_omni_graph_action_Counter", test_graph), "omni.graph.action.Counter"
)
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test graph invalid")
self.assertTrue(test_node is not None and test_node.is_valid(), "Test node invalid")
await og.Controller.evaluate(test_graph)
values_to_set = inputs + state_set
if values_to_set:
for attribute_name, attribute_value, _ in inputs + state_set:
og.Controller((attribute_name, test_node)).set(attribute_value)
await og.Controller.evaluate(test_graph)
for attribute_name, expected_value, _ in outputs + state_get:
attribute = og.Controller.attribute(attribute_name, test_node)
actual_output = og.Controller.get(attribute)
expected_type = None
if isinstance(expected_value, dict):
expected_type = expected_value["type"]
expected_value = expected_value["value"]
ogts.verify_values(expected_value, actual_output, f"omni.graph.action.Counter User test case #{i+1}: {attribute_name} attribute value error")
if expected_type:
tp = og.AttributeType.type_from_ogn_type_name(expected_type)
actual_type = attribute.get_resolved_type()
if tp != actual_type:
raise ValueError(f"omni.graph.action.Counter User tests - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}")
async def test_data_access(self):
from omni.graph.action.ogn.OgnCounterDatabase import OgnCounterDatabase
test_file_name = "OgnCounterTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_Counter")
database = OgnCounterDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:reset"))
attribute = test_node.get_attribute("inputs:reset")
db_value = database.inputs.reset
self.assertTrue(test_node.get_attribute_exists("outputs:count"))
attribute = test_node.get_attribute("outputs:count")
db_value = database.outputs.count
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
self.assertTrue(test_node.get_attribute_exists("state:count"))
attribute = test_node.get_attribute("state:count")
db_value = database.state.count
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnCustomEvent.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnCustomEventDatabase import OgnOnCustomEventDatabase
test_file_name = "OgnOnCustomEventTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnCustomEvent")
database = OgnOnCustomEventDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 2)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:eventName"))
attribute = test_node.get_attribute("inputs:eventName")
db_value = database.inputs.eventName
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:onlyPlayback"))
attribute = test_node.get_attribute("inputs:onlyPlayback")
db_value = database.inputs.onlyPlayback
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs_bundle"))
attribute = test_node.get_attribute("outputs_bundle")
db_value = database.outputs.bundle
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
self.assertTrue(test_node.get_attribute_exists("outputs:path"))
attribute = test_node.get_attribute("outputs:path")
db_value = database.outputs.path
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/__init__.py | """====== GENERATED BY omni.graph.tools - DO NOT EDIT ======"""
import omni.graph.tools._internal as ogi
ogi.import_tests_in_directory(__file__, __name__)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnAddPrimRelationship.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnAddPrimRelationshipDatabase import OgnAddPrimRelationshipDatabase
test_file_name = "OgnAddPrimRelationshipTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_AddPrimRelationship")
database = OgnAddPrimRelationshipDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:name"))
attribute = test_node.get_attribute("inputs:name")
db_value = database.inputs.name
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:path"))
attribute = test_node.get_attribute("inputs:path")
db_value = database.inputs.path
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:target"))
attribute = test_node.get_attribute("inputs:target")
db_value = database.inputs.target
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:isSuccessful"))
attribute = test_node.get_attribute("outputs:isSuccessful")
db_value = database.outputs.isSuccessful
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnSyncGate.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnSyncGateDatabase import OgnSyncGateDatabase
test_file_name = "OgnSyncGateTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_SyncGate")
database = OgnSyncGateDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:syncValue"))
attribute = test_node.get_attribute("inputs:syncValue")
db_value = database.inputs.syncValue
expected_value = 0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
self.assertTrue(test_node.get_attribute_exists("outputs:syncValue"))
attribute = test_node.get_attribute("outputs:syncValue")
db_value = database.outputs.syncValue
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnForEach.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnForEachDatabase import OgnForEachDatabase
test_file_name = "OgnForEachTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_ForEach")
database = OgnForEachDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("outputs:arrayIndex"))
attribute = test_node.get_attribute("outputs:arrayIndex")
db_value = database.outputs.arrayIndex
self.assertTrue(test_node.get_attribute_exists("outputs:finished"))
attribute = test_node.get_attribute("outputs:finished")
db_value = database.outputs.finished
self.assertTrue(test_node.get_attribute_exists("outputs:loopBody"))
attribute = test_node.get_attribute("outputs:loopBody")
db_value = database.outputs.loopBody
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnMultisequence.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnMultisequenceDatabase import OgnMultisequenceDatabase
test_file_name = "OgnMultisequenceTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_Multisequence")
database = OgnMultisequenceDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("outputs:output0"))
attribute = test_node.get_attribute("outputs:output0")
db_value = database.outputs.output0
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnRationalTimeSyncGate.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnRationalTimeSyncGateDatabase import OgnRationalTimeSyncGateDatabase
test_file_name = "OgnRationalTimeSyncGateTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_RationalTimeSyncGate")
database = OgnRationalTimeSyncGateDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:rationalTimeDenominator"))
attribute = test_node.get_attribute("inputs:rationalTimeDenominator")
db_value = database.inputs.rationalTimeDenominator
expected_value = 0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:rationalTimeNumerator"))
attribute = test_node.get_attribute("inputs:rationalTimeNumerator")
db_value = database.inputs.rationalTimeNumerator
expected_value = 0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
self.assertTrue(test_node.get_attribute_exists("outputs:rationalTimeDenominator"))
attribute = test_node.get_attribute("outputs:rationalTimeDenominator")
db_value = database.outputs.rationalTimeDenominator
self.assertTrue(test_node.get_attribute_exists("outputs:rationalTimeNumerator"))
attribute = test_node.get_attribute("outputs:rationalTimeNumerator")
db_value = database.outputs.rationalTimeNumerator
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnClosing.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnClosingDatabase import OgnOnClosingDatabase
test_file_name = "OgnOnClosingTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnClosing")
database = OgnOnClosingDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnMouseInput.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnMouseInputDatabase import OgnOnMouseInputDatabase
test_file_name = "OgnOnMouseInputTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnMouseInput")
database = OgnOnMouseInputDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:mouseElement"))
attribute = test_node.get_attribute("inputs:mouseElement")
db_value = database.inputs.mouseElement
expected_value = "Left Button"
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:onlyPlayback"))
attribute = test_node.get_attribute("inputs:onlyPlayback")
db_value = database.inputs.onlyPlayback
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:isPressed"))
attribute = test_node.get_attribute("outputs:isPressed")
db_value = database.outputs.isPressed
self.assertTrue(test_node.get_attribute_exists("outputs:pressed"))
attribute = test_node.get_attribute("outputs:pressed")
db_value = database.outputs.pressed
self.assertTrue(test_node.get_attribute_exists("outputs:released"))
attribute = test_node.get_attribute("outputs:released")
db_value = database.outputs.released
self.assertTrue(test_node.get_attribute_exists("outputs:value"))
attribute = test_node.get_attribute("outputs:value")
db_value = database.outputs.value
self.assertTrue(test_node.get_attribute_exists("outputs:valueChanged"))
attribute = test_node.get_attribute("outputs:valueChanged")
db_value = database.outputs.valueChanged
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnObjectChange.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnObjectChangeDatabase import OgnOnObjectChangeDatabase
test_file_name = "OgnOnObjectChangeTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnObjectChange")
database = OgnOnObjectChangeDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 4)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:onlyPlayback"))
attribute = test_node.get_attribute("inputs:onlyPlayback")
db_value = database.inputs.onlyPlayback
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:changed"))
attribute = test_node.get_attribute("outputs:changed")
db_value = database.outputs.changed
self.assertTrue(test_node.get_attribute_exists("outputs:propertyName"))
attribute = test_node.get_attribute("outputs:propertyName")
db_value = database.outputs.propertyName
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnSetPrimActive.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnSetPrimActiveDatabase import OgnSetPrimActiveDatabase
test_file_name = "OgnSetPrimActiveTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_SetPrimActive")
database = OgnSetPrimActiveDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:active"))
attribute = test_node.get_attribute("inputs:active")
db_value = database.inputs.active
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:prim"))
attribute = test_node.get_attribute("inputs:prim")
db_value = database.inputs.prim
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:primTarget"))
attribute = test_node.get_attribute("inputs:primTarget")
db_value = database.inputs.primTarget
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnMultigate.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnMultigateDatabase import OgnMultigateDatabase
test_file_name = "OgnMultigateTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_Multigate")
database = OgnMultigateDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("outputs:output0"))
attribute = test_node.get_attribute("outputs:output0")
db_value = database.outputs.output0
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnImpulseEvent.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
TEST_DATA = [
{
'outputs': [
['outputs:execOut', 0, False],
],
'state_set': [
['state:enableImpulse', False, False],
],
'state_get': [
['state:enableImpulse', False, False],
],
},
{
'inputs': [
['inputs:onlyPlayback', False, False],
],
'outputs': [
['outputs:execOut', 1, False],
],
'state_set': [
['state:enableImpulse', True, False],
],
'state_get': [
['state:enableImpulse', False, False],
],
},
]
async def test_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_action_OnImpulseEvent", "omni.graph.action.OnImpulseEvent", test_run, test_info)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.action.OnImpulseEvent User test case #{i+1}")
async def test_vectorized_generated(self):
test_info = _TestGraphAndNode()
controller = og.Controller()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_action_OnImpulseEvent","omni.graph.action.OnImpulseEvent", test_run, test_info, 16)
await controller.evaluate(test_info.graph)
_test_verify_scene(self, controller, test_run, test_info, f"omni.graph.action.OnImpulseEvent User test case #{i+1}", 16)
async def test_thread_safety(self):
import omni.kit
# Generate multiple instances of the test setup to run them concurrently
instance_setup = dict()
for n in range(24):
instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode()
for i, test_run in enumerate(self.TEST_DATA):
await _test_clear_scene(self, test_run)
for (key, test_info) in instance_setup.items():
test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_action_OnImpulseEvent", "omni.graph.action.OnImpulseEvent", test_run, test_info)
self.assertEqual(len(og.get_all_graphs()), 24)
# We want to evaluate all graphs concurrently. Kick them all.
# Evaluate multiple times to skip 2 serial frames and increase chances for a race condition.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
for (key, test_instance) in instance_setup.items():
_test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.action.OnImpulseEvent User test case #{i+1}, instance{key}")
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnImpulseEventDatabase import OgnOnImpulseEventDatabase
test_file_name = "OgnOnImpulseEventTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnImpulseEvent")
database = OgnOnImpulseEventDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 2)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:onlyPlayback"))
attribute = test_node.get_attribute("inputs:onlyPlayback")
db_value = database.inputs.onlyPlayback
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
self.assertTrue(test_node.get_attribute_exists("state:enableImpulse"))
attribute = test_node.get_attribute("state:enableImpulse")
db_value = database.state.enableImpulse
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnFlipFlop.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
import os
class TestOgn(ogts.OmniGraphTestCase):
async def test_generated(self):
test_data = [{'outputs': [['outputs:a', 0, False], ['outputs:b', 1, False], ['outputs:isA', False, False]]}]
test_node = None
test_graph = None
for i, test_run in enumerate(test_data):
inputs = test_run.get('inputs', [])
outputs = test_run.get('outputs', [])
state_set = test_run.get('state_set', [])
state_get = test_run.get('state_get', [])
setup = test_run.get('setup', None)
if setup is None or setup:
await omni.usd.get_context().new_stage_async()
test_graph = None
elif not setup:
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test")
if setup:
(test_graph, test_nodes, _, _) = og.Controller.edit("/TestGraph", setup)
self.assertTrue(test_nodes)
test_node = test_nodes[0]
elif setup is None:
if test_graph is None:
test_graph = og.Controller.create_graph("/TestGraph")
self.assertTrue(test_graph is not None and test_graph.is_valid())
test_node = og.Controller.create_node(
("TestNode_omni_graph_action_FlipFlop", test_graph), "omni.graph.action.FlipFlop"
)
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test graph invalid")
self.assertTrue(test_node is not None and test_node.is_valid(), "Test node invalid")
await og.Controller.evaluate(test_graph)
values_to_set = inputs + state_set
if values_to_set:
for attribute_name, attribute_value, _ in inputs + state_set:
og.Controller((attribute_name, test_node)).set(attribute_value)
await og.Controller.evaluate(test_graph)
for attribute_name, expected_value, _ in outputs + state_get:
attribute = og.Controller.attribute(attribute_name, test_node)
actual_output = og.Controller.get(attribute)
expected_type = None
if isinstance(expected_value, dict):
expected_type = expected_value["type"]
expected_value = expected_value["value"]
ogts.verify_values(expected_value, actual_output, f"omni.graph.action.FlipFlop User test case #{i+1}: {attribute_name} attribute value error")
if expected_type:
tp = og.AttributeType.type_from_ogn_type_name(expected_type)
actual_type = attribute.get_resolved_type()
if tp != actual_type:
raise ValueError(f"omni.graph.action.FlipFlop User tests - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}")
async def test_data_access(self):
from omni.graph.action.ogn.OgnFlipFlopDatabase import OgnFlipFlopDatabase
test_file_name = "OgnFlipFlopTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_FlipFlop")
database = OgnFlipFlopDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("outputs:a"))
attribute = test_node.get_attribute("outputs:a")
db_value = database.outputs.a
self.assertTrue(test_node.get_attribute_exists("outputs:b"))
attribute = test_node.get_attribute("outputs:b")
db_value = database.outputs.b
self.assertTrue(test_node.get_attribute_exists("outputs:isA"))
attribute = test_node.get_attribute("outputs:isA")
db_value = database.outputs.isA
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnce.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnceDatabase import OgnOnceDatabase
test_file_name = "OgnOnceTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_Once")
database = OgnOnceDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:reset"))
attribute = test_node.get_attribute("inputs:reset")
db_value = database.inputs.reset
self.assertTrue(test_node.get_attribute_exists("outputs:after"))
attribute = test_node.get_attribute("outputs:after")
db_value = database.outputs.after
self.assertTrue(test_node.get_attribute_exists("outputs:once"))
attribute = test_node.get_attribute("outputs:once")
db_value = database.outputs.once
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnSequence.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnSequenceDatabase import OgnSequenceDatabase
test_file_name = "OgnSequenceTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_Sequence")
database = OgnSequenceDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("outputs:a"))
attribute = test_node.get_attribute("outputs:a")
db_value = database.outputs.a
self.assertTrue(test_node.get_attribute_exists("outputs:b"))
attribute = test_node.get_attribute("outputs:b")
db_value = database.outputs.b
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnLoaded.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnLoadedDatabase import OgnOnLoadedDatabase
test_file_name = "OgnOnLoadedTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnLoaded")
database = OgnOnLoadedDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnSendCustomEvent.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnSendCustomEventDatabase import OgnSendCustomEventDatabase
test_file_name = "OgnSendCustomEventTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_SendCustomEvent")
database = OgnSendCustomEventDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:eventName"))
attribute = test_node.get_attribute("inputs:eventName")
db_value = database.inputs.eventName
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:path"))
attribute = test_node.get_attribute("inputs:path")
db_value = database.inputs.path
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnKeyboardInput.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnKeyboardInputDatabase import OgnOnKeyboardInputDatabase
test_file_name = "OgnOnKeyboardInputTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnKeyboardInput")
database = OgnOnKeyboardInputDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 3)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:altIn"))
attribute = test_node.get_attribute("inputs:altIn")
db_value = database.inputs.altIn
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:ctrlIn"))
attribute = test_node.get_attribute("inputs:ctrlIn")
db_value = database.inputs.ctrlIn
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:keyIn"))
attribute = test_node.get_attribute("inputs:keyIn")
db_value = database.inputs.keyIn
expected_value = "A"
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:onlyPlayback"))
attribute = test_node.get_attribute("inputs:onlyPlayback")
db_value = database.inputs.onlyPlayback
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:shiftIn"))
attribute = test_node.get_attribute("inputs:shiftIn")
db_value = database.inputs.shiftIn
expected_value = False
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:isPressed"))
attribute = test_node.get_attribute("outputs:isPressed")
db_value = database.outputs.isPressed
self.assertTrue(test_node.get_attribute_exists("outputs:keyOut"))
attribute = test_node.get_attribute("outputs:keyOut")
db_value = database.outputs.keyOut
self.assertTrue(test_node.get_attribute_exists("outputs:pressed"))
attribute = test_node.get_attribute("outputs:pressed")
db_value = database.outputs.pressed
self.assertTrue(test_node.get_attribute_exists("outputs:released"))
attribute = test_node.get_attribute("outputs:released")
db_value = database.outputs.released
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnForLoop.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
import os
class TestOgn(ogts.OmniGraphTestCase):
async def test_generated(self):
test_data = [{'inputs': [['inputs:start', 1, False], ['inputs:stop', 0, False], ['inputs:step', 1, False]], 'outputs': [['outputs:loopBody', 0, False], ['outputs:finished', 1, False], ['outputs:value', 0, False], ['outputs:index', 0, False]], 'state_get': [['state:i', -1, False]]}, {'inputs': [['inputs:start', 1, False], ['inputs:stop', 3, False], ['inputs:step', 1, False]], 'outputs': [['outputs:loopBody', 2, False], ['outputs:finished', 0, False], ['outputs:value', 1, False], ['outputs:index', 0, False]], 'state_set': [['state:i', -1, False]], 'state_get': [['state:i', 1, False]]}, {'inputs': [['inputs:start', 1, False], ['inputs:stop', 3, False], ['inputs:step', 1, False]], 'outputs': [['outputs:loopBody', 2, False], ['outputs:finished', 0, False], ['outputs:value', 2, False], ['outputs:index', 1, False]], 'state_set': [['state:i', 1, False]], 'state_get': [['state:i', 2, False]]}, {'inputs': [['inputs:start', 1, False], ['inputs:stop', 3, False], ['inputs:step', 1, False]], 'outputs': [['outputs:loopBody', 0, False], ['outputs:finished', 1, False]], 'state_set': [['state:i', 2, False]], 'state_get': [['state:i', -1, False]]}, {'inputs': [['inputs:start', 3, False], ['inputs:stop', 1, False], ['inputs:step', -1, False]], 'outputs': [['outputs:loopBody', 2, False], ['outputs:finished', 0, False], ['outputs:value', 3, False], ['outputs:index', 0, False]], 'state_set': [['state:i', -1, False]], 'state_get': [['state:i', 1, False]]}, {'inputs': [['inputs:start', 3, False], ['inputs:stop', 1, False], ['inputs:step', -1, False]], 'outputs': [['outputs:loopBody', 2, False], ['outputs:finished', 0, False], ['outputs:value', 2, False], ['outputs:index', 1, False]], 'state_set': [['state:i', 1, False]], 'state_get': [['state:i', 2, False]]}, {'inputs': [['inputs:start', 3, False], ['inputs:stop', 1, False], ['inputs:step', -1, False]], 'outputs': [['outputs:loopBody', 0, False], ['outputs:finished', 1, False]], 'state_set': [['state:i', 2, False]], 'state_get': [['state:i', -1, False]]}, {'inputs': [['inputs:start', 1, False], ['inputs:stop', 3, False], ['inputs:step', 1, False], ['inputs:breakLoop', 1, False]], 'outputs': [['outputs:loopBody', 0, False], ['outputs:finished', 1, False]], 'state_set': [['state:i', 1, False]], 'state_get': [['state:i', -1, False]]}, {'inputs': [['inputs:start', 1000, False], ['inputs:stop', 999, False], ['inputs:step', 1, False]], 'outputs': [['outputs:loopBody', 0, False], ['outputs:finished', 1, False]], 'state_set': [['state:i', -1, False]], 'state_get': [['state:i', -1, False]]}, {'inputs': [['inputs:start', 1000, False], ['inputs:stop', 2000, False], ['inputs:step', 10, False]], 'outputs': [['outputs:loopBody', 2, False], ['outputs:finished', 0, False], ['outputs:value', 1020, False]], 'state_set': [['state:i', 2, False]], 'state_get': [['state:i', 3, False]]}]
test_node = None
test_graph = None
for i, test_run in enumerate(test_data):
inputs = test_run.get('inputs', [])
outputs = test_run.get('outputs', [])
state_set = test_run.get('state_set', [])
state_get = test_run.get('state_get', [])
setup = test_run.get('setup', None)
if setup is None or setup:
await omni.usd.get_context().new_stage_async()
test_graph = None
elif not setup:
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test")
if setup:
(test_graph, test_nodes, _, _) = og.Controller.edit("/TestGraph", setup)
self.assertTrue(test_nodes)
test_node = test_nodes[0]
elif setup is None:
if test_graph is None:
test_graph = og.Controller.create_graph("/TestGraph")
self.assertTrue(test_graph is not None and test_graph.is_valid())
test_node = og.Controller.create_node(
("TestNode_omni_graph_action_ForLoop", test_graph), "omni.graph.action.ForLoop"
)
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test graph invalid")
self.assertTrue(test_node is not None and test_node.is_valid(), "Test node invalid")
await og.Controller.evaluate(test_graph)
values_to_set = inputs + state_set
if values_to_set:
for attribute_name, attribute_value, _ in inputs + state_set:
og.Controller((attribute_name, test_node)).set(attribute_value)
await og.Controller.evaluate(test_graph)
for attribute_name, expected_value, _ in outputs + state_get:
attribute = og.Controller.attribute(attribute_name, test_node)
actual_output = og.Controller.get(attribute)
expected_type = None
if isinstance(expected_value, dict):
expected_type = expected_value["type"]
expected_value = expected_value["value"]
ogts.verify_values(expected_value, actual_output, f"omni.graph.action.ForLoop User test case #{i+1}: {attribute_name} attribute value error")
if expected_type:
tp = og.AttributeType.type_from_ogn_type_name(expected_type)
actual_type = attribute.get_resolved_type()
if tp != actual_type:
raise ValueError(f"omni.graph.action.ForLoop User tests - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}")
async def test_data_access(self):
from omni.graph.action.ogn.OgnForLoopDatabase import OgnForLoopDatabase
test_file_name = "OgnForLoopTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_ForLoop")
database = OgnForLoopDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:breakLoop"))
attribute = test_node.get_attribute("inputs:breakLoop")
db_value = database.inputs.breakLoop
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:start"))
attribute = test_node.get_attribute("inputs:start")
db_value = database.inputs.start
expected_value = 0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:step"))
attribute = test_node.get_attribute("inputs:step")
db_value = database.inputs.step
expected_value = 1
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:stop"))
attribute = test_node.get_attribute("inputs:stop")
db_value = database.inputs.stop
expected_value = 0
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:finished"))
attribute = test_node.get_attribute("outputs:finished")
db_value = database.outputs.finished
self.assertTrue(test_node.get_attribute_exists("outputs:index"))
attribute = test_node.get_attribute("outputs:index")
db_value = database.outputs.index
self.assertTrue(test_node.get_attribute_exists("outputs:loopBody"))
attribute = test_node.get_attribute("outputs:loopBody")
db_value = database.outputs.loopBody
self.assertTrue(test_node.get_attribute_exists("outputs:value"))
attribute = test_node.get_attribute("outputs:value")
db_value = database.outputs.value
self.assertTrue(test_node.get_attribute_exists("state:i"))
attribute = test_node.get_attribute("state:i")
db_value = database.state.i
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnMessageBusEvent.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnMessageBusEventDatabase import OgnOnMessageBusEventDatabase
test_file_name = "OgnOnMessageBusEventTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnMessageBusEvent")
database = OgnOnMessageBusEventDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:eventName"))
attribute = test_node.get_attribute("inputs:eventName")
db_value = database.inputs.eventName
expected_value = ""
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:onlyPlayback"))
attribute = test_node.get_attribute("inputs:onlyPlayback")
db_value = database.inputs.onlyPlayback
expected_value = True
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnOnPlaybackTick.py | import os
import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.action.ogn.OgnOnPlaybackTickDatabase import OgnOnPlaybackTickDatabase
test_file_name = "OgnOnPlaybackTickTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_OnPlaybackTick")
database = OgnOnPlaybackTickDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("outputs:deltaSeconds"))
attribute = test_node.get_attribute("outputs:deltaSeconds")
db_value = database.outputs.deltaSeconds
self.assertTrue(test_node.get_attribute_exists("outputs:frame"))
attribute = test_node.get_attribute("outputs:frame")
db_value = database.outputs.frame
self.assertTrue(test_node.get_attribute_exists("outputs:tick"))
attribute = test_node.get_attribute("outputs:tick")
db_value = database.outputs.tick
self.assertTrue(test_node.get_attribute_exists("outputs:time"))
attribute = test_node.get_attribute("outputs:time")
db_value = database.outputs.time
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnSwitchTokenTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnSwitchToken.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_SwitchToken" (
docs="""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 that is set to 'A'"""
)
{
token node:type = "omni.graph.action.SwitchToken"
int node:typeVersion = 1
# 2 attributes
custom uint inputs:execIn (
docs="""Input execution"""
)
custom token inputs:value = "" (
docs="""The value to switch on"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnGateTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnGate.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_Gate" (
docs="""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"""
)
{
token node:type = "omni.graph.action.Gate"
int node:typeVersion = 1
# 3 attributes
custom uint inputs:enter (
docs="""Incoming execution flow controlled by the gate"""
)
custom bool inputs:startClosed = false (
docs="""If true the gate will start in a closed state"""
)
custom uint inputs:toggle (
docs="""The gate is opened or closed"""
)
# 1 attribute
custom uint outputs:exit (
docs="""The enter pulses will be passed to this output if the gate is open"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnCustomEventTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnCustomEvent.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnCustomEvent" (
docs="""Event node which fires when the specified custom event is sent. This node is used in combination with SendCustomEvent"""
)
{
token node:type = "omni.graph.action.OnCustomEvent"
int node:typeVersion = 2
# 2 attributes
custom token inputs:eventName = "" (
docs="""The name of the custom event"""
)
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played."""
)
# 3 attributes
def Output "outputs_bundle" (
docs="""Bundle received with the event"""
)
{
}
custom uint outputs:execOut (
docs="""Executes when the event is received"""
)
custom token outputs:path (
docs="""The path associated with the received custom event"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnClosingTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnClosing.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnClosing" (
docs="""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 transition state"""
)
{
token node:type = "omni.graph.action.OnClosing"
int node:typeVersion = 1
# 1 attribute
custom uint outputs:execOut (
docs="""The execution output"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnTickTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnTick.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnTick" (
docs="""Executes an output execution pulse at a regular multiple of the refresh rate"""
)
{
token node:type = "omni.graph.action.OnTick"
int node:typeVersion = 1
# 2 attributes
custom uint inputs:framePeriod = 0 (
docs="""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."""
)
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played."""
)
# 7 attributes
custom double outputs:absoluteSimTime (
docs="""The accumulated total of elapsed times between rendered frames"""
)
custom double outputs:deltaSeconds (
docs="""The number of seconds elapsed since the last output pulse"""
)
custom double outputs:frame (
docs="""The global animation time in frames, equivalent to (time * fps), during playback"""
)
custom bool outputs:isPlaying (
docs="""True during global animation timeline playback"""
)
custom uint outputs:tick (
docs="""The execution output"""
)
custom double outputs:time (
docs="""The global animation time in seconds during playback"""
)
custom double outputs:timeSinceStart (
docs="""Elapsed time since the App started"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnSyncGateTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnSyncGate.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_SyncGate" (
docs="""This node triggers when all its input executions have triggered successively at the same synchronization value."""
)
{
token node:type = "omni.graph.action.SyncGate"
int node:typeVersion = 1
# 2 attributes
custom uint inputs:execIn (
docs="""The input execution"""
)
custom uint64 inputs:syncValue = 0 (
docs="""Value of the synchronization reference."""
)
# 2 attributes
custom uint outputs:execOut (
docs="""The output execution"""
)
custom uint64 outputs:syncValue (
docs="""Value of the synchronization reference."""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnLoadedTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnLoaded.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnLoaded" (
docs="""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."""
)
{
token node:type = "omni.graph.action.OnLoaded"
int node:typeVersion = 1
# 1 attribute
custom uint outputs:execOut (
docs="""Executes after graph creation or loading"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnFlipFlopTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnFlipFlop.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_FlipFlop" (
docs="""This node alternates activating its outputs, starting with A"""
)
{
token node:type = "omni.graph.action.FlipFlop"
int node:typeVersion = 1
# 1 attribute
custom uint inputs:execIn (
docs="""The input execution"""
)
# 3 attributes
custom uint outputs:a (
docs="""Executed on the 1st and odd numbered triggers"""
)
custom uint outputs:b (
docs="""Executed on the even number triggers"""
)
custom bool outputs:isA (
docs="""Set to true when a is activated"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnSendCustomEventTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnSendCustomEvent.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_SendCustomEvent" (
docs="""Sends a custom event, which will asynchronously trigger any OnCustomEvent nodes which are listening for the same eventName"""
)
{
token node:type = "omni.graph.action.SendCustomEvent"
int node:typeVersion = 1
# 4 attributes
custom rel inputs:bundle (
docs="""Bundle to be sent with the event"""
)
custom token inputs:eventName = "" (
docs="""The name of the custom event"""
)
custom uint inputs:execIn (
docs="""Input Execution"""
)
custom token inputs:path = "" (
docs="""The path associated with the event"""
)
# 1 attribute
custom uint outputs:execOut (
docs="""Output Execution"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnObjectChangeTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnObjectChange.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnObjectChange" (
docs="""Executes an output execution pulse when the watched USD Object changes"""
)
{
token node:type = "omni.graph.action.OnObjectChange"
int node:typeVersion = 3
# 3 attributes
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played."""
)
custom string inputs:path (
docs="""The path of object of interest (property or prim). If the prim input has a target, this is ignored"""
)
custom rel inputs:prim (
docs="""The prim of interest. If this has a target, the path input will be ignored"""
)
# 2 attributes
custom uint outputs:changed (
docs="""The execution output"""
)
custom token outputs:propertyName (
docs="""The name of the property that changed"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnImpulseEventTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnImpulseEvent.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnImpulseEvent" (
docs="""Triggers the output execution once when state is set"""
)
{
token node:type = "omni.graph.action.OnImpulseEvent"
int node:typeVersion = 2
# 1 attribute
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played."""
)
# 1 attribute
custom uint outputs:execOut (
docs="""The execution output"""
)
# 1 attribute
custom bool state:enableImpulse (
docs="""When true, execute output once and reset to false"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnGamepadInputTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnGamepadInput.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnGamepadInput" (
docs="""Event node which fires when a gamepad event occurs. This node only capture events on buttons, excluding triggers and sticks"""
)
{
token node:type = "omni.graph.action.OnGamepadInput"
int node:typeVersion = 1
# 3 attributes
custom token inputs:gamepadElementIn = "Face Button Bottom" (
docs="""The gamepad button to trigger the downstream execution."""
)
custom uint inputs:gamepadId = 0 (
docs="""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."""
)
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played."""
)
# 3 attributes
custom bool outputs:isPressed (
docs="""True if the gamepad button was pressed, False if it was released"""
)
custom uint outputs:pressed (
docs="""Executes when gamepad element was pressed"""
)
custom uint outputs:released (
docs="""Executes when gamepad element was released"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnSequenceTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnSequence.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_Sequence" (
docs="""Outputs an execution pulse along output A and B in sequence"""
)
{
token node:type = "omni.graph.action.Sequence"
int node:typeVersion = 1
# 1 attribute
custom uint inputs:execIn (
docs="""Input execution"""
)
# 2 attributes
custom uint outputs:a (
docs="""The first output path"""
)
custom uint outputs:b (
docs="""The second outputs path"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnMultigateTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnMultigate.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_Multigate" (
docs="""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..."""
)
{
token node:type = "omni.graph.action.Multigate"
int node:typeVersion = 1
# 1 attribute
custom uint inputs:execIn (
docs="""The input execution"""
)
# 1 attribute
custom uint outputs:output0 (
docs="""Output execution"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnKeyboardInputTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnKeyboardInput.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnKeyboardInput" (
docs="""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."""
)
{
token node:type = "omni.graph.action.OnKeyboardInput"
int node:typeVersion = 3
# 5 attributes
custom bool inputs:altIn = false (
docs="""When true, the node will check with a key modifier Alt"""
)
custom bool inputs:ctrlIn = false (
docs="""When true, the node will check with a key modifier Control"""
)
custom token inputs:keyIn = "A" (
docs="""The key to trigger the downstream execution """
)
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played."""
)
custom bool inputs:shiftIn = false (
docs="""When true, the node will check with a key modifier Shift"""
)
# 4 attributes
custom bool outputs:isPressed (
docs="""True if the key was pressed, False if it was released"""
)
custom token outputs:keyOut (
docs="""The key that was pressed or released"""
)
custom uint outputs:pressed (
docs="""Executes when key was pressed"""
)
custom uint outputs:released (
docs="""Executes when key was released"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnForEachTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnForEach.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_ForEach" (
docs="""Executes the a loop body once for each element in the input array. The finished output is executed after all iterations are complete"""
)
{
token node:type = "omni.graph.action.ForEach"
int node:typeVersion = 1
# 2 attributes
custom token inputs:arrayIn (
docs="""The array to loop over"""
)
custom uint inputs:execIn (
docs="""Input execution"""
)
# 4 attributes
custom int outputs:arrayIndex (
docs="""The current or last index visited"""
)
custom token outputs:element (
docs="""The current or last element of the array visited"""
)
custom uint outputs:finished (
docs="""Executed when the loop is finished"""
)
custom uint outputs:loopBody (
docs="""Executed for each element of the array"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnSetPrimActiveTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnSetPrimActive.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_SetPrimActive" (
docs="""Set a Prim active or not in the stage."""
)
{
token node:type = "omni.graph.action.SetPrimActive"
int node:typeVersion = 1
# 3 attributes
custom bool inputs:active = false (
docs="""Wheter to set the prim active or not"""
)
custom uint inputs:execIn (
docs="""Input execution"""
)
custom string inputs:prim = "" (
docs="""The prim to be (de)activated"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnMultisequenceTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnMultisequence.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_Multisequence" (
docs="""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."""
)
{
token node:type = "omni.graph.action.Multisequence"
int node:typeVersion = 1
# 1 attribute
custom uint inputs:execIn (
docs="""The input execution"""
)
# 1 attribute
custom uint outputs:output0 (
docs="""Output execution"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnDelayTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnDelay.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_Delay" (
docs="""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."""
)
{
token node:type = "omni.graph.action.Delay"
int node:typeVersion = 1
# 2 attributes
custom double inputs:duration = 0.0 (
docs="""The duration of the delay (Seconds)"""
)
custom uint inputs:execIn (
docs="""The input execution"""
)
# 1 attribute
custom uint outputs:finished (
docs="""Triggered when the delay is finished"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnPlaybackTickTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnPlaybackTick.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnPlaybackTick" (
docs="""Executes an output execution pulse during playback"""
)
{
token node:type = "omni.graph.action.OnPlaybackTick"
int node:typeVersion = 1
# 4 attributes
custom double outputs:deltaSeconds (
docs="""The number of seconds elapsed since the last update"""
)
custom double outputs:frame (
docs="""The global playback time in frames, equivalent to (time * fps)"""
)
custom uint outputs:tick (
docs="""The execution output"""
)
custom double outputs:time (
docs="""The global playback time in seconds"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnAddPrimRelationshipTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnAddPrimRelationship.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_AddPrimRelationship" (
docs="""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."""
)
{
token node:type = "omni.graph.action.AddPrimRelationship"
int node:typeVersion = 1
# 4 attributes
custom uint inputs:execIn (
docs="""The input execution port."""
)
custom token inputs:name = "" (
docs="""Name of the relationship property."""
)
custom string inputs:path = "" (
docs="""Path of the prim with the relationship property."""
)
custom string inputs:target = "" (
docs="""The target path to be added, which may be a prim, attribute or another relationship."""
)
# 1 attribute
custom bool outputs:isSuccessful (
docs="""Whether the node has successfully added the new target to the relationship."""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnForLoopTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnForLoop.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_ForLoop" (
docs="""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"""
)
{
token node:type = "omni.graph.action.ForLoop"
int node:typeVersion = 1
# 5 attributes
custom uint inputs:breakLoop (
docs="""Breaks out of the loop when the loop body traversal reaches it"""
)
custom uint inputs:execIn (
docs="""Input execution"""
)
custom int inputs:start = 0 (
docs="""The first value in the range"""
)
custom int inputs:step = 1 (
docs="""The step size of the range"""
)
custom int inputs:stop = 0 (
docs="""The limiting value of the range"""
)
# 4 attributes
custom uint outputs:finished (
docs="""Executed when the loop is finished"""
)
custom int outputs:index (
docs="""The current or last index within the range"""
)
custom uint outputs:loopBody (
docs="""Executed for each index in the range"""
)
custom int outputs:value (
docs="""The current or last value of the range"""
)
# 1 attribute
custom int state:i = -1 (
docs="""The next position in the range or -1 when loop is not active"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnBranchTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnBranch.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_Branch" (
docs="""Outputs an execution pulse along a branch based on a boolean condition"""
)
{
token node:type = "omni.graph.action.Branch"
int node:typeVersion = 1
# 2 attributes
custom bool inputs:condition = false (
docs="""The boolean condition which determines the output direction"""
)
custom uint inputs:execIn (
docs="""Input execution"""
)
# 2 attributes
custom uint outputs:execFalse (
docs="""The output path when condition is False"""
)
custom uint outputs:execTrue (
docs="""The output path when condition is True"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnStageEventTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnStageEvent.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnStageEvent" (
docs="""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.
OmniGraph Start Play: OmniGraph updates have started
OmniGraph Stop Play: OmniGraph updates have been stopped
Simulation Start Play: Simulation updates have started
Simulation Stop Play: Simulation updates have been stopped
Animation Start Play: Animation playback has started
Animation Stop Play: Animation playback has stopped"""
)
{
token node:type = "omni.graph.action.OnStageEvent"
int node:typeVersion = 2
# 2 attributes
custom token inputs:eventName = "" (
docs="""The event of interest"""
)
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played."""
)
# 1 attribute
custom uint outputs:execOut (
docs="""The execution output"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnCounterTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnCounter.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_Counter" (
docs="""This node counts the number of times it is computed since being reset"""
)
{
token node:type = "omni.graph.action.Counter"
int node:typeVersion = 1
# 2 attributes
custom uint inputs:execIn (
docs="""The input execution"""
)
custom uint inputs:reset (
docs="""Reset the internal counter"""
)
# 2 attributes
custom int outputs:count (
docs="""The count value"""
)
custom uint outputs:execOut (
docs="""The output execution"""
)
# 1 attribute
custom int state:count (
docs="""The counter state"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnMouseInputTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnMouseInput.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_OnMouseInput" (
docs="""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."""
)
{
token node:type = "omni.graph.action.OnMouseInput"
int node:typeVersion = 1
# 2 attributes
custom token inputs:mouseElement = "Left Button" (
docs="""The event to trigger the downstream execution """
)
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played."""
)
# 5 attributes
custom bool outputs:isPressed (
docs="""True if the mouse button was pressed, False if it was released or mouse element is not related to a button"""
)
custom uint outputs:pressed (
docs="""Executes when mouse button was pressed. Will not execute on move or scroll events"""
)
custom uint outputs:released (
docs="""Executes when mouse button was released. Will not execute on move or scroll events"""
)
custom float2 outputs:value (
docs="""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]"""
)
custom uint outputs:valueChanged (
docs="""Executes when user moves the cursor or scrolls the cursor. Will not execute on button events"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/usd/OgnOnceTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnce.ogn
Contains templates for node types found in that file."""
)
def OmniGraph "TestGraph"
{
token evaluator:type = "push"
int2 fileFormatVersion = (1, 3)
token flatCacheBacking = "Shared"
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "Template_omni_graph_action_Once" (
docs="""Controls flow of execution by passing input through differently on the first time"""
)
{
token node:type = "omni.graph.action.Once"
int node:typeVersion = 1
# 2 attributes
custom uint inputs:execIn (
docs="""Input execution"""
)
custom uint inputs:reset (
docs="""Resets the gate state"""
)
# 2 attributes
custom uint outputs:after (
docs="""Executes after the first time"""
)
custom uint outputs:once (
docs="""Executes the first time"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/_impl/extension.py | """Support required by the Carbonite extension loader"""
from contextlib import suppress
import omni.ext
from ..bindings._omni_graph_action import acquire_interface as _acquire_interface # noqa: PLE0402
from ..bindings._omni_graph_action import release_interface as _release_interface # noqa: PLE0402
class _PublicExtension(omni.ext.IExt):
"""Object that tracks the lifetime of the Python part of the extension loading"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__interface = None
with suppress(ImportError):
import omni.kit.app # noqa: PLW0621
app = omni.kit.app.get_app()
manager = app.get_extension_manager()
# This is a bit of a hack to make the template directory visible to the OmniGraph UI extension
# if it happens to already be enabled. The "hack" part is that this logic really should be in
# omni.graph.ui, but it would be much more complicated there, requiring management of extensions
# that both do and do not have dependencies on omni.graph.ui.
if manager.is_extension_enabled("omni.graph.ui"):
import omni.graph.ui # noqa: PLW0621
omni.graph.ui.ComputeNodeWidget.get_instance().add_template_path(__file__)
def on_startup(self):
"""Set up initial conditions for the Python part of the extension"""
self.__interface = _acquire_interface()
def on_shutdown(self):
"""Shutting down this part of the extension prepares it for hot reload"""
if self.__interface is not None:
_release_interface(self.__interface)
self.__interface = None
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/_impl/templates/template_omni.graph.action.Multisequence.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 pathlib import Path
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.window.property.templates import HORIZONTAL_SPACING
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.controller = og.Controller()
self.add_button = None
self.remove_button = None
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = self.controller.node(self.node_prim_path)
def _retrieve_existing_outputs(self):
# Retrieve all existing attributes of the form "outputs:output{num}"
# Also find the largest suffix among all such attributes
# Returned largest suffix = -1 if there are no such attributes
output_attribs = [attrib for attrib in self.node.get_attributes() if attrib.get_name()[:14] == "outputs:output"]
largest_suffix = -1
for attrib in output_attribs:
largest_suffix = max(largest_suffix, int(attrib.get_name()[14:]))
return (output_attribs, largest_suffix)
def _on_click_add(self):
(_, largest_suffix) = self._retrieve_existing_outputs()
self.controller.create_attribute(
self.node,
f"outputs:output{largest_suffix+1}",
og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
self.compute_node_widget.rebuild_window()
self.remove_button.enabled = True
def _on_click_remove(self):
(output_attribs, largest_suffix) = self._retrieve_existing_outputs()
if not output_attribs:
return
attrib_to_remove = self.node.get_attribute(f"outputs:output{largest_suffix}")
self.controller.remove_attribute(attrib_to_remove)
self.compute_node_widget.rebuild_window()
self.remove_button.enabled = len(output_attribs) > 1
def _controls_build_fn(self, *args):
(output_attribs, _) = self._retrieve_existing_outputs()
icons_path = Path(__file__).absolute().parent.parent.parent.parent.parent.parent.joinpath("icons")
with ui.HStack(height=0, spacing=HORIZONTAL_SPACING):
ui.Spacer()
self.add_button = ui.Button(
image_url=f"{icons_path.joinpath('add.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
clicked_fn=self._on_click_add,
tooltip_fn=lambda: ui.Label("Add New Output"),
)
self.remove_button = ui.Button(
image_url=f"{icons_path.joinpath('remove.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
enabled=(len(output_attribs) > 1),
clicked_fn=self._on_click_remove,
tooltip_fn=lambda: ui.Label("Remove Output"),
)
def apply(self, props):
# Called by compute_node_widget to apply UI when selection changes
def find_prop(name):
return next((p for p in props if p.prop_name == name), None)
frame = CustomLayoutFrame(hide_extra=True)
(output_attribs, _) = self._retrieve_existing_outputs()
with frame:
with CustomLayoutGroup("Outputs"):
for attrib in output_attribs:
prop = find_prop(attrib.get_name())
CustomLayoutProperty(prop.prop_name)
CustomLayoutProperty(None, None, build_fn=self._controls_build_fn)
return frame.apply(props)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/_impl/templates/template_omni.graph.action.Multigate.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.window.property.templates import HORIZONTAL_SPACING
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.controller = og.Controller()
self.add_button = None
self.remove_button = None
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = self.controller.node(self.node_prim_path)
def _retrieve_existing_outputs(self):
# Retrieve all existing attributes of the form "outputs:output{num}"
# Also find the largest suffix among all such attributes
# Returned largest suffix = -1 if there are no such attributes
output_attribs = [attrib for attrib in self.node.get_attributes() if attrib.get_name()[:14] == "outputs:output"]
largest_suffix = -1
for attrib in output_attribs:
largest_suffix = max(largest_suffix, int(attrib.get_name()[14:]))
return (output_attribs, largest_suffix)
def _on_click_add(self):
(_, largest_suffix) = self._retrieve_existing_outputs()
self.controller.create_attribute(
self.node,
f"outputs:output{largest_suffix+1}",
og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
self.compute_node_widget.rebuild_window()
self.remove_button.enabled = True
def _on_click_remove(self):
(output_attribs, largest_suffix) = self._retrieve_existing_outputs()
if not output_attribs:
return
attrib_to_remove = self.node.get_attribute(f"outputs:output{largest_suffix}")
self.controller.remove_attribute(attrib_to_remove)
self.compute_node_widget.rebuild_window()
self.remove_button.enabled = len(output_attribs) > 1
def _controls_build_fn(self, *args):
(output_attribs, _) = self._retrieve_existing_outputs()
icons_path = Path(__file__).absolute().parent.parent.parent.parent.parent.parent.joinpath("icons")
with ui.HStack(height=0, spacing=HORIZONTAL_SPACING):
ui.Spacer()
self.add_button = ui.Button(
image_url=f"{icons_path.joinpath('add.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
clicked_fn=self._on_click_add,
tooltip_fn=lambda: ui.Label("Add New Output"),
)
self.remove_button = ui.Button(
image_url=f"{icons_path.joinpath('remove.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
enabled=(len(output_attribs) > 1),
clicked_fn=self._on_click_remove,
tooltip_fn=lambda: ui.Label("Remove Output"),
)
def apply(self, props):
# Called by compute_node_widget to apply UI when selection changes
def find_prop(name):
try:
return next((p for p in props if p.prop_name == name))
except StopIteration:
return None
frame = CustomLayoutFrame(hide_extra=True)
(output_attribs, _) = self._retrieve_existing_outputs()
with frame:
with CustomLayoutGroup("Outputs"):
for attrib in output_attribs:
prop = find_prop(attrib.get_name())
CustomLayoutProperty(prop.prop_name)
CustomLayoutProperty(None, None, build_fn=self._controls_build_fn)
return frame.apply(props)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/_impl/templates/template_omni.graph.action.SwitchToken.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 pathlib import Path
from typing import List
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.window.property.templates import HORIZONTAL_SPACING
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.controller = og.Controller()
self.add_button: ui.Button = None
self.remove_button: ui.Button = None
self.node = self.controller.node(self.compute_node_widget._payload[-1])
def _get_input_attrib_names(self) -> List[str]:
"""Return the list of dynamic input attribs"""
all_attribs = self.node.get_attributes()
input_attrib_names = []
for attrib in all_attribs:
attrib_name = attrib.get_name()
name_prefix = attrib_name[:13]
if name_prefix == "inputs:branch":
input_attrib_names.append(attrib_name)
return input_attrib_names
def _get_max_suffix(self) -> int:
"""Return the maximum suffix of dynamic inputs or -1 if there are none"""
names = self._get_input_attrib_names()
if not names:
return -1
return max(int(name[13:]) for name in names)
def _on_click_add(self):
next_suffix = f"{self._get_max_suffix() + 1:02}"
new_attr = self.controller.create_attribute(
self.node,
f"inputs:branch{next_suffix}",
og.Type(og.BaseDataType.TOKEN, 1, 0, og.AttributeRole.NONE),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
)
new_attr.set_metadata(og.MetadataKeys.LITERAL_ONLY, "1")
self.controller.create_attribute(
self.node,
f"outputs:output{next_suffix}",
og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
self.compute_node_widget.rebuild_window()
self.remove_button.enabled = True
def _on_click_remove(self):
max_suffix = self._get_max_suffix()
if max_suffix < 0:
return
attrib_to_remove = self.node.get_attribute(f"outputs:output{max_suffix:02}")
self.controller.remove_attribute(attrib_to_remove)
attrib_to_remove = self.node.get_attribute(f"inputs:branch{max_suffix:02}")
self.controller.remove_attribute(attrib_to_remove)
self.compute_node_widget.rebuild_window()
self.remove_button.enabled = max_suffix > 0
def _controls_build_fn(self, *args):
max_suffix = self._get_max_suffix()
icons_path = Path(__file__).absolute().parent.parent.parent.parent.parent.parent.joinpath("icons")
with ui.HStack(height=0, spacing=HORIZONTAL_SPACING):
ui.Spacer()
self.add_button = ui.Button(
image_url=f"{icons_path.joinpath('add.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
clicked_fn=self._on_click_add,
tooltip_fn=lambda: ui.Label("Add New Branch"),
)
self.remove_button = ui.Button(
image_url=f"{icons_path.joinpath('remove.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
enabled=(max_suffix > 0),
clicked_fn=self._on_click_remove,
tooltip_fn=lambda: ui.Label("Remove Branch"),
)
def apply(self, props):
# Called by compute_node_widget to apply UI when selection changes
def find_prop(name):
return next((p for p in props if p.prop_name == name), None)
frame = CustomLayoutFrame(hide_extra=True)
names = self._get_input_attrib_names()
with frame:
with CustomLayoutGroup("Inputs"):
for name in names:
prop = find_prop(name)
CustomLayoutProperty(prop.prop_name)
CustomLayoutProperty(None, None, build_fn=self._controls_build_fn)
return frame.apply(props)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_nodes_02.py | """Action Graph Node Tests, Part 2"""
import random
from functools import partial
from typing import List
import carb
import carb.input
import numpy as np
import omni.client
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.tools.ogn as ogn
import omni.kit.app
import omni.kit.test
from carb.input import GamepadInput, KeyboardEventType, KeyboardInput
from omni.graph.core import ThreadsafetyTestUtils
# ======================================================================
class TestActionGraphNodes(ogts.OmniGraphTestCase):
"""Tests action graph node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
keys = og.Controller.Keys
E = og.ExecutionAttributeState.ENABLED
D = og.ExecutionAttributeState.DISABLED
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_ongamepadinput_node(self, test_instance_id: int = 0):
"""Test OnGamepadInput node"""
# Obtain an interface to a few gamepads and carb input provider.
input_provider = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, carb.input.acquire_input_provider()
)
gamepad_list = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
[
input_provider.create_gamepad("Gamepad 0", "0"),
input_provider.create_gamepad("Gamepad 1", "1"),
input_provider.create_gamepad("Gamepad 2", "2"),
],
)
# Connect the gamepads.
for gamepad in gamepad_list:
self.assertIsNotNone(gamepad)
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(input_provider.set_gamepad_connected, gamepad, True)
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_gamepad_input_node,), _, _) = og.Controller.edit(
graph_path, {self.keys.CREATE_NODES: ("OnGamepadInput", "omni.graph.action.OnGamepadInput")}
)
# Obtain necessary attributes.
in_onlyplayback_attr = on_gamepad_input_node.get_attribute("inputs:onlyPlayback")
in_gamepadid_attr = on_gamepad_input_node.get_attribute("inputs:gamepadId")
in_gamepad_element_attr = on_gamepad_input_node.get_attribute("inputs:gamepadElementIn")
out_pressed_attr = on_gamepad_input_node.get_attribute("outputs:pressed")
out_released_attr = on_gamepad_input_node.get_attribute("outputs:released")
out_ispressed_attr = on_gamepad_input_node.get_attribute("outputs:isPressed")
# Define a list of all possible gamepad inputs.
# FIXME: Note that the commented-out gamepad inputs produce errors in the OnGamepadInput's
# compute method because those specific inputs are not being considered. Maybe change to
# include these inputs and/or not spit out scary-looking error messages to users?
possible_gamepad_inputs = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
[
GamepadInput.A,
GamepadInput.B,
# GamepadInput.COUNT,
GamepadInput.DPAD_DOWN,
GamepadInput.DPAD_LEFT,
GamepadInput.DPAD_RIGHT,
GamepadInput.DPAD_UP,
GamepadInput.LEFT_SHOULDER,
GamepadInput.LEFT_STICK,
# GamepadInput.LEFT_STICK_DOWN,
# GamepadInput.LEFT_STICK_LEFT,
# GamepadInput.LEFT_STICK_RIGHT,
# GamepadInput.LEFT_STICK_UP,
# GamepadInput.LEFT_TRIGGER,
GamepadInput.MENU1,
GamepadInput.MENU2,
GamepadInput.RIGHT_SHOULDER,
GamepadInput.RIGHT_STICK,
# GamepadInput.RIGHT_STICK_DOWN,
# GamepadInput.RIGHT_STICK_LEFT,
# GamepadInput.RIGHT_STICK_RIGHT,
# GamepadInput.RIGHT_STICK_UP,
# GamepadInput.RIGHT_TRIGGER,
GamepadInput.X,
GamepadInput.Y,
],
)
# Define a dict of all valid inputs:gamepadElementIn tokens, along with
# their corresponding gamepad input. NOTE: The node's allowed token names
# are a bit different from the carb.input.GamepadInput values, might make
# sense to have them be the same?
allowed_gamepad_element_tokens = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
{
"Face Button Bottom": GamepadInput.A,
"Face Button Right": GamepadInput.B,
"Face Button Left": GamepadInput.X,
"Face Button Top": GamepadInput.Y,
"Left Shoulder": GamepadInput.LEFT_SHOULDER,
"Right Shoulder": GamepadInput.RIGHT_SHOULDER,
"Special Left": GamepadInput.MENU1,
"Special Right": GamepadInput.MENU2,
"Left Stick Button": GamepadInput.LEFT_STICK,
"Right Stick Button": GamepadInput.RIGHT_STICK,
"D-Pad Up": GamepadInput.DPAD_UP,
"D-Pad Right": GamepadInput.DPAD_RIGHT,
"D-Pad Down": GamepadInput.DPAD_DOWN,
"D-Pad Left": GamepadInput.DPAD_LEFT,
},
)
# Wrap main driver code in the following generator (in order to leverage
# the ThreadsafetyTestUtils.make_threading_test decorator). Note that for simplicity's sake the
# fake gamepad IDs correspond directly with their index in the gamepad_list.
def _test_ongamepadinput_node(quick_run: bool = True, num_inputs_to_test: int = 5):
_possible_gamepad_inputs = []
_allowed_gamepad_element_tokens = {}
# Codepath for accelerated test (won't take as long and still provide some code coverage).
if quick_run:
# Make sure that the input flags make sense.
if num_inputs_to_test < 1:
num_inputs_to_test = 1
elif num_inputs_to_test > 14:
num_inputs_to_test = 14
# Define two sets of random indices that'll determine the combination of inputs:gamepadElementIn
# tokens and emulated key inputs that we'll test for the current function call. Note that the
# inputs:gamepadElementIn tokens we choose and the emulated keys need not coincide, resulting
# in no output being generated by the OnGamepadInput node. Also note that because we want to
# use the same set of random indices in each test instance (so that all test graph instances
# run their tests/comparisons using the same combination of buttons/inputs), we add said indices
# (or more specifically an internal method that's used to create those indices, so that they're
# only created once for all test instances) to the overall threading cache.
def create_random_indices():
rand_indices_0 = set()
while len(rand_indices_0) < num_inputs_to_test:
rand_indices_0.add(random.randrange(len(possible_gamepad_inputs)))
rand_indices_1 = set()
while len(rand_indices_1) < num_inputs_to_test:
rand_indices_1.add(random.randrange(len(allowed_gamepad_element_tokens)))
return rand_indices_0, rand_indices_1
rand_indices_0, rand_indices_1 = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, create_random_indices()
)
# Convert the sets into lists so that their elements can be accessible by index.
rand_indices_0 = list(rand_indices_0)
rand_indices_1 = list(rand_indices_1)
# Create an abbreviated list of possible gamepad input elements.
for r_i in rand_indices_0:
_possible_gamepad_inputs.append(possible_gamepad_inputs[r_i])
# Create an abbreviated dict of allowed token-key input pairs.
temp_keys_list = list(allowed_gamepad_element_tokens)
temp_values_list = list(allowed_gamepad_element_tokens.values())
for r_i in rand_indices_1:
_allowed_gamepad_element_tokens[temp_keys_list[r_i]] = temp_values_list[r_i]
# Codepath for full test.
else:
_possible_gamepad_inputs = possible_gamepad_inputs
_allowed_gamepad_element_tokens = allowed_gamepad_element_tokens
# Set the gamepad id on each OnGamepadInput node. Note that multiple gamepad nodes are set to
# track the same gamepad to look for potential concurrency issues.
# for on_gamepad_input_node in on_gamepad_input_nodes:
in_gamepadid_attr.set(test_instance_id % len(gamepad_list)) # noqa S001
# Loop through each allowed gamepad element token, and set it on the OnGamepadInput nodes'
# corresponding input attributes.
for allowed_token, allowed_input in _allowed_gamepad_element_tokens.items():
in_gamepad_element_attr.set(allowed_token)
# Loop through each possible gamepad input, which we will emulate.
for emulated_input in _possible_gamepad_inputs:
# Loop through each possible input event type (0 == key is released, 1 == key is pressed)
for event_type in [1, 0]:
# Trigger each gamepad input.
input_provider.buffer_gamepad_event(
gamepad_list[test_instance_id % len(gamepad_list)], emulated_input, event_type # noqa S001
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# If the current emulated input matches the inputs:gamepadElementsIn attribute setting,
# check that the nodes reacted appropriately. Otherwise check that the nodes did not
# register the input.
if emulated_input == allowed_input:
if event_type == 1:
self.assertEqual(out_pressed_attr.get(), self.E)
self.assertEqual(out_released_attr.get(), self.D)
self.assertTrue(out_ispressed_attr.get())
elif event_type == 0:
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
else:
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertFalse(out_ispressed_attr.get())
# Test that the OnGamepadInput nodes works correctly when the onlyPlayback input is disabled.
in_onlyplayback_attr.set(False)
for _ in _test_ongamepadinput_node():
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# Test that the OnGamepadInput nodes works correctly when the onlyPlayback input is enabled.
in_onlyplayback_attr.set(True)
timeline = omni.timeline.get_timeline_interface()
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
timeline.play()
for _ in _test_ongamepadinput_node():
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
timeline.stop()
# Delete the gamepad node before destroying the gamepads themselves so that the nodes don't throw
# any warnings about having invalid gamepadIds.
og.Controller.delete_node(on_gamepad_input_node)
# Disconnect and destroy the gamepads.
for gamepad in gamepad_list:
ThreadsafetyTestUtils.single_evaluation_last_test_instance(
test_instance_id, partial(input_provider.set_gamepad_connected, gamepad, False)
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
ThreadsafetyTestUtils.single_evaluation_last_test_instance(
test_instance_id, partial(input_provider.destroy_gamepad, gamepad)
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# ----------------------------------------------------------------------
# The OnImpulseEvent node ALSO has a built-in test construct in its .ogn file located
# at ../../nodes/OgnOnImpulseEvent.ogn (relative to the source location of the currently-
# opened testing script).
@ThreadsafetyTestUtils.make_threading_test
def test_onimpulseevent_node(self, test_instance_id: int = 0):
"""Test OnImpulseEvent node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (_, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False)],
self.keys.CONNECT: (
"OnImpulse.outputs:execOut",
"Counter.inputs:execIn",
),
},
)
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
# After several updates, there should have been no compute calls.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(counter_controller.get(), 0)
# Change the OnImpulse node's state attribute. The node should now request compute.
og.Controller.edit(graph_path, {self.keys.SET_VALUES: (graph_path + "/OnImpulse.state:enableImpulse", True)})
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(counter_controller.get(), 1)
# More updates should not result in more computes.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(counter_controller.get(), 1)
# ----------------------------------------------------------------------
async def test_onkeyboardinput_node(self):
"""Test OnKeyboardInput node"""
app = omni.kit.app.get_app()
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, (on_keyboard_input_node,), _, _) = og.Controller.edit(
self.TEST_GRAPH_PATH, {self.keys.CREATE_NODES: ("OnKeyboardInput", "omni.graph.action.OnKeyboardInput")}
)
# Obtain necessary attributes.
in_keyin_attr = on_keyboard_input_node.get_attribute("inputs:keyIn")
in_playbackonly_attr = on_keyboard_input_node.get_attribute("inputs:onlyPlayback")
out_keyout_attr = on_keyboard_input_node.get_attribute("outputs:keyOut")
out_pressed_attr = on_keyboard_input_node.get_attribute("outputs:pressed")
out_released_attr = on_keyboard_input_node.get_attribute("outputs:released")
out_ispressed_attr = on_keyboard_input_node.get_attribute("outputs:isPressed")
# Obtain an interface to the keyboard and carb input provider.
keyboard = omni.appwindow.get_default_app_window().get_keyboard()
input_provider = carb.input.acquire_input_provider()
self.assertIsNotNone(keyboard)
# Define a list of all possible carb.input.KeyboardInput inputs. Note that not all possible
# keys are necessarily detectable by the OnKeyboardInput node (this list also includes the
# UNKNOWN key).
possible_key_inputs = [
KeyboardInput.A,
KeyboardInput.APOSTROPHE,
KeyboardInput.B,
KeyboardInput.BACKSLASH,
KeyboardInput.BACKSPACE,
KeyboardInput.C,
KeyboardInput.CAPS_LOCK,
KeyboardInput.COMMA,
KeyboardInput.D,
KeyboardInput.DEL,
KeyboardInput.DOWN,
KeyboardInput.E,
KeyboardInput.END,
KeyboardInput.ENTER,
KeyboardInput.EQUAL,
KeyboardInput.ESCAPE,
KeyboardInput.F,
KeyboardInput.F1,
KeyboardInput.F10,
KeyboardInput.F11,
KeyboardInput.F12,
KeyboardInput.F2,
KeyboardInput.F3,
KeyboardInput.F4,
KeyboardInput.F5,
KeyboardInput.F6,
KeyboardInput.F7,
KeyboardInput.F8,
KeyboardInput.F9,
KeyboardInput.G,
KeyboardInput.GRAVE_ACCENT,
KeyboardInput.H,
KeyboardInput.HOME,
KeyboardInput.I,
KeyboardInput.INSERT,
KeyboardInput.J,
KeyboardInput.K,
KeyboardInput.KEY_0,
KeyboardInput.KEY_1,
KeyboardInput.KEY_2,
KeyboardInput.KEY_3,
KeyboardInput.KEY_4,
KeyboardInput.KEY_5,
KeyboardInput.KEY_6,
KeyboardInput.KEY_7,
KeyboardInput.KEY_8,
KeyboardInput.KEY_9,
KeyboardInput.L,
KeyboardInput.LEFT,
KeyboardInput.LEFT_ALT,
KeyboardInput.LEFT_BRACKET,
KeyboardInput.LEFT_CONTROL,
KeyboardInput.LEFT_SHIFT,
KeyboardInput.LEFT_SUPER,
KeyboardInput.M,
KeyboardInput.MENU,
KeyboardInput.MINUS,
KeyboardInput.N,
KeyboardInput.NUMPAD_0,
KeyboardInput.NUMPAD_1,
KeyboardInput.NUMPAD_2,
KeyboardInput.NUMPAD_3,
KeyboardInput.NUMPAD_4,
KeyboardInput.NUMPAD_5,
KeyboardInput.NUMPAD_6,
KeyboardInput.NUMPAD_7,
KeyboardInput.NUMPAD_8,
KeyboardInput.NUMPAD_9,
KeyboardInput.NUMPAD_ADD,
KeyboardInput.NUMPAD_DEL,
KeyboardInput.NUMPAD_DIVIDE,
KeyboardInput.NUMPAD_ENTER,
KeyboardInput.NUMPAD_EQUAL,
KeyboardInput.NUMPAD_MULTIPLY,
KeyboardInput.NUMPAD_SUBTRACT,
KeyboardInput.NUM_LOCK,
KeyboardInput.O,
KeyboardInput.P,
KeyboardInput.PAGE_DOWN,
KeyboardInput.PAGE_UP,
KeyboardInput.PAUSE,
KeyboardInput.PERIOD,
KeyboardInput.PRINT_SCREEN,
KeyboardInput.Q,
KeyboardInput.R,
KeyboardInput.RIGHT,
KeyboardInput.RIGHT_ALT,
KeyboardInput.RIGHT_BRACKET,
KeyboardInput.RIGHT_CONTROL,
KeyboardInput.RIGHT_SHIFT,
KeyboardInput.RIGHT_SUPER,
KeyboardInput.S,
KeyboardInput.SCROLL_LOCK,
KeyboardInput.SEMICOLON,
KeyboardInput.SLASH,
KeyboardInput.SPACE,
KeyboardInput.T,
KeyboardInput.TAB,
KeyboardInput.U,
KeyboardInput.UNKNOWN,
KeyboardInput.UP,
KeyboardInput.V,
KeyboardInput.W,
KeyboardInput.X,
KeyboardInput.Y,
KeyboardInput.Z,
]
# Define a dictionary of token keys representing the possible inputs to the OnKeyboardInput node's
# "keyIn" attribute, and values representing the corresponding carb.input.KeyboardInput. Note that
# not all possible keys are necessarily allowed for detection by the OnKeyboardInput node (e.g.
# "Unknown")
allowed_token_key_inputs = {
"A": KeyboardInput.A,
"B": KeyboardInput.B,
"C": KeyboardInput.C,
"D": KeyboardInput.D,
"E": KeyboardInput.E,
"F": KeyboardInput.F,
"G": KeyboardInput.G,
"H": KeyboardInput.H,
"I": KeyboardInput.I,
"J": KeyboardInput.J,
"K": KeyboardInput.K,
"L": KeyboardInput.L,
"M": KeyboardInput.M,
"N": KeyboardInput.N,
"O": KeyboardInput.O,
"P": KeyboardInput.P,
"Q": KeyboardInput.Q,
"R": KeyboardInput.R,
"S": KeyboardInput.S,
"T": KeyboardInput.T,
"U": KeyboardInput.U,
"V": KeyboardInput.V,
"W": KeyboardInput.W,
"X": KeyboardInput.X,
"Y": KeyboardInput.Y,
"Z": KeyboardInput.Z,
"Apostrophe": KeyboardInput.APOSTROPHE,
"Backslash": KeyboardInput.BACKSLASH,
"Backspace": KeyboardInput.BACKSPACE,
"CapsLock": KeyboardInput.CAPS_LOCK,
"Comma": KeyboardInput.COMMA,
"Del": KeyboardInput.DEL,
"Down": KeyboardInput.DOWN,
"End": KeyboardInput.END,
"Enter": KeyboardInput.ENTER,
"Equal": KeyboardInput.EQUAL,
"Escape": KeyboardInput.ESCAPE,
"F1": KeyboardInput.F1,
"F10": KeyboardInput.F10,
"F11": KeyboardInput.F11,
"F12": KeyboardInput.F12,
"F2": KeyboardInput.F2,
"F3": KeyboardInput.F3,
"F4": KeyboardInput.F4,
"F5": KeyboardInput.F5,
"F6": KeyboardInput.F6,
"F7": KeyboardInput.F7,
"F8": KeyboardInput.F8,
"F9": KeyboardInput.F9,
"GraveAccent": KeyboardInput.GRAVE_ACCENT,
"Home": KeyboardInput.HOME,
"Insert": KeyboardInput.INSERT,
"Key0": KeyboardInput.KEY_0,
"Key1": KeyboardInput.KEY_1,
"Key2": KeyboardInput.KEY_2,
"Key3": KeyboardInput.KEY_3,
"Key4": KeyboardInput.KEY_4,
"Key5": KeyboardInput.KEY_5,
"Key6": KeyboardInput.KEY_6,
"Key7": KeyboardInput.KEY_7,
"Key8": KeyboardInput.KEY_8,
"Key9": KeyboardInput.KEY_9,
"Left": KeyboardInput.LEFT,
"LeftAlt": KeyboardInput.LEFT_ALT,
"LeftBracket": KeyboardInput.LEFT_BRACKET,
"LeftControl": KeyboardInput.LEFT_CONTROL,
"LeftShift": KeyboardInput.LEFT_SHIFT,
"LeftSuper": KeyboardInput.LEFT_SUPER,
"Menu": KeyboardInput.MENU,
"Minus": KeyboardInput.MINUS,
"NumLock": KeyboardInput.NUM_LOCK,
"Numpad0": KeyboardInput.NUMPAD_0,
"Numpad1": KeyboardInput.NUMPAD_1,
"Numpad2": KeyboardInput.NUMPAD_2,
"Numpad3": KeyboardInput.NUMPAD_3,
"Numpad4": KeyboardInput.NUMPAD_4,
"Numpad5": KeyboardInput.NUMPAD_5,
"Numpad6": KeyboardInput.NUMPAD_6,
"Numpad7": KeyboardInput.NUMPAD_7,
"Numpad8": KeyboardInput.NUMPAD_8,
"Numpad9": KeyboardInput.NUMPAD_9,
"NumpadAdd": KeyboardInput.NUMPAD_ADD,
"NumpadDel": KeyboardInput.NUMPAD_DEL,
"NumpadDivide": KeyboardInput.NUMPAD_DIVIDE,
"NumpadEnter": KeyboardInput.NUMPAD_ENTER,
"NumpadEqual": KeyboardInput.NUMPAD_EQUAL,
"NumpadMultiply": KeyboardInput.NUMPAD_MULTIPLY,
"NumpadSubtract": KeyboardInput.NUMPAD_SUBTRACT,
"PageDown": KeyboardInput.PAGE_DOWN,
"PageUp": KeyboardInput.PAGE_UP,
"Pause": KeyboardInput.PAUSE,
"Period": KeyboardInput.PERIOD,
"PrintScreen": KeyboardInput.PRINT_SCREEN,
"Right": KeyboardInput.RIGHT,
"RightAlt": KeyboardInput.RIGHT_ALT,
"RightBracket": KeyboardInput.RIGHT_BRACKET,
"RightControl": KeyboardInput.RIGHT_CONTROL,
"RightShift": KeyboardInput.RIGHT_SHIFT,
"RightSuper": KeyboardInput.RIGHT_SUPER,
"ScrollLock": KeyboardInput.SCROLL_LOCK,
"Semicolon": KeyboardInput.SEMICOLON,
"Slash": KeyboardInput.SLASH,
"Space": KeyboardInput.SPACE,
"Tab": KeyboardInput.TAB,
"Up": KeyboardInput.UP,
}
# Define a list of all possible keyboard event types (for convenience).
# We won't consider KEY_REPEAT and CHAR events here.
keyboard_event_types = [
KeyboardEventType.KEY_PRESS,
KeyboardEventType.KEY_RELEASE,
]
# Create a list of all possible keyboard modifier combinations. Don't need permutations
# since bitwise OR operator is commutative and associative.
modifier_combinations = [
0, # 0
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT, # 1
carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, # 2
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, # 3
carb.input.KEYBOARD_MODIFIER_FLAG_ALT, # 4
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_ALT, # 5
carb.input.KEYBOARD_MODIFIER_FLAG_ALT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, # 6
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT
| carb.input.KEYBOARD_MODIFIER_FLAG_ALT
| carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, # 7
]
# Create a list of tuples of lists of tuples and indices of all possible input key modifier
# settings on the OnKeyboardInput node.
node_input_modifier_attribute_combinations = [
([("inputs:shiftIn", False), ("inputs:altIn", False), ("inputs:ctrlIn", False)], 0),
([("inputs:shiftIn", True), ("inputs:altIn", False), ("inputs:ctrlIn", False)], 1),
([("inputs:shiftIn", False), ("inputs:altIn", False), ("inputs:ctrlIn", True)], 2),
([("inputs:shiftIn", True), ("inputs:altIn", False), ("inputs:ctrlIn", True)], 3),
([("inputs:shiftIn", False), ("inputs:altIn", True), ("inputs:ctrlIn", False)], 4),
([("inputs:shiftIn", True), ("inputs:altIn", True), ("inputs:ctrlIn", False)], 5),
([("inputs:shiftIn", False), ("inputs:altIn", True), ("inputs:ctrlIn", True)], 6),
([("inputs:shiftIn", True), ("inputs:altIn", True), ("inputs:ctrlIn", True)], 7),
]
# NOTE: Although the below test confirms that the OnKeyboardInput node works for all
# input combinations, it takes a while to run and times out the test (which is typically
# set to automatically crash after 300s). To account for this, each time we run the test
# a random subset of allowed input tokens and input keys are chosen with which
# we perform the test; this cuts down on computation time and still provides some
# decent code coverage.
# Wrap main test driver code in the following method. Note that in addition to testing
# whether specific buttons activate their corresponding code path, we also check that
# no other buttons can activate code paths they don't belong to. Check for all possible
# key + special modifier press/release permutations.
async def _test_onkeyboardinput_node(
quick_run: bool = True, num_keys_to_test: int = 10, num_modifiers_to_test: int = 1
):
_possible_key_inputs = []
_allowed_token_key_inputs = {}
_modifier_combinations = []
_node_input_modifier_attribute_combinations = []
# Codepath for accelerated test (won't time out and still provide some code coverage).
if quick_run:
# Make sure that the input flags make sense.
if num_keys_to_test < 1:
num_keys_to_test = 1
elif num_keys_to_test > 105:
num_keys_to_test = 105
if num_modifiers_to_test < 1:
num_modifiers_to_test = 1
elif num_modifiers_to_test > 8:
num_modifiers_to_test = 8
# Define three sets of random indices that'll determine the combination of inputs:keyIn
# tokens, emulated key inputs, and modifier values that we'll test for the current function call.
# Note that the inputs:keyIn tokens we choose and the emulated keys need not coincide, resulting
# in no output being generated by the OnKeyboardInput node.
rand_indices_0 = set()
while len(rand_indices_0) < num_keys_to_test:
rand_indices_0.add(random.randrange(len(possible_key_inputs)))
rand_indices_1 = set()
while len(rand_indices_1) < num_keys_to_test:
rand_indices_1.add(random.randrange(len(allowed_token_key_inputs)))
rand_indices_2 = set()
while len(rand_indices_2) < num_modifiers_to_test:
rand_indices_2.add(random.randrange(len(modifier_combinations)))
# Convert the sets into lists so that their elements can be accessible by index.
rand_indices_0 = list(rand_indices_0)
rand_indices_1 = list(rand_indices_1)
rand_indices_2 = list(rand_indices_2)
# Create an abbreviated list of possible key inputs.
for i in range(0, num_keys_to_test):
_possible_key_inputs.append(possible_key_inputs[rand_indices_0[i]])
# Create an abbreviated dict of allowed token-key input pairs.
temp_keys_list = list(allowed_token_key_inputs)
temp_values_list = list(allowed_token_key_inputs.values())
for i in range(0, num_keys_to_test):
_allowed_token_key_inputs[temp_keys_list[rand_indices_1[i]]] = temp_values_list[rand_indices_1[i]]
# Create abbreviated lists of modifier values and corresponing input attribute-value pairs.
for rand_idx in rand_indices_2:
_modifier_combinations.append(modifier_combinations[rand_idx])
_node_input_modifier_attribute_combinations.append(
node_input_modifier_attribute_combinations[rand_idx]
)
# Codepath for full test.
else:
_possible_key_inputs = possible_key_inputs
_allowed_token_key_inputs = allowed_token_key_inputs
_modifier_combinations = modifier_combinations
_node_input_modifier_attribute_combinations = node_input_modifier_attribute_combinations
# Loop through each possible inputs:keyIn token, and the set the inputs:keyIn attribute on the
# OnKeyboardInput node.
for token, _ in _allowed_token_key_inputs.items(): # noqa PLR1702
in_keyin_attr.set(token)
# Loop through each possible modification combination, and set the corresponding input attributes
# on the OnKeyboardInput node. Also store an index to represent the current modification state.
for node_input_modifier_attribute_tuple in _node_input_modifier_attribute_combinations:
node_input_modifier_attribute_list_in_tuple = node_input_modifier_attribute_tuple[0]
for input_attr_value_modifier_pair in node_input_modifier_attribute_list_in_tuple:
og.Controller.set(
og.Controller.attribute(input_attr_value_modifier_pair[0], on_keyboard_input_node),
input_attr_value_modifier_pair[1],
)
# Loop through each possible input key.
for key in _possible_key_inputs:
# Loop through all possible modification combinations.
for modifier in _modifier_combinations:
# Loop through each possible keyboard event type.
for event_type in keyboard_event_types:
# Trigger the current keyboard event.
input_provider.buffer_keyboard_key_event(keyboard, event_type, key, modifier)
await app.next_update_async()
# If the currently-pressed key matches the currently-set inputs:keyIn token's
# corresponding KeyboardInput + modifiers, check that the OnKeyboardInput node gets
# correctly activated.
if (
_allowed_token_key_inputs[token] == key # noqa PLR1733
and node_input_modifier_attribute_tuple[1] == modifier
):
# If the key has been pressed, check for the corresponding expected conditions.
if event_type == KeyboardEventType.KEY_PRESS:
self.assertEqual(out_keyout_attr.get(), token)
self.assertEqual(out_pressed_attr.get(), self.E)
self.assertEqual(out_released_attr.get(), self.D)
self.assertTrue(out_ispressed_attr.get())
# If the key has been released, check for the corresponding expected conditions.
elif event_type == KeyboardEventType.KEY_RELEASE:
self.assertEqual(out_keyout_attr.get(), token)
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
else:
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertFalse(out_ispressed_attr.get())
# Test that the OnKeyboardInput node works correctly when its onlyPlayback input is disabled.
in_playbackonly_attr.set(False)
await _test_onkeyboardinput_node()
# Test that the OnKeyboardInput node works correctly when its onlyPlayback input is enabled.
in_playbackonly_attr.set(True)
timeline = omni.timeline.get_timeline_interface()
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
timeline.play()
await _test_onkeyboardinput_node()
timeline.stop()
# ----------------------------------------------------------------------
# NOTE: Even though the OnLoaded node is threadsafe (its compute method is very simple),
# we don't adapt the below test to check for thread-safety conditions because it relies
# on other nodes (omni.graph.action.SendCustomEvent) which are NOT threadsafe.
async def test_onloaded_node(self):
"""Test OnLoaded node"""
def registered_event_name(event_name):
"""Returns the internal name used for the given custom event name"""
name = "omni.graph.action." + event_name
return carb.events.type_from_string(name)
events = []
def on_event(event):
events.append(event.payload["!path"])
reg_event_name = registered_event_name("foo")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_push_by_type(reg_event_name, on_event)
self.assertIsNotNone(sub)
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("OnLoaded", "omni.graph.action.OnLoaded"),
("Send1", "omni.graph.action.SendCustomEvent"),
("Send2", "omni.graph.action.SendCustomEvent"),
],
self.keys.CONNECT: [
("OnLoaded.outputs:execOut", "Send1.inputs:execIn"),
("OnTick.outputs:tick", "Send2.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Send1.inputs:eventName", "foo"),
("Send2.inputs:eventName", "foo"),
("Send1.inputs:path", "Loaded"),
("Send2.inputs:path", "Tick"),
],
},
)
# Evaluate once so that graph is in steady state.
await og.Controller.evaluate()
# Verify Loaded came before OnTick.
self.assertListEqual(events, ["Loaded", "Tick"])
# ----------------------------------------------------------------------
async def test_onmessagebusevent_node(self):
"""Test OnMessageBusEvent node"""
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, (on_custom_event, _), _, _,) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnCustomEvent", "omni.graph.action.OnMessageBusEvent"),
("Counter1", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnCustomEvent.outputs:execOut", "Counter1.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnCustomEvent.inputs:onlyPlayback", False),
("OnCustomEvent.inputs:eventName", "testEvent"),
],
},
)
# One compute for the first-time subscribe.
await omni.kit.app.get_app().next_update_async()
def get_all_supported_types() -> List[str]:
"""Helper to get all the types supported by the node"""
types = []
for attr_type in ogn.supported_attribute_type_names():
if (
attr_type in ("any", "transform", "bundle", "target", "execution")
or (attr_type[:9] == "transform")
or attr_type.startswith("objectId")
or attr_type.startswith("frame")
):
continue
types.append(attr_type)
return types
def assert_are_equal(expected_val, val):
"""Helper to assert two values are equal, sequence container type need not match"""
if isinstance(expected_val, (list, tuple, np.ndarray)):
for left, right in zip(expected_val, val):
return assert_are_equal(left, right)
if isinstance(val, np.ndarray):
self.assertListEqual(expected_val, list(val))
else:
self.assertEqual(expected_val, val)
return True
msg = carb.events.type_from_string("testEvent")
payload = {}
expected_vals = []
for sup_type in sorted(get_all_supported_types()):
payload = {}
name = sup_type.replace("[", "_").replace("]", "_")
manager = ogn.get_attribute_manager_type(sup_type)
# Create a dynamic output attribute on the node which matches the type of the test payload.
og_type = og.AttributeType.type_from_ogn_type_name(sup_type)
attrib = og.Controller.create_attribute(
on_custom_event, f"outputs:{name}", sup_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT
)
# Get a sample value in python format (nested tuples/lists).
sample_val = manager.sample_values()[0]
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)
)
payload_val = sample_val
# Convert the sample value into numpy format for use with OG API.
if is_array:
if is_matrix:
payload_val = np.array(sample_val).flatten().flatten().tolist()
elif is_tuple:
payload_val = np.array(sample_val).flatten().tolist()
elif is_matrix:
payload_val = np.array(sample_val).flatten().tolist()
payload[name] = payload_val
expected_vals.append((attrib, sample_val))
# Push the message to kit message bus.
omni.kit.app.get_app().get_message_bus_event_stream().push(msg, payload=payload)
# Wait for one kit update to allow the event-push mechanism to trigger the node callback.
await omni.kit.app.get_app().next_update_async()
# Verify the value.
out_val = og.Controller.get(attrib)
try:
assert_are_equal(out_val, out_val)
except AssertionError as exc:
raise AssertionError(f"{sample_val} != {out_val}") from exc
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_evaluation2.py | """Action Graph Evaluation Tests Part 2"""
import json
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.usd
# ======================================================================
class TestActionGraphEvaluation2(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_retrigger_latent(self):
"""Test that latent nodes can be re-triggered"""
want_debug = False
e_state = og.ExecutionAttributeState
tick_count = 0
boop_count = 0
exec_in_latent_count = 0
max_ticks = 20
class CancelTickerPy:
"""Helper node type which does latent ticking and can be canceled, and has an independent counter "boop" """
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
nonlocal tick_count
nonlocal boop_count
nonlocal exec_in_latent_count
exec_in = node.get_attribute("inputs:execIn")
exec_in_val = og.Controller.get(exec_in)
cancel = node.get_attribute("inputs:cancel")
cancel_val = og.Controller.get(cancel)
boop = node.get_attribute("inputs:boop")
boop_val = og.Controller.get(boop)
want_debug and print(
f"### {tick_count} execIn={exec_in_val} cancel={cancel_val} boop={boop_val}"
) # noqa: expression-not-assigned
if cancel_val == e_state.ENABLED:
# Finish latent by cancel
og.Controller.set(node.get_attribute("outputs:canceled"), e_state.LATENT_FINISH)
self.assertEqual(exec_in_val, e_state.DISABLED)
self.assertEqual(boop_val, e_state.DISABLED)
tick_count = 0
return True
if exec_in_val == e_state.ENABLED:
self.assertEqual(cancel_val, e_state.DISABLED)
self.assertEqual(boop_val, e_state.DISABLED)
if tick_count > 0:
# execIn triggered while in latent - should not be possible
exec_in_latent_count += 1
else:
og.Controller.set(node.get_attribute("outputs:tick"), e_state.LATENT_PUSH)
return True
# we are ticking
self.assertEqual(cancel_val, e_state.DISABLED)
tick_count += 1
if tick_count < max_ticks:
og.Controller.set(node.get_attribute("outputs:tick"), e_state.ENABLED)
else:
# Finish latent naturally
og.Controller.set(node.get_attribute("outputs:execOut"), e_state.LATENT_FINISH)
tick_count = 0
if boop_val == e_state.ENABLED:
# We get here during latent ticking, if the boop input is enabled
self.assertEqual(exec_in_val, e_state.DISABLED)
self.assertEqual(cancel_val, e_state.DISABLED)
boop_count += 1
return True
@staticmethod
def get_node_type() -> str:
return "omni.graph.test.CancelTickerPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
node_type.add_input(
"inputs:execIn",
"execution",
True,
)
node_type.add_input(
"inputs:cancel",
"execution",
True,
)
node_type.add_input(
"inputs:boop",
"execution",
True,
)
node_type.add_output("outputs:tick", "execution", True)
node_type.add_output("outputs:canceled", "execution", True)
node_type.add_output("outputs:execOut", "execution", True)
return True
og.register_node_type(CancelTickerPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (ticker, start, _, cancel, boop, _, _, counter), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Ticker", "omni.graph.test.CancelTickerPy"),
("Start", "omni.graph.action.OnImpulseEvent"),
("Start2", "omni.graph.action.OnImpulseEvent"),
("Cancel", "omni.graph.action.OnImpulseEvent"),
("Boop", "omni.graph.action.OnImpulseEvent"),
("Once", "omni.graph.action.Once"),
("Once2", "omni.graph.action.Once"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("Start.outputs:execOut", "Ticker.inputs:execIn"),
("Start2.outputs:execOut", "Ticker.inputs:execIn"),
("Cancel.outputs:execOut", "Once.inputs:execIn"),
("Once.outputs:once", "Ticker.inputs:cancel"),
("Once.outputs:after", "Ticker.inputs:cancel"),
("Cancel.outputs:execOut", "Once2.inputs:execIn"),
("Boop.outputs:execOut", "Ticker.inputs:boop"),
("Once2.outputs:once", "Ticker.inputs:cancel"),
("Once2.outputs:after", "Ticker.inputs:cancel"),
("Ticker.outputs:tick", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("Start.inputs:onlyPlayback", False),
("Start2.inputs:onlyPlayback", False),
("Cancel.inputs:onlyPlayback", False),
("Boop.inputs:onlyPlayback", False),
],
},
)
# cancel, check nothing happens
og.Controller.set(controller.attribute("state:enableImpulse", cancel), True)
await controller.evaluate(graph)
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.DISABLED)
# start ticking
og.Controller.set(controller.attribute("state:enableImpulse", start), True)
await controller.evaluate(graph) # Starts latent state
await controller.evaluate(graph) # Tick 1
self.assertEqual(tick_count, 1)
# Verify the tick has started
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.ENABLED)
await controller.evaluate(graph) # Tick 2
self.assertEqual(tick_count, 2)
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.ENABLED)
await controller.evaluate(graph) # Tick 3
self.assertEqual(tick_count, 3)
# Boop - node keeps ticking
og.Controller.set(controller.attribute("state:enableImpulse", boop), True)
# Boop will trigger a compute, which increments boop + ticks AND the normal latent tick
await controller.evaluate(graph)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 5)
# Now check that the next tick can run WITHOUT inputs:boop being high
await controller.evaluate(graph)
self.assertEqual(boop_count, 1) # No change in boop count (OM-64856)
self.assertEqual(tick_count, 6)
# Now check that we can't re-trigger execIn
self.assertEqual(exec_in_latent_count, 0)
og.Controller.set(controller.attribute("state:enableImpulse", start), True)
# Start will not trigger any compute because the node is latent
await controller.evaluate(graph)
self.assertEqual(exec_in_latent_count, 0)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 7)
# Now check the normal tick proceeds as normal
await controller.evaluate(graph)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 8)
# Cancel
counter_attr = controller.attribute("outputs:count", counter)
count_0 = og.Controller.get(counter_attr)
og.Controller.set(controller.attribute("state:enableImpulse", cancel), True)
await controller.evaluate(graph) # latent finish
await controller.evaluate(graph) # no action
await controller.evaluate(graph) # no action
count_1 = og.Controller.get(counter_attr)
self.assertEqual(count_0 + 1, count_1)
# ----------------------------------------------------------------------
async def test_cycle_break(self):
"""test that an illegal cycle issues a warning"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (on_impulse, count_a, count_b), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("A", "omni.graph.action.Counter"),
("B", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "A.inputs:execIn"),
("A.outputs:execOut", "B.inputs:execIn"),
("B.outputs:execOut", "A.inputs:execIn"),
],
keys.SET_VALUES: [
("OnImpulse.state:enableImpulse", True),
("OnImpulse.inputs:onlyPlayback", False),
],
},
)
with ogts.ExpectedError():
await controller.evaluate(graph)
og.Controller.set(controller.attribute("state:enableImpulse", on_impulse), True)
with ogts.ExpectedError():
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", count_a)), 2)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", count_b)), 2)
# ----------------------------------------------------------------------
async def test_dep_sort_fan_out(self):
"""Test that dependency sort works when there is data fan-out"""
# +-------------+
# +-------->| |
# | | SwitchTokenA|
# | +--->+-------------+
# +----------+ |
# |OnImpulse + | +--------------+
# +----------+ | | SwitchTokenB |
# | +^-------------+
# +------+-+ +--------+ |
# | ConstA +--->AppendB +---+
# +--------+ +--------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, const_a, _, switch_a, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ConstA", "omni.graph.nodes.ConstantToken"),
("AppendB", "omni.graph.nodes.AppendString"),
("SwitchTokenA", "omni.graph.action.SwitchToken"),
("SwitchTokenB", "omni.graph.action.SwitchToken"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "SwitchTokenA.inputs:execIn"),
("ConstA.inputs:value", "SwitchTokenA.inputs:value"),
("ConstA.inputs:value", "AppendB.inputs:value"),
("AppendB.outputs:value", "SwitchTokenB.inputs:value"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("AppendB.inputs:suffix", {"value": "Foo", "type": "token"}),
],
},
)
await controller.evaluate(graph)
graph_state = og.OmniGraphInspector().as_json(graph, flags=["evaluation"])
graph_state_obj = json.loads(graph_state)
trace = graph_state_obj["Evaluator"]["LastNonEmptyEvaluation"]["Trace"]
# Verify the evaluation trace includes exactly what we expect
expected_trace = [
const_a.get_prim_path(),
switch_a.get_prim_path(),
]
self.assertListEqual(expected_trace, trace)
# ----------------------------------------------------------------------
async def test_exec_fan_out_shared_deps(self):
"""Test that dependency sort works when there is shared data in exec fan-out"""
# +---------+
# +---------->| Write1 |
# | +----^----+
# | |
# | +----------+
# | |
# +-----------+ | |
# | OnImpulse +-----+-----+----> +---------+
# +-----------+ | | | Write2 |
# | +----->+---------+
# | |
# | | +---------+
# +-----+----->| Write3 |
# | +---------+
# | ^
# +-------+ +---+----+---+
# | Const +----->| Inc |
# +-------+ +--------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Const", "omni.graph.nodes.ConstantDouble"),
("Inc", "omni.graph.nodes.Increment"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
("Write2", "omni.graph.nodes.WritePrimAttribute"),
("Write3", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: [
("/World/TestPrim1", {"val": ("double", 1.0)}),
("/World/TestPrim2", {"val": ("double", 2.0)}),
("/World/TestPrim3", {"val": ("double", 3.0)}),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Write1.inputs:execIn"),
("OnImpulse.outputs:execOut", "Write2.inputs:execIn"),
("OnImpulse.outputs:execOut", "Write3.inputs:execIn"),
("Const.inputs:value", "Inc.inputs:value"),
("Inc.outputs:result", "Write1.inputs:value"),
("Inc.outputs:result", "Write2.inputs:value"),
("Inc.outputs:result", "Write3.inputs:value"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("Const.inputs:value", 41.0),
("Inc.inputs:increment", 1.0),
("Write1.inputs:primPath", "/World/TestPrim1"),
("Write1.inputs:usePath", True),
("Write1.inputs:name", "val"),
("Write2.inputs:primPath", "/World/TestPrim2"),
("Write2.inputs:usePath", True),
("Write2.inputs:name", "val"),
("Write3.inputs:primPath", "/World/TestPrim3"),
("Write3.inputs:usePath", True),
("Write3.inputs:name", "val"),
],
},
)
await controller.evaluate(graph)
stage = omni.usd.get_context().get_stage()
for i in (1, 2, 3):
self.assertEqual(stage.GetAttributeAtPath(f"/World/TestPrim{i}.val").Get(), 42.0)
# ----------------------------------------------------------------------
async def test_exec_fan_out_shared_deps2(self):
"""Test that dependency sort works when there is shared data in exec fan-out"""
# ┌───────┐ ┌────────┐
# │Const1 ├───────────►│Append1 │
# └───────┘ │ ├──────────►┌───────────┐
# ┌──►└────────┘ │ WriteVar1 │
# ┌─────────────┐ │ ┌────►└───────────┘
# │ GraphTarget ├───┤ │
# └─────────────┘ └─►┌─────────┐ │ ┌───────────┐
# │ Append2 ├─────┼────►│ WriteVar2 │
# ┌────────┐ ┌─►└─────────┘ │ └───────────┘
# │ Const2 ├────────┘ │ ▲
# └────────┘ │ │
# │ │
# ┌──────────┐ │ │
# │ OnImpulse├────┴──────┘
# └──────────┘
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Const1", "omni.graph.nodes.ConstantToken"),
("Const2", "omni.graph.nodes.ConstantToken"),
("Append1", "omni.graph.nodes.AppendPath"),
("Append2", "omni.graph.nodes.AppendPath"),
("GraphTarget", "omni.graph.nodes.GraphTarget"),
("WriteVar1", "omni.graph.core.WriteVariable"),
("WriteVar2", "omni.graph.core.WriteVariable"),
],
keys.CREATE_VARIABLES: [
("path1", og.Type(og.BaseDataType.TOKEN)),
("path2", og.Type(og.BaseDataType.TOKEN)),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "WriteVar1.inputs:execIn"),
("OnImpulse.outputs:execOut", "WriteVar2.inputs:execIn"),
("GraphTarget.outputs:primPath", "Append1.inputs:path"),
("GraphTarget.outputs:primPath", "Append2.inputs:path"),
("Const1.inputs:value", "Append1.inputs:suffix"),
("Const2.inputs:value", "Append2.inputs:suffix"),
("Append1.outputs:path", "WriteVar1.inputs:value"),
("Append2.outputs:path", "WriteVar2.inputs:value"),
],
keys.SET_VALUES: [
("WriteVar1.inputs:variableName", "path1"),
("WriteVar2.inputs:variableName", "path2"),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("Const1.inputs:value", "A"),
("Const2.inputs:value", "B"),
],
},
)
await controller.evaluate(graph)
context = graph.get_default_graph_context()
graph_path = self.TEST_GRAPH_PATH
variable = graph.find_variable("path1")
self.assertEquals(variable.get(context), f"{graph_path}/A")
variable = graph.find_variable("path2")
self.assertEquals(variable.get(context), f"{graph_path}/B")
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_nodes_03.py | """Action Graph Node Tests, Part 3"""
import random
from functools import partial
import carb.input
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.app
import omni.kit.test
import omni.usd
from carb.input import MouseEventType
from omni.graph.core import ThreadsafetyTestUtils
from pxr import Gf, OmniGraphSchemaTools, Sdf
# ======================================================================
class TestActionGraphNodes(ogts.OmniGraphTestCase):
"""Tests action graph node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
keys = og.Controller.Keys
E = og.ExecutionAttributeState.ENABLED
D = og.ExecutionAttributeState.DISABLED
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_onmouseinput_node(self, test_instance_id: int = 0):
"""Test OnMouseInput node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_mouse_input_node,), _, _) = og.Controller.edit(
graph_path,
{self.keys.CREATE_NODES: ("OnMouseInput", "omni.graph.action.OnMouseInput")},
)
# Obtain necessary attributes.
in_onlyplayback_attr = on_mouse_input_node.get_attribute("inputs:onlyPlayback")
in_mouse_element_attr = on_mouse_input_node.get_attribute("inputs:mouseElement")
out_pressed_attr = on_mouse_input_node.get_attribute("outputs:pressed")
out_released_attr = on_mouse_input_node.get_attribute("outputs:released")
out_valuechanged_attr = on_mouse_input_node.get_attribute("outputs:valueChanged")
out_ispressed_attr = on_mouse_input_node.get_attribute("outputs:isPressed")
out_value_attr = on_mouse_input_node.get_attribute("outputs:value")
# Obtain an interface to the mouse and carb input provider.
mouse = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, omni.appwindow.get_default_app_window().get_mouse()
)
input_provider = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, carb.input.acquire_input_provider()
)
# Define a list of tokens representing the possible inputs to the OnMouseInput node's "mouseElement" attribute.
mouse_tokens = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
["Left Button", "Middle Button", "Right Button", "Normalized Move", "Pixel Move", "Scroll"],
)
# Define a list of all possible mouse event types (for convenience).
mouse_event_types = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
[
MouseEventType.LEFT_BUTTON_DOWN,
MouseEventType.LEFT_BUTTON_UP,
MouseEventType.MIDDLE_BUTTON_DOWN,
MouseEventType.MIDDLE_BUTTON_UP,
MouseEventType.RIGHT_BUTTON_DOWN,
MouseEventType.RIGHT_BUTTON_UP,
MouseEventType.MOVE,
MouseEventType.SCROLL,
],
)
# Define some imaginary window dimensions for testing purposes.
window_width = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, 1440)
window_height = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, 720)
# Wrap main test driver code in the following generator (to leverage the
# ThreadsafetyTestUtils.make_threading_test decorator to its fullest). Note that
# in addition to testing whether specific buttons activate their corresponding code
# path, we also check that no other buttons can activate code paths they don't belong
# to (e.g. that pressing the left mouse button doesn't get registered as a button
# press when "inputs:mouseElement" is set to "Right Button").
def _test_onmouseinput_node():
# Loop through each possible "inputs.mouseElement" token, and set the input attribute
# on the OnMouseInput nodes in each graph.
for token in mouse_tokens:
in_mouse_element_attr.set(token)
# Loop through each possible mouse event type.
for event_type in mouse_event_types:
# Generate a new random test position for the mouse cursor. Note that we
# add it to the threading cache so that each test graph instance runs
# its tests/comparisons against the same randomly-generated position.
pos = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, (random.randint(0, window_width), random.randint(0, window_height))
)
# Trigger the current mouse event.
input_provider.buffer_mouse_event(
mouse, event_type, (pos[0] / window_width, pos[1] / window_height), 0, pos
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# Test left/middle/right mouse button pressed functionality. Only left/middle/right
# mouse button presses should activate this codepath.
if (
(event_type == MouseEventType.LEFT_BUTTON_DOWN and token == "Left Button")
or (event_type == MouseEventType.MIDDLE_BUTTON_DOWN and token == "Middle Button")
or (event_type == MouseEventType.RIGHT_BUTTON_DOWN and token == "Right Button")
):
self.assertEqual(out_pressed_attr.get(), self.E)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.D)
self.assertTrue(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertEqual(out_value_attr.get()[0], 0)
self.assertEqual(out_value_attr.get()[1], 0)
# Test left/middle/right mouse button released functionality. Only left/middle/right mouse
# button releases should activate this codepath.
elif (
(event_type == MouseEventType.LEFT_BUTTON_UP and token == "Left Button")
or (event_type == MouseEventType.MIDDLE_BUTTON_UP and token == "Middle Button")
or (event_type == MouseEventType.RIGHT_BUTTON_UP and token == "Right Button")
):
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.E)
self.assertEqual(out_valuechanged_attr.get(), self.D)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertEqual(out_value_attr.get()[0], 0)
self.assertEqual(out_value_attr.get()[1], 0)
# Test mouse movement functionality with the "Normalized Move" option enabled. Only mouse movement
# should activate this codepath.
elif event_type == MouseEventType.MOVE and token == "Normalized Move":
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertAlmostEqual(out_value_attr.get()[0], pos[0] / window_width)
self.assertAlmostEqual(out_value_attr.get()[1], pos[1] / window_height)
# Test mouse movement functionality with the "Pixel Move" option enabled. Only mouse movement
# should activate this codepath.
elif event_type == MouseEventType.MOVE and token == "Pixel Move":
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertEqual(out_value_attr.get()[0], pos[0])
self.assertEqual(out_value_attr.get()[1], pos[1])
# Test mouse scrolling functionality with the "Scroll" option enabled. Only mouse scrolling
# should activate this codepath.
elif event_type == MouseEventType.SCROLL and token == "Scroll":
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertAlmostEqual(out_value_attr.get()[0], pos[0] / window_width)
self.assertAlmostEqual(out_value_attr.get()[1], pos[1] / window_height)
# Non-activated codepath.
else:
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.D)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertEqual(out_value_attr.get()[0], 0)
self.assertEqual(out_value_attr.get()[1], 0)
# Test that the OnMouseInput node works correctly when its onlyPlayback input is disabled.
in_onlyplayback_attr.set(False)
for _ in _test_onmouseinput_node():
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# Test that the OnMouseInput node works correctly when its onlyPlayback input is enabled.
in_onlyplayback_attr.set(True)
timeline = omni.timeline.get_timeline_interface()
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
timeline.play()
for _ in _test_onmouseinput_node():
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
timeline.stop()
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_onobjectchange_node(self, test_instance_id: int = 0):
"""Test OnObjectChange node"""
usd_context = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, omni.usd.get_context())
stage = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, usd_context.get_stage())
cube = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, ogts.create_cube(stage, "Cube", (0.6, 0.4, 0.0))
)
attr_position = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, cube.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False)
)
attr_rotation = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, cube.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Float3, False)
)
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(graph, (on_object_change_node, flip_flop_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
(graph_path + "/OnObjectChange", "omni.graph.action.OnObjectChange"),
(graph_path + "/FlipFlop", "omni.graph.action.FlipFlop"),
],
self.keys.SET_VALUES: [
(graph_path + "/OnObjectChange.inputs:onlyPlayback", False),
(graph_path + "/OnObjectChange.inputs:prim", attr_position.GetPrimPath()),
(graph_path + "/OnObjectChange.inputs:name", attr_position.GetName()),
],
self.keys.CONNECT: (
graph_path + "/OnObjectChange.outputs:changed",
graph_path + "/FlipFlop.inputs:execIn",
),
},
)
outa = og.Controller.attribute("outputs:a", flip_flop_node)
# Check the current FlipFlop state, and that it isn't changing until we move the cube.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
ff_a_state_1 = og.Controller.get(outa)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(outa), ff_a_state_1)
# Try changing a different (non-translate) attribute - should not trigger.
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(attr_rotation.Set, Gf.Vec3f(180.0, 0.0, 0.0))
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(outa), ff_a_state_1)
# Now change the translate attribute - should trigger.
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(attr_position.Set, Gf.Vec3f(1.0, 0.0, 0.0))
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
ff_a_state_2 = og.Controller.get(outa)
self.assertEqual(ff_a_state_2, 1 if not ff_a_state_1 else 0)
property_path = og.Controller.get(og.Controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_position.GetName())
# Look at the prim itself.
og.Controller.edit(
graph,
{self.keys.SET_VALUES: (graph_path + "/OnObjectChange.inputs:name", "")},
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Now change the rotate attribute - should trigger.
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(attr_rotation.Set, Gf.Vec3f(245.0, 0.0, 0.0))
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
ff_a_state_1 = og.Controller.get(outa)
self.assertEqual(ff_a_state_1, 1 if not ff_a_state_2 else 0)
property_path = og.Controller.get(og.Controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_rotation.GetName())
# Now use the path input instead of the target. Do this for all OnObjectChange nodes!
og.Controller.edit(
graph,
{
self.keys.SET_VALUES: [
(graph_path + "/OnObjectChange.inputs:path", cube.GetPath().pathString),
(graph_path + "/OnObjectChange.inputs:prim", []),
]
},
)
# Compute once to set up the inputs.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Change the rotate attribute - should trigger.
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(attr_rotation.Set, Gf.Vec3f(0.0, 0.0, 0.0))
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
ff_a_state_2 = og.Controller.get(outa)
self.assertEqual(ff_a_state_2, 1 if not ff_a_state_1 else 0)
property_path = og.Controller.get(og.Controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_rotation.GetName())
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_onplaybacktick_node(self, test_instance_id: int = 0):
"""Test OnPlaybackTick node"""
timeline = omni.timeline.get_timeline_interface()
# The stage's default stage is probably 60, set to 30 for this specific case
stage = omni.usd.get_context().get_stage()
fps = 30.0
stage.SetTimeCodesPerSecond(fps)
stage.SetStartTimeCode(1.0)
stage.SetEndTimeCode(10.0)
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_p_tick_node, _), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnPTick", "omni.graph.action.OnPlaybackTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
self.keys.CONNECT: [
("OnPTick.outputs:tick", "FlipFlop.inputs:execIn"),
],
},
)
# Obtain necessary attributes.
tick_time_attr = on_p_tick_node.get_attribute("outputs:time")
tick_frame_attr = on_p_tick_node.get_attribute("outputs:frame")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Check that the OnPlaybackTick node doesn't trigger when playback is not active.
self.assertEqual(tick_time_attr.get(), 0)
self.assertEqual(tick_frame_attr.get(), 0)
# Check that the OnPlaybackTick node does trigger when playback is active, and the values are correct.
timeline.play()
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertAlmostEqual(tick_time_attr.get(), timeline.get_current_time(), places=5)
self.assertAlmostEqual(tick_frame_attr.get(), tick_time_attr.get() * fps, places=5)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_ontick_node(self, test_instance_id: int = 0):
"""Test OnTick node"""
timeline = omni.timeline.get_timeline_interface()
# The stage's default stage is probably 60, set to 30 for this specific case
stage = omni.usd.get_context().get_stage()
fps = 30.0
stage.SetTimeCodesPerSecond(fps)
stage.SetStartTimeCode(1.0)
stage.SetEndTimeCode(10.0)
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_tick_node, _), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "FlipFlop.inputs:execIn"),
],
self.keys.SET_VALUES: ("OnTick.inputs:onlyPlayback", True),
},
)
# Obtain necessary attributes.
ontick_time_attr = on_tick_node.get_attribute("outputs:time")
ontick_frame_attr = on_tick_node.get_attribute("outputs:frame")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Check that the OnTick node doesn't trigger when playback is not active.
self.assertEqual(ontick_time_attr.get(), 0)
self.assertEqual(ontick_frame_attr.get(), 0)
# Check that the OnTick node does trigger when playback is active, and the values are correct.
timeline.play()
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertAlmostEqual(ontick_time_attr.get(), timeline.get_current_time(), places=5)
self.assertAlmostEqual(ontick_frame_attr.get(), ontick_time_attr.get() * fps, places=5)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_onvariablechange_node(self, test_instance_id: int = 0):
"""Test OnVariableChange node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(graph, (on_variable_change_node, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnVariableChange", "omni.graph.action.OnVariableChange"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [
("OnVariableChange.inputs:onlyPlayback", False),
],
self.keys.CONNECT: [("OnVariableChange.outputs:changed", "Counter.inputs:execIn")],
},
)
graph_context = graph.get_default_graph_context()
# Create a new float variable on each graph, and set the OnVariableChange nodes to track this single variable.
var_name = "myVar" + str(test_instance_id)
my_var = og.Controller.create_variable(graph, var_name, "FLOAT")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
og.Controller.set(og.Controller.attribute("inputs:variableName", on_variable_change_node), var_name)
# Check that the execution output is still set to zero.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.D)
# Change the variable's value, check that the execution reads true now.
my_var.set(graph_context, 5.2)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.E)
# Evaluate a second time to check that the execution gets set back to zero.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.D)
# Make sure that the output execution remains off if we try setting the variable
# to the same previous value.
my_var.set(graph_context, 5.2)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.D)
# Check that setting the inputs:variableName to a nonexistant variable results in the output
# execution pin remaining zero.
og.Controller.set(og.Controller.attribute("inputs:variableName", on_variable_change_node), "nonexistant_name")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.D)
# Set the onlyPlayback flag to true, run a similar set of tests to ensure that this setting
# still works with the node. Note that a Counter node is used here to detect the variable change
# because it's trickier to check against outputs:changed directly (harder to time everything with
# all of the async stuff + when the timeline is running).
og.Controller.set(og.Controller.attribute("inputs:variableName", on_variable_change_node), var_name)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
og.Controller.set(og.Controller.attribute("inputs:onlyPlayback", on_variable_change_node), True)
timeline = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, omni.timeline.get_timeline_interface()
)
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(timeline.set_target_framerate, timeline.get_time_codes_per_seconds())
)
ThreadsafetyTestUtils.single_evaluation_first_test_instance(test_instance_id, partial(timeline.play))
my_var.set(graph_context, 4.6)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
my_var.set(graph_context, 4.6)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
my_var.set(graph_context, 4.6)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
og.Controller.set(og.Controller.attribute("inputs:variableName", on_variable_change_node), "nonexistant_name_2")
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
ThreadsafetyTestUtils.single_evaluation_last_test_instance(test_instance_id, partial(timeline.stop))
# ----------------------------------------------------------------------
async def _run_test_variable_of_type(self, graph_id, var_type: og.Type, initial_value, changed_value):
"""Helper method to run a variable test with different variable types"""
graph_path = self.TEST_GRAPH_PATH + graph_id
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(graph, (_, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnVariableChange", "omni.graph.action.OnVariableChange"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [
("OnVariableChange.inputs:onlyPlayback", False),
("OnVariableChange.inputs:variableName", "var"),
],
self.keys.CONNECT: [("OnVariableChange.outputs:changed", "Counter.inputs:execIn")],
self.keys.CREATE_VARIABLES: [
("var", var_type),
],
},
)
# test that nothing triggered on the initial run
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 0)
var = graph.find_variable("var")
# set the initial value, expected a trigger
var.set(graph.get_context(), initial_value)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 1)
ogts.verify_values(var.get(graph.get_context()), initial_value, "expected initial value to be set")
# change the value of the variable and makes sure the OnVariableChange triggers
var.set(graph.get_context(), changed_value)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
ogts.verify_values(var.get(graph.get_context()), changed_value, "expeected changed value to be set")
# ----------------------------------------------------------------------
async def test_onvariablechanged_by_type(self):
"""Tests OnVariableChange for different types of variables, including strings and arrays"""
await self._run_test_variable_of_type("_int", og.Type(og.BaseDataType.INT), 1, 2)
await self._run_test_variable_of_type("_int_array", og.Type(og.BaseDataType.INT, 1, 1), [1, 2, 3], [3, 4, 5])
await self._run_test_variable_of_type(
"_int_array_size", og.Type(og.BaseDataType.INT, 1, 1), [1, 2, 3, 4, 5], [1, 2, 3]
)
await self._run_test_variable_of_type("_tuple", og.Type(og.BaseDataType.INT, 3, 0), (1, 2, 3), (3, 4, 5))
await self._run_test_variable_of_type(
"_string", og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.TEXT), "init", "changed"
)
await self._run_test_variable_of_type(
"_tuple_array", og.Type(og.BaseDataType.INT, 3, 1), [(1, 2, 3), (4, 5, 6)], [(3, 4, 5)]
)
# ----------------------------------------------------------------------
async def test_onvariablechange_node_instances(self):
"""Tests that OnVariableChange node works with instancing"""
controller = og.Controller()
keys = og.Controller.Keys
int_range = range(1, 100)
stage = omni.usd.get_context().get_stage()
for i in int_range:
prim_name = f"/World/Prim_{i}"
prim = stage.DefinePrim(prim_name)
OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self.TEST_GRAPH_PATH)
prim.CreateAttribute("graph:variable:int_var", Sdf.ValueTypeNames.Int).Set(0)
prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Int).Set(i)
(_, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnVariableChange", "omni.graph.action.OnVariableChange"),
("GraphTarget", "omni.graph.nodes.GraphTarget"),
("ReadPrimAttr", "omni.graph.nodes.ReadPrimAttribute"),
("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"),
("Add", "omni.graph.nodes.Add"),
("ConstantInt", "omni.graph.nodes.ConstantInt"),
],
keys.CONNECT: [
("OnVariableChange.outputs:changed", "WritePrimAttr.inputs:execIn"),
("GraphTarget.outputs:primPath", "WritePrimAttr.inputs:primPath"),
("GraphTarget.outputs:primPath", "ReadPrimAttr.inputs:primPath"),
("ReadPrimAttr.outputs:value", "Add.inputs:a"),
("ConstantInt.inputs:value", "Add.inputs:b"),
("Add.outputs:sum", "WritePrimAttr.inputs:value"),
],
keys.CREATE_VARIABLES: [("int_var", og.Type(og.BaseDataType.INT))],
keys.SET_VALUES: [
("OnVariableChange.inputs:onlyPlayback", False),
("OnVariableChange.inputs:variableName", "int_var"),
("WritePrimAttr.inputs:usePath", True),
("WritePrimAttr.inputs:name", "graph_output"),
("ReadPrimAttr.inputs:usePath", True),
("ReadPrimAttr.inputs:name", "graph_output"),
("ConstantInt.inputs:value", 1),
],
},
)
await omni.kit.app.get_app().next_update_async()
# Setting value of int_var from 0 to 1.
for i in int_range:
prim_path = f"/World/Prim_{i}"
prev_val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get()
stage.GetPrimAtPath(prim_path).GetAttribute("graph:variable:int_var").Set(1)
await omni.kit.app.get_app().next_update_async()
val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get()
self.assertEqual(val, prev_val + 1, msg=f"{prim_path}")
# Setting value of int_var from 1 to 1.
for i in int_range:
prim_path = f"/World/Prim_{i}"
prev_val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get()
stage.GetPrimAtPath(prim_path).GetAttribute("graph:variable:int_var").Set(1)
await omni.kit.app.get_app().next_update_async()
val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get()
self.assertEqual(val, prev_val + 1, msg=f"{prim_path}")
# ----------------------------------------------------------------------
# The SendCustomEvent node is tested in tandem with the OnCustomEvent node above; it is also used
# extensively in other tests, so we skip adding another dedicated test here.
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_sequence_node(self, test_instance_id: int = 0):
"""Test Sequence node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (_, sequence_node, counter0_node, counter1_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Sequence", "omni.graph.action.Sequence"),
("Counter0", "omni.graph.action.Counter"),
("Counter1", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Sequence.inputs:execIn"),
("Sequence.outputs:a", "Counter0.inputs:execIn"),
("Sequence.outputs:b", "Counter1.inputs:execIn"),
],
},
)
# Obtain necessary attributes.
in_exec_attr_0 = counter0_node.get_attribute("inputs:execIn")
out_cnt_attr_0 = counter0_node.get_attribute("outputs:count")
out_cnt_attr_1 = counter1_node.get_attribute("outputs:count")
out_a_attr = sequence_node.get_attribute("outputs:a")
out_b_attr = sequence_node.get_attribute("outputs:b")
# Check that the Sequence node correctly executes through its outputs when input
# execution is enabled via the OnTick node. This is done by checking whether
# each counter has been incremented by 1, and if the last output pin on the Sequence
# nodes remain enabled (regardless of the fact that they're not connected downstream).
# Similar test to the Multisequence node.
self.assertEqual(out_cnt_attr_0.get(), 0)
self.assertEqual(out_cnt_attr_1.get(), 0)
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 1)
self.assertEqual(out_cnt_attr_1.get(), 1)
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.E)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 2)
self.assertEqual(out_cnt_attr_1.get(), 2)
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.E)
# Connect output pin b to the Counter1 node. This is because both pins a and b share
# the same terminal input attribute, so both must have the same value. Since
# b is the last attribute and must be set to 1 (due to logic inside this node's
# compute method), output a must also take on this value.
og.Controller.connect(out_b_attr, in_exec_attr_0)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 4)
self.assertEqual(out_cnt_attr_1.get(), 3)
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.E)
# ----------------------------------------------------------------------
async def test_setprimactive_node(self):
await self._setprimactive_node(False)
# ----------------------------------------------------------------------
async def test_setprimactive_node_with_target(self):
await self._setprimactive_node(True)
# ----------------------------------------------------------------------
async def _setprimactive_node(self, use_target_inputs):
"""
Test SetPrimActive node. If use_target_inputs is true, will use the prim target inputs rather than prim path
"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
(_, (_, set_prim_active_node), _, _,) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("SetPrimActive", "omni.graph.action.SetPrimActive"),
],
self.keys.CREATE_PRIMS: [
("/TestPrim", {}),
],
self.keys.CONNECT: [("OnTick.outputs:tick", "SetPrimActive.inputs:execIn")],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("SetPrimActive.inputs:prim", "/TestPrim"),
("SetPrimActive.inputs:active", True),
],
},
)
await og.Controller.evaluate()
if use_target_inputs:
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/SetPrimActive.inputs:primTarget")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/TestPrim")
await og.Controller.evaluate()
# Check that the prim we're pointing to remains active when we trigger
# graph evaluation.
prim = stage.GetPrimAtPath("/TestPrim")
self.assertTrue(prim.IsActive())
await og.Controller.evaluate()
self.assertTrue(prim.IsActive())
# Now set the prim to be inactive.
og.Controller.set(og.Controller.attribute("inputs:active", set_prim_active_node), False)
await og.Controller.evaluate()
self.assertFalse(prim.IsActive())
await og.Controller.evaluate()
self.assertFalse(prim.IsActive())
# Again set to be active, make sure that the prim gets reactivated.
og.Controller.set(og.Controller.attribute("inputs:active", set_prim_active_node), True)
await og.Controller.evaluate()
self.assertTrue(prim.IsActive())
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_switchtoken_node(self, test_instance_id: int = 0):
"""Test SwitchToken node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (_, switch_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Switch", "omni.graph.action.SwitchToken"),
],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Switch.inputs:execIn"),
],
},
)
# Test that an execution connection is correctly triggering the downstream nodes once per evaluation.
def add_input(index: int):
og.Controller.create_attribute(
switch_node,
f"inputs:branch{index:02}",
"token",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
)
og.Controller.create_attribute(
switch_node,
f"outputs:output{index:02}",
"execution",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
og.Controller.set(og.Controller.attribute(f"inputs:branch{index:02}", switch_node), f"{index:02}")
for index in range(5):
add_input(index)
for index in range(5):
og.Controller.set(og.Controller.attribute("inputs:value", switch_node), f"{index:02}")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
for index2 in range(5):
expected_val = (
og.ExecutionAttributeState.DISABLED if index2 != index else og.ExecutionAttributeState.ENABLED
)
self.assertEqual(
og.Controller.get(og.Controller.attribute(f"outputs:output{index2:02}", switch_node)),
expected_val,
)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_syncgate_node(self, test_instance_id: int = 0):
"""Test SyncGate node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(
_,
(on_impulse0_node, on_impulse1_node, on_impulse2_node, on_impulse3_node, sync_gate_node, counter_node),
_,
_,
) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnImpulse0", "omni.graph.action.OnImpulseEvent"),
("OnImpulse1", "omni.graph.action.OnImpulseEvent"),
("OnImpulse2", "omni.graph.action.OnImpulseEvent"),
("OnImpulse3", "omni.graph.action.OnImpulseEvent"),
("SyncGate", "omni.graph.action.SyncGate"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnImpulse0.outputs:execOut", "SyncGate.inputs:execIn"),
("OnImpulse1.outputs:execOut", "SyncGate.inputs:execIn"),
("OnImpulse2.outputs:execOut", "SyncGate.inputs:execIn"),
("OnImpulse3.outputs:execOut", "SyncGate.inputs:execIn"),
("SyncGate.outputs:execOut", "Counter.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnImpulse0.inputs:onlyPlayback", False),
("OnImpulse1.inputs:onlyPlayback", False),
("OnImpulse2.inputs:onlyPlayback", False),
("OnImpulse3.inputs:onlyPlayback", False),
("SyncGate.inputs:syncValue", 5),
],
},
)
# Obtain necessary attributes.
state_enable_impulse_attr_0 = on_impulse0_node.get_attribute("state:enableImpulse")
state_enable_impulse_attr_1 = on_impulse1_node.get_attribute("state:enableImpulse")
state_enable_impulse_attr_2 = on_impulse2_node.get_attribute("state:enableImpulse")
state_enable_impulse_attr_3 = on_impulse3_node.get_attribute("state:enableImpulse")
in_syncvalue_attr = sync_gate_node.get_attribute("inputs:syncValue")
out_syncvalue_attr = sync_gate_node.get_attribute("outputs:syncValue")
out_cnt_attr = counter_node.get_attribute("outputs:count")
# First check that the SyncGate node only gets unblocked when it detects 4+ input
# enabled executions, at which point the Counter node will begin to be incremented.
# Also check that after the 1st graph evaluation the SyncGate's output syncValue gets
# set to its input syncValue.
state_enable_impulse_attr_0.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 0)
state_enable_impulse_attr_1.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 0)
state_enable_impulse_attr_2.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 0)
state_enable_impulse_attr_3.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 1)
state_enable_impulse_attr_0.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 2)
# Now reset the SyncGate node's syncValue. Check that we once again need 4+ input executions
# with the "enabled" status flowing into the SyncGate in order to unlock it. Also note
# that we don't technically need each separate OnImpulse node to trigger to unlock the gate;
# we could have a single OnImpulse node (per graph) send 4 separate impulses to open each gate
# in each graph, since that would reach the threshold number of accumulated execIn states for
# this setup (equal to 4 since we have 4 nodes connected to the SyncGate's inputs:execIn pin).
in_syncvalue_attr.set(9)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
for i in range(0, 5):
state_enable_impulse_attr_0.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 9)
if i < 3:
self.assertEqual(out_cnt_attr.get(), 2)
else:
self.assertEqual(out_cnt_attr.get(), 2 + (i - 2))
# Now reset the syncValue again per node. This time only send 2 input impulses, then reset the syncValue
# immediately after. Check that we'll again need to send 4 input impulses to open the corresponding gate
# (which was essentially "relocked" with the syncValue change).
in_syncvalue_attr.set(21)
state_enable_impulse_attr_0.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 21)
self.assertEqual(out_cnt_attr.get(), 4)
state_enable_impulse_attr_2.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 21)
self.assertEqual(out_cnt_attr.get(), 4)
in_syncvalue_attr.set(25)
for i in range(0, 5):
state_enable_impulse_attr_2.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 25)
if i < 3:
self.assertEqual(out_cnt_attr.get(), 4)
else:
self.assertEqual(out_cnt_attr.get(), 4 + (i - 2))
# ----------------------------------------------------------------------
async def test_countdown_node(self):
"""Test Countdown node"""
duration = 5
period = 3
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, (_, _, counter0_node, counter1_node), _, _,) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Countdown", "omni.graph.action.Countdown"),
("Counter0", "omni.graph.action.Counter"),
("Counter1", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Countdown.inputs:execIn"),
("Countdown.outputs:finished", "Counter0.inputs:execIn"),
("Countdown.outputs:tick", "Counter1.inputs:execIn"),
],
# Set the Countdown inputs so that the Counter0 node only gets incremented
# once 4 update ticks have passed since the graph creation, and so that
# the Counter1 node gets incremented every 2 ticks.
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Countdown.inputs:duration", duration),
("Countdown.inputs:period", period),
],
},
)
# Obtain necessary attributes.
out_cnt_attr_0 = counter0_node.get_attribute("outputs:count")
out_cnt_attr_1 = counter1_node.get_attribute("outputs:count")
# Test against a predetermined set of values to make sure that
# this node doesn't break in the future.
cnt0 = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
cnt1 = [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]
for i in range(0, 20):
await og.Controller.evaluate()
self.assertEqual(og.Controller.get(out_cnt_attr_0), cnt0[i])
self.assertEqual(og.Controller.get(out_cnt_attr_1), cnt1[i])
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_actiongraph.py | """Basic tests of the action graph"""
import omni.client
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from pxr import Gf, Sdf
# ======================================================================
class TestActionGraphNodes(ogts.OmniGraphTestCase):
"""Tests action graph node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_basic(self):
"""exercise a basic network of execution nodes"""
controller = og.Controller()
keys = og.Controller.Keys
# Test that an execution connection is correctly triggering the downstream node once per evaluation
(graph, (_, flip_flop_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [("OnTick", "omni.graph.action.OnTick"), ("FlipFlop", "omni.graph.action.FlipFlop")],
keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
keys.CONNECT: ("OnTick.outputs:tick", "FlipFlop.inputs:execIn"),
},
)
outa = controller.attribute("outputs:a", flip_flop_node)
outb = controller.attribute("outputs:b", flip_flop_node)
outisa = controller.attribute("outputs:isA", flip_flop_node)
# first eval, 'a'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.ENABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.DISABLED)
self.assertTrue(og.Controller.get(outisa))
# second eval 'b'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.DISABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.ENABLED)
self.assertFalse(og.Controller.get(outisa))
# third eval 'a'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.ENABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.DISABLED)
self.assertTrue(og.Controller.get(outisa))
# Test that non-usd-backed node has execution attribute type correct
_, on_tick_no_usd = og.cmds.CreateNode(
graph=graph,
node_path=f"{self.TEST_GRAPH_PATH}/OnTickNoUSD",
node_type="omni.graph.action.OnTick",
create_usd=False,
)
og.cmds.CreateNode(
graph=graph,
node_path=f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD",
node_type="omni.graph.action.FlipFlop",
create_usd=False,
)
controller.attribute("inputs:onlyPlayback", on_tick_no_usd, graph).set(False)
og.cmds.ConnectAttrs(
src_attr=f"{self.TEST_GRAPH_PATH}/OnTickNoUSD.outputs:tick",
dest_attr=f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD.inputs:execIn",
modify_usd=False,
)
outa = controller.attribute("outputs:a", f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD")
outb = controller.attribute("outputs:b", f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD")
outisa = controller.attribute("outputs:isA", f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD")
# first eval, 'a'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.ENABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.DISABLED)
self.assertTrue(og.Controller.get(outisa))
# second eval 'b'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.DISABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.ENABLED)
self.assertFalse(og.Controller.get(outisa))
# third eval 'a'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.ENABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.DISABLED)
self.assertTrue(og.Controller.get(outisa))
# ----------------------------------------------------------------------
async def test_notice(self):
"""Tests the OnObjectChange node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
cube = ogts.create_cube(stage, "Cube", (0.6, 0.4, 0.0))
attr_position = cube.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False)
attr_rotation = cube.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Float3, False)
(graph, (on_object_change_node, flip_flop_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnObjectChange", "omni.graph.action.OnObjectChange"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
keys.SET_VALUES: [
("OnObjectChange.inputs:onlyPlayback", False),
("OnObjectChange.inputs:path", attr_position.GetPath().pathString),
],
keys.CONNECT: ("OnObjectChange.outputs:changed", "FlipFlop.inputs:execIn"),
},
)
outa = controller.attribute("outputs:a", flip_flop_node)
# check current flipflop state, and that it isn't changing until we move the cube
await controller.evaluate(graph)
ff_a_state_1 = og.Controller.get(outa)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), ff_a_state_1)
# Try changing a different attr - should not trigger
attr_rotation.Set(Gf.Vec3f(180.0, 0.0, 0.0))
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), ff_a_state_1)
# Now change the translate - should trigger
attr_position.Set(Gf.Vec3f(1.0, 0.0, 0.0))
await controller.evaluate(graph)
ff_a_state_2 = og.Controller.get(outa)
self.assertEqual(ff_a_state_2, 1 if not ff_a_state_1 else 0)
property_path = og.Controller.get(controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_position.GetName())
# Look at prim itself
controller.edit(graph, {keys.SET_VALUES: ("OnObjectChange.inputs:path", cube.GetPath().pathString)})
await controller.evaluate(graph)
# Now change the rotate - should trigger
attr_rotation.Set(Gf.Vec3f(245.0, 0.0, 0.0))
await controller.evaluate(graph)
ff_a_state_1 = og.Controller.get(outa)
self.assertEqual(ff_a_state_1, 1 if not ff_a_state_2 else 0)
property_path = og.Controller.get(controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_rotation.GetName())
# Now use a prim rel instead of the path input
inputs_prim = stage.GetPrimAtPath(on_object_change_node.get_prim_path()).GetRelationship("inputs:prim")
inputs_prim.AddTarget(cube.GetPath())
controller.edit(graph, {keys.SET_VALUES: ("OnObjectChange.inputs:path", "")})
# compute once to set up the inputs
await controller.evaluate(graph)
# change rotate - should trigger
attr_rotation.Set(Gf.Vec3f(0.0, 0.0, 0.0))
await controller.evaluate(graph)
ff_a_state_2 = og.Controller.get(outa)
self.assertEqual(ff_a_state_2, 1 if not ff_a_state_1 else 0)
property_path = og.Controller.get(controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_rotation.GetName())
# ----------------------------------------------------------------------
async def test_onplaybacktick(self):
"""Test OnPlaybackTick and OnTick node"""
controller = og.Controller()
keys = og.Controller.Keys
app = omni.kit.app.get_app()
timeline = omni.timeline.get_timeline_interface()
timeline.set_start_time(1.0)
timeline.set_end_time(10.0)
fps = 24.0
timeline.set_time_codes_per_second(fps)
(graph, (on_p_tick_node, on_tick_node, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnPTick", "omni.graph.action.OnPlaybackTick"),
("OnTick", "omni.graph.action.OnTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
keys.CONNECT: [
("OnPTick.outputs:tick", "FlipFlop.inputs:execIn"),
("OnTick.outputs:tick", "FlipFlop.inputs:execIn"),
],
keys.SET_VALUES: ("OnTick.inputs:onlyPlayback", True),
},
)
await controller.evaluate(graph)
tick_time = controller.attribute("outputs:time", on_p_tick_node)
tick_frame = controller.attribute("outputs:frame", on_p_tick_node)
ontick_time = controller.attribute("outputs:time", on_tick_node)
ontick_frame = controller.attribute("outputs:frame", on_tick_node)
# Check that the OnPlaybackTick node doesn't trigger when playback is not active
self.assertEqual(og.Controller.get(tick_time), 0)
self.assertEqual(og.Controller.get(tick_frame), 0)
self.assertEqual(og.Controller.get(ontick_time), 0)
self.assertEqual(og.Controller.get(ontick_frame), 0)
# Check that the OnPlaybackTick node does trigger when playback is active, and the values are correct
timeline.play()
await app.next_update_async()
await controller.evaluate(graph)
t0 = og.Controller.get(tick_time)
f0 = og.Controller.get(tick_frame)
self.assertAlmostEqual(t0, timeline.get_current_time(), places=5)
self.assertAlmostEqual(f0, t0 * fps, places=5)
t0 = og.Controller.get(ontick_time)
f0 = og.Controller.get(ontick_frame)
self.assertAlmostEqual(t0, timeline.get_current_time(), places=5)
self.assertAlmostEqual(f0, t0 * fps, places=5)
# ----------------------------------------------------------------------
async def test_non_action_subgraph(self):
"""Tests subgraphs in action graph"""
controller = og.Controller()
keys = og.Controller.Keys
# Test that a push subgraph is ticked by the top level Action graph
subgraph_path = self.TEST_GRAPH_PATH + "/push_sub"
graph = omni.graph.core.get_current_graph()
graph.create_subgraph(subgraph_path, evaluator="push")
subgraph = graph.get_subgraph(subgraph_path)
self.assertTrue(subgraph.is_valid())
sub_ff_node = self.TEST_GRAPH_PATH + "/push_sub/FlipFlop"
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
keys.CONNECT: ("OnTick.outputs:tick", "FlipFlop.inputs:execIn"),
},
)
await og.Controller.evaluate()
controller.edit(subgraph, {keys.CREATE_NODES: (sub_ff_node, "omni.graph.action.FlipFlop")})
sub_flipflop_node = subgraph.get_node(sub_ff_node)
self.assertTrue(sub_flipflop_node.is_valid())
ffstate0 = og.Controller.get(controller.attribute("outputs:isA", sub_ff_node))
await og.Controller.evaluate()
ffstate1 = og.Controller.get(controller.attribute("outputs:isA", sub_ff_node))
self.assertNotEqual(ffstate0, ffstate1)
# ----------------------------------------------------------------------
async def test_custom_events(self):
"""Test SendCustomEvent and OnCustomEvent node"""
controller = og.Controller()
keys = og.Controller.Keys
await omni.kit.app.get_app().next_update_async()
(_, (_, _, event1_node, counter1_node, event2_node, counter2_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Send", "omni.graph.action.SendCustomEvent"),
("OnCustomEvent1", "omni.graph.action.OnCustomEvent"),
("Counter1", "omni.graph.action.Counter"),
("OnCustomEvent2", "omni.graph.action.OnCustomEvent"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Send.inputs:execIn"),
("OnCustomEvent1.outputs:execOut", "Counter1.inputs:execIn"),
("OnCustomEvent2.outputs:execOut", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [
("OnCustomEvent1.inputs:onlyPlayback", False),
("OnCustomEvent2.inputs:onlyPlayback", False),
("OnImpulse.inputs:onlyPlayback", False),
("Send.inputs:eventName", "foo"),
("Send.inputs:path", "Test Path"),
("OnCustomEvent1.inputs:eventName", "foo"),
("OnCustomEvent2.inputs:eventName", "foo"),
],
},
)
counter1_controller = og.Controller(og.Controller.attribute("outputs:count", counter1_node))
counter2_controller = og.Controller(og.Controller.attribute("outputs:count", counter2_node))
event1_controller = og.Controller(og.Controller.attribute("outputs:path", event1_node))
event2_controller = og.Controller(og.Controller.attribute("outputs:path", event2_node))
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 0)
# trigger graph once, this will queue up the event for the next evaluation
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
# Note that if this is a push subscription, the receivers will run this frame instead of next
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 0)
# This evaluation should trigger the receivers
await omni.kit.app.get_app().next_update_async()
# Verify that events were received
self.assertEqual(counter1_controller.get(), 1)
self.assertEqual(event1_controller.get(), "Test Path")
self.assertEqual(counter2_controller.get(), 1)
self.assertEqual(event2_controller.get(), "Test Path")
# Verify the contents of the associated bundle
# FIXME: Authored bundle is always empty?
# bundle_contents = og.BundleContents(graph.get_default_graph_context(), event1_node, "outputs:bundle", True)
# self.assertEqual(1, bundle_contents.size)
# Modify the event name one receiver and sender and ensure it still works
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [("Send.inputs:eventName", "bar"), ("OnImpulse.state:enableImpulse", True)],
},
)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# We changed the sender event name, so counter should _not_ have triggered again
self.assertEqual(counter1_controller.get(), 1)
# Change the receiver name to match
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnCustomEvent1.inputs:eventName", "bar")})
await omni.kit.app.get_app().next_update_async()
# trigger send again and verify we get it (1 frame lag for pop)
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 2)
# ----------------------------------------------------------------------
async def test_request_driven_node(self):
"""Test that RequestDriven nodes are computed as expected"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Counter", "omni.graph.action.Counter"),
],
keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False)],
keys.CONNECT: ("OnImpulse.outputs:execOut", "Counter.inputs:execIn"),
},
)
# After several updates, there should have been no compute calls
await controller.evaluate(graph)
await controller.evaluate(graph)
await controller.evaluate(graph)
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
self.assertEqual(counter_controller.get(), 0)
# change OnImpulse state attrib. The node should now request compute
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 1)
# more updates should not result in more computes
await controller.evaluate(graph)
await controller.evaluate(graph)
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 1)
# ----------------------------------------------------------------------
async def test_stage_events(self):
"""Test OnStageEvent"""
controller = og.Controller()
keys = og.Controller.Keys
(_, (_, _, _, counter_node, counter2_node, counter3_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnStageEvent", "omni.graph.action.OnStageEvent"),
("OnStageEvent2", "omni.graph.action.OnStageEvent"),
("OnStageEvent3", "omni.graph.action.OnStageEvent"),
("Counter", "omni.graph.action.Counter"),
("Counter2", "omni.graph.action.Counter"),
("Counter3", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnStageEvent.outputs:execOut", "Counter.inputs:execIn"),
("OnStageEvent2.outputs:execOut", "Counter2.inputs:execIn"),
("OnStageEvent3.outputs:execOut", "Counter3.inputs:execIn"),
],
keys.SET_VALUES: [
("OnStageEvent.inputs:eventName", "Selection Changed"),
("OnStageEvent.inputs:onlyPlayback", False),
("OnStageEvent2.inputs:eventName", "Animation Stop Play"),
("OnStageEvent2.inputs:onlyPlayback", True),
("OnStageEvent3.inputs:eventName", "Animation Start Play"),
("OnStageEvent3.inputs:onlyPlayback", True),
],
},
)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 0)
selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([self.TEST_GRAPH_PATH + "/OnStageEvent"], False)
# 1 frame delay on the pop, 1 frame delay on the compute
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_node)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 0)
# Verify that start/stop events work when only-plackback is true
timeline = omni.timeline.get_timeline_interface()
timeline.set_start_time(1.0)
timeline.set_end_time(10.0)
timeline.play()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 1)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 1)
timeline.stop()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 1)
await controller.evaluate()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 1)
# -----------------------------------------------------------------------
async def test_add_prim_relationship(self):
"""Test AddPrimRelationship"""
controller = og.Controller()
# Check that we can add relationship to a prim and get that relationship
#
# +---------+ +---------------------+
# | ONTICK +-->| AddPrimRelationship +
# +---------+ +---------------------+
#
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("AddRel", "omni.graph.action.AddPrimRelationship"),
],
keys.CREATE_PRIMS: [
("/Test", {}),
("/Target", {}),
],
keys.CONNECT: [("OnTick.outputs:tick", "AddRel.inputs:execIn")],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("AddRel.inputs:path", "/Test"),
("AddRel.inputs:name", "rel"),
("AddRel.inputs:target", "/Target"),
],
},
)
prim = stage.GetPrimAtPath("/Test")
await controller.evaluate()
rel = prim.GetRelationship("rel")
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertTrue(str(targets[0]) == "/Target")
# ----------------------------------------------------------------------
async def test_switch(self):
"""Test the Switch nodes"""
controller = og.Controller()
keys = og.Controller.Keys
# Test that an execution connection is correctly triggering the downstream node once per evaluation
(graph, (_, switch_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Switch", "omni.graph.action.SwitchToken"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Switch.inputs:execIn"),
],
},
)
def add_input(index: int):
controller.create_attribute(
switch_node,
f"inputs:branch{index:02}",
"token",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
)
controller.create_attribute(
switch_node,
f"outputs:output{index:02}",
"execution",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
og.Controller.set(controller.attribute(f"inputs:branch{index:02}", switch_node), f"{index:02}")
for index in range(5):
add_input(index)
for index in range(5):
og.Controller.set(controller.attribute("inputs:value", switch_node), f"{index:02}")
await controller.evaluate(graph)
for index2 in range(5):
expected_val = (
og.ExecutionAttributeState.DISABLED if index2 != index else og.ExecutionAttributeState.ENABLED
)
self.assertEqual(
og.Controller.get(controller.attribute(f"outputs:output{index2:02}", switch_node)), expected_val
)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_compounds.py | """Action Graph with Compounds"""
import carb.events
import omni.graph.core as og
import omni.graph.core._unstable as ogu
import omni.graph.core.tests as ogts
import omni.kit.app
# ======================================================================
class TestActionGraphCompounds(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ------------------------------------------------------------------------
async def test_create_action_subgraph_with_command(self):
"""Validates the create compound subgraph command in an action graph"""
# "Add" will only compute if the subgraph is executed as a push graph OR
# is flattened into the parent graph
# ┌───────────────┐
# │Subgraph │
# ┌─────┐ │ ┌─────┐ │
# │Const├───►────► Add ├───►├────┐
# └─────┘ │ └──▲──┘ │ │
# │ │ │ │
# │ ┌─────┴┐ │ │
# │ │Const2│ │ │
# │ └──────┘ │ │
# │ │ │
# └───────────────┘ │
# ┌───────┐ ┌▼────────────┐
# │OnTick ├──────────────────────►WriteVariable│
# └───────┘ └─────────────┘
controller = og.Controller()
keys = controller.Keys
(graph, (_, _, const_2, add, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Const", "omni.graph.nodes.ConstantInt"),
("Const2", "omni.graph.nodes.ConstantInt"),
("Add", "omni.graph.nodes.Add"),
("WriteVariable", "omni.graph.core.WriteVariable"),
],
keys.CREATE_VARIABLES: [
("int_var", og.Type(og.BaseDataType.INT), 0),
],
keys.CONNECT: [
("Const.inputs:value", "Add.inputs:a"),
("Const2.inputs:value", "Add.inputs:b"),
("Add.outputs:sum", "WriteVariable.inputs:value"),
("OnTick.outputs:tick", "WriteVariable.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("WriteVariable.inputs:variableName", "int_var"),
],
},
)
await og.Controller.evaluate(graph)
self.assertEquals(graph.get_variables()[0].get(graph.get_default_graph_context()), 0)
controller.edit(
self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Const.inputs:value", 22), ("Const2.inputs:value", 20)]}
)
ogu.cmds.ReplaceWithCompoundSubgraph(
nodes=[add.get_prim_path(), const_2.get_prim_path()], compound_name="Subgraph"
)
await og.Controller.evaluate(graph)
self.assertEquals(graph.get_variables()[0].get(graph.get_default_graph_context()), 42.0)
# ------------------------------------------------------------------------
async def test_event_node_in_subgraph(self):
"""
Test that a compute-on-request node inside a subgraph works
"""
controller = og.Controller(update_usd=True)
keys = controller.Keys
(graph, (compound_node,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
(
"CompoundOuter",
{
keys.CREATE_NODES: [
(
"CompoundInner",
{
keys.CREATE_NODES: [
("OnEvent", "omni.graph.action.OnMessageBusEvent"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [("OnEvent.outputs:execOut", "Counter.inputs:execIn")],
keys.SET_VALUES: [
("OnEvent.inputs:onlyPlayback", False),
("OnEvent.inputs:eventName", "testEvent"),
],
},
)
]
},
),
],
},
)
# One compute for the first-time subscribe.
await omni.kit.app.get_app().next_update_async()
msg = carb.events.type_from_string("testEvent")
counter_attr = og.Controller.attribute(
f"{compound_node.get_prim_path()}/Subgraph/CompoundInner/Subgraph/Counter.outputs:count"
)
await og.Controller.evaluate(graph)
self.assertEqual(counter_attr.get(), 0)
omni.kit.app.get_app().get_message_bus_event_stream().push(msg)
# Wait for one kit update to allow the event-push mechanism to trigger the node callback.
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter_attr.get(), 1)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter_attr.get(), 1)
omni.kit.app.get_app().get_message_bus_event_stream().push(msg)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter_attr.get(), 2)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_api.py | """Testing the stability of the API in this module"""
import omni.graph.action as oga
import omni.graph.core.tests as ogts
from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents
# ======================================================================
class _TestOmniGraphActionApi(ogts.OmniGraphTestCase):
_UNPUBLISHED = ["bindings", "ogn", "tests"]
async def test_api(self):
_check_module_api_consistency(oga, self._UNPUBLISHED) # noqa: PLW0212
_check_module_api_consistency(oga.tests, is_test_module=True) # noqa: PLW0212
async def test_api_features(self):
"""Test that the known public API features continue to exist"""
_check_public_api_contents(oga, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212
_check_public_api_contents(oga.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/__init__.py | """There is no public API to this module."""
__all__ = []
scan_for_test_modules = True
"""The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_evaluation_02.py | """Action Graph Evaluation Tests, Part 2"""
from enum import Enum, auto
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from omni.graph.action import get_interface
from pxr import Gf
# ======================================================================
class TestActionGraphEvaluation(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_latent_fan_out(self):
"""Test latent nodes when part of parallel evaluation"""
# +------------+
# +---->|TickCounterA|
# | +------------+
# |
# +--------++ +----------+
# +-> TickA +--->|FinishedA |
# | +---------+ +----------+
# +---------+ +-----------+ |
# |OnImpulse+-->|TickCounter+-+
# +---------+ +-----------+ |
# | +---------+ +----------+
# +>| TickB +--->|FinishedB |
# +--------++ +----------+
# |
# | +------------+
# +---->|TickCounterB|
# +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.Countdown"),
("TickB", "omni.graph.action.Countdown"),
("TickCounter", "omni.graph.action.Counter"),
("TickCounterA", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickA.inputs:execIn"),
("TickCounter.outputs:execOut", "TickB.inputs:execIn"),
("TickA.outputs:tick", "TickCounterA.inputs:execIn"),
("TickB.outputs:tick", "TickCounterB.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, _, _, tick_counter, tick_counter_a, tick_counter_b, finish_counter_a, finish_counter_b) = nodes
def check_counts(t_def, t_a, t_b, f_a, f_b):
for node, expected in (
(tick_counter, t_def),
(tick_counter_a, t_a),
(tick_counter_b, t_b),
(finish_counter_a, f_a),
(finish_counter_b, f_b),
):
count = og.Controller.get(controller.attribute("outputs:count", node))
self.assertEqual(count, expected, node.get_prim_path())
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 0)
await controller.evaluate(graph)
check_counts(1, 1, 1, 0, 0)
await controller.evaluate(graph)
check_counts(1, 2, 2, 0, 0)
await controller.evaluate(graph)
check_counts(1, 2, 2, 1, 1)
# ----------------------------------------------------------------------
async def test_loop_cancel(self):
"""Test loop canceling"""
# Check that a loop can be canceled.
# We set up the loop to run for 7 iterations, but cancel when we hit iteration 2.
#
# +--------+
# +------------->|COUNTER2|
# | finish +--------+
# +---------+ +----------+ +----------+ +-------+ +---------+
# | IMPULSE +-->| FOR-LOOP +--->| COMPARE +--->|BRANCH +--->| COUNTER1|
# +---------+ +----------+ +----------+ +-------+ +---------+
# ^ |
# | cancel |
# +------------------------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, for_loop, _, _, count_1, count_2), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ForLoop", "omni.graph.action.ForLoop"),
("Compare", "omni.graph.nodes.Compare"),
("Branch", "omni.graph.action.Branch"),
("Counter1", "omni.graph.action.Counter"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "ForLoop.inputs:execIn"),
("ForLoop.outputs:loopBody", "Branch.inputs:execIn"),
("ForLoop.outputs:index", "Compare.inputs:a"),
("ForLoop.outputs:finished", "Counter2.inputs:execIn"),
("Compare.outputs:result", "Branch.inputs:condition"),
("Branch.outputs:execFalse", "Counter1.inputs:execIn"),
("Branch.outputs:execTrue", "ForLoop.inputs:breakLoop"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("Compare.inputs:b", 2, "int"),
("Compare.inputs:operation", "=="),
("ForLoop.inputs:stop", 6),
],
},
)
await controller.evaluate(graph)
# Trigger graph once.
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# Verify the loop body only counted 2 times, and finish once.
c_1 = og.Controller.get(og.Controller.attribute("outputs:count", count_1))
c_2 = og.Controller.get(og.Controller.attribute("outputs:count", count_2))
index = og.Controller.get(og.Controller.attribute("outputs:index", for_loop))
self.assertEqual(index, 2)
self.assertEqual(c_1, 2)
self.assertEqual(c_2, 1)
# ----------------------------------------------------------------------
async def test_loop_sideffects(self):
"""Test that nodes in loops can read results of external side effects"""
# +----------+ +---------+ +-------+ +--------------------+
# | OnImpulse+----->| ForLoop +----->| Add +------>| WritePrimAttribute |
# +----------+ +---------+ +-------+ +--------------------+
# ^
# +-----------------+ |
# |ReadPrimAttribute +---+
# +-----------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, prims, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Get", "omni.graph.nodes.ReadPrimAttribute"),
("ForLoop1", "omni.graph.action.ForLoop"),
("Add", "omni.graph.nodes.Add"),
("Set", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: ("/World/Accumulator", {"acc": ("int", 0)}),
keys.SET_VALUES: [
("Get.inputs:name", "acc"),
("Get.inputs:usePath", True),
("Get.inputs:primPath", "/World/Accumulator"),
("ForLoop1.inputs:start", 0),
("ForLoop1.inputs:stop", 5),
("Set.inputs:name", "acc"),
("Set.inputs:usePath", True),
("Set.inputs:primPath", "/World/Accumulator"),
("OnImpulse.inputs:onlyPlayback", False),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "Set.inputs:execIn"),
("Get.outputs:value", "Add.inputs:a"),
("ForLoop1.outputs:value", "Add.inputs:b"),
("Add.outputs:sum", "Set.inputs:value"),
],
},
)
await controller.evaluate(graph)
# Trigger graph evaluation once.
# Should result in sum = 0 + 0 + 1 + 2 + 3 + 4.
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("OnImpulse.state:enableImpulse", True)]})
await controller.evaluate(graph)
self.assertEqual(prims[0].GetAttribute("acc").Get(), 10)
# ----------------------------------------------------------------------
async def test_nested_forloop(self):
"""Test nested ForLoop nodes"""
keys = og.Controller.Keys
controller = og.Controller()
(graph, (_, _, _, _, _, _, write_node), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Const", "omni.graph.nodes.ConstantInt2"),
("Add", "omni.graph.nodes.Add"),
("Branch", "omni.graph.action.Branch"),
("For", "omni.graph.action.ForLoop"),
("For2", "omni.graph.action.ForLoop"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: (
"/World/TestPrim",
{
"val1": ("int[2]", Gf.Vec2i(1, 1)),
},
),
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Const.inputs:value", [1, 2]),
("Write1.inputs:name", "val1"),
("Write1.inputs:primPath", "/World/TestPrim"),
("Write1.inputs:usePath", True),
("For.inputs:stop", 3),
("For2.inputs:start", 4),
("For2.inputs:step", 2),
("For2.inputs:stop", 10),
("Branch.inputs:condition", True),
],
keys.CONNECT: [
("OnTick.outputs:tick", "For.inputs:execIn"),
("For.outputs:loopBody", "Branch.inputs:execIn"),
("Branch.outputs:execTrue", "For2.inputs:execIn"),
("For2.outputs:loopBody", "Write1.inputs:execIn"),
("For2.outputs:value", "Add.inputs:a"),
("Const.inputs:value", "Add.inputs:b"),
("Add.outputs:sum", "Write1.inputs:value"),
],
},
)
await controller.evaluate(graph)
context = omni.usd.get_context()
stage = context.get_stage()
# For2 should loop over the range [4, 6, 8, 10).
self.assertEqual(9, write_node.get_compute_count())
# [1, 2] + 8 = [9, 10].
self.assertListEqual([9, 10], list(stage.GetAttributeAtPath("/World/TestPrim.val1").Get()))
# ----------------------------------------------------------------------
async def test_om_63924(self):
"""Test OM-63924 bug is fixed"""
# The problem here was that if there was fan in to a node which was
# computed once and then totally unwound before the other history was
# processed, there would never be a deferred activation and so the 2nd
# compute would never happen. Instead we want to only unwind one history
# at a time to ensure each one is fully evaluated.
i = 2
class OnForEachEventPy:
"""Helper Python node that implements ForEach logic"""
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
"""Compute method"""
nonlocal i
inputs_go = node.get_attribute("inputs:go")
go_val = og.Controller.get(inputs_go)
if not go_val:
return True
if i > 0:
og.Controller.set(
node.get_attribute("outputs:execOut"), og.ExecutionAttributeState.ENABLED_AND_PUSH
)
og.Controller.set(node.get_attribute("outputs:syncValue"), i)
i -= 1
return True
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.test.OnForEachEventPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input(
"inputs:go",
"bool",
False,
)
node_type.add_output("outputs:execOut", "execution", True)
node_type.add_output("outputs:syncValue", "uint64", True)
return True
og.register_node_type(OnForEachEventPy, 1)
class NoOpPy:
"""Helper Python node that performs no internal operation"""
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
"""Compute method"""
og.Controller.set(node.get_attribute("outputs:execOut"), og.ExecutionAttributeState.ENABLED)
return True
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.test.NoOpPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input(
"inputs:execIn",
"execution",
True,
)
node_type.add_output("outputs:execOut", "execution", True)
return True
og.register_node_type(NoOpPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (for_each, _, _, _, _, no_op_2), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("PostProcessDispatcher", "omni.graph.test.OnForEachEventPy"),
("TSA1", "omni.graph.action.SyncGate"),
("TSA0", "omni.graph.action.SyncGate"),
("TestSyncAccum", "omni.graph.action.SyncGate"),
("TestPrimBbox", "omni.graph.test.NoOpPy"),
("NoOpPy2", "omni.graph.test.NoOpPy"),
],
keys.CONNECT: [
("PostProcessDispatcher.outputs:execOut", "TSA0.inputs:execIn"),
("PostProcessDispatcher.outputs:execOut", "TSA1.inputs:execIn"),
("TSA1.outputs:execOut", "TestSyncAccum.inputs:execIn"),
("TSA0.outputs:execOut", "TestPrimBbox.inputs:execIn"),
("TestPrimBbox.outputs:execOut", "TestSyncAccum.inputs:execIn"),
("TestSyncAccum.outputs:execOut", "NoOpPy2.inputs:execIn"),
("PostProcessDispatcher.outputs:syncValue", "TSA1.inputs:syncValue"),
("PostProcessDispatcher.outputs:syncValue", "TSA0.inputs:syncValue"),
("PostProcessDispatcher.outputs:syncValue", "TestSyncAccum.inputs:syncValue"),
],
},
)
og.Controller.set(controller.attribute("inputs:go", for_each), True)
await controller.evaluate(graph)
# Verify the final sync gate triggered due to being computed 2x.
exec_out = og.Controller.get(controller.attribute("outputs:execOut", no_op_2))
self.assertEqual(exec_out, og.ExecutionAttributeState.ENABLED)
# ----------------------------------------------------------------------
async def test_retrigger_latent(self):
"""Test that latent nodes can be re-triggered"""
want_debug = False
e_state = og.ExecutionAttributeState
tick_count = 0
boop_count = 0
exec_in_latent_count = 0
max_ticks = 20
class CancelTickerPy:
"""Helper node type which does latent ticking and can be canceled, and has an independent counter "boop" """
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
"""Compute method"""
nonlocal tick_count
nonlocal boop_count
nonlocal exec_in_latent_count
exec_in = node.get_attribute("inputs:execIn")
exec_in_val = og.Controller.get(exec_in)
cancel = node.get_attribute("inputs:cancel")
cancel_val = og.Controller.get(cancel)
boop = node.get_attribute("inputs:boop")
boop_val = og.Controller.get(boop)
if want_debug:
print(f"### {tick_count} execIn={exec_in_val} cancel={cancel_val} boop={boop_val}")
if cancel_val == e_state.ENABLED:
# Finish latent by cancel.
og.Controller.set(node.get_attribute("outputs:canceled"), e_state.LATENT_FINISH)
self.assertEqual(exec_in_val, e_state.DISABLED)
self.assertEqual(boop_val, e_state.DISABLED)
tick_count = 0
return True
if exec_in_val == e_state.ENABLED:
self.assertEqual(cancel_val, e_state.DISABLED)
self.assertEqual(boop_val, e_state.DISABLED)
if tick_count > 0:
# execIn triggered while in latent - should not be possible.
exec_in_latent_count += 1
else:
og.Controller.set(node.get_attribute("outputs:tick"), e_state.LATENT_PUSH)
return True
# We are ticking.
self.assertEqual(cancel_val, e_state.DISABLED)
tick_count += 1
if tick_count < max_ticks:
og.Controller.set(node.get_attribute("outputs:tick"), e_state.ENABLED)
else:
# Finish latent naturally.
og.Controller.set(node.get_attribute("outputs:execOut"), e_state.LATENT_FINISH)
tick_count = 0
if boop_val == e_state.ENABLED:
# We get here during latent ticking, if the boop input is enabled.
self.assertEqual(exec_in_val, e_state.DISABLED)
self.assertEqual(cancel_val, e_state.DISABLED)
boop_count += 1
return True
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.test.CancelTickerPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input(
"inputs:execIn",
"execution",
True,
)
node_type.add_input(
"inputs:cancel",
"execution",
True,
)
node_type.add_input(
"inputs:boop",
"execution",
True,
)
node_type.add_output("outputs:tick", "execution", True)
node_type.add_output("outputs:canceled", "execution", True)
node_type.add_output("outputs:execOut", "execution", True)
return True
og.register_node_type(CancelTickerPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (ticker, start, _, cancel, boop, _, _, counter), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Ticker", "omni.graph.test.CancelTickerPy"),
("Start", "omni.graph.action.OnImpulseEvent"),
("Start2", "omni.graph.action.OnImpulseEvent"),
("Cancel", "omni.graph.action.OnImpulseEvent"),
("Boop", "omni.graph.action.OnImpulseEvent"),
("Once", "omni.graph.action.Once"),
("Once2", "omni.graph.action.Once"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("Start.outputs:execOut", "Ticker.inputs:execIn"),
("Start2.outputs:execOut", "Ticker.inputs:execIn"),
("Cancel.outputs:execOut", "Once.inputs:execIn"),
("Once.outputs:once", "Ticker.inputs:cancel"),
("Once.outputs:after", "Ticker.inputs:cancel"),
("Cancel.outputs:execOut", "Once2.inputs:execIn"),
("Boop.outputs:execOut", "Ticker.inputs:boop"),
("Once2.outputs:once", "Ticker.inputs:cancel"),
("Once2.outputs:after", "Ticker.inputs:cancel"),
("Ticker.outputs:tick", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("Start.inputs:onlyPlayback", False),
("Start2.inputs:onlyPlayback", False),
("Cancel.inputs:onlyPlayback", False),
("Boop.inputs:onlyPlayback", False),
],
},
)
# Cancel, check nothing happens.
og.Controller.set(controller.attribute("state:enableImpulse", cancel), True)
await controller.evaluate(graph)
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.DISABLED)
# Start ticking.
og.Controller.set(controller.attribute("state:enableImpulse", start), True)
await controller.evaluate(graph) # Starts latent state.
await controller.evaluate(graph) # Tick 1
self.assertEqual(tick_count, 1)
# Verify the tick has started.
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.ENABLED)
await controller.evaluate(graph) # Tick 2
self.assertEqual(tick_count, 2)
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.ENABLED)
await controller.evaluate(graph) # Tick 3
self.assertEqual(tick_count, 3)
# Boop - node keeps ticking.
og.Controller.set(controller.attribute("state:enableImpulse", boop), True)
# Boop will trigger a compute, which increments boop + ticks AND the normal latent tick.
await controller.evaluate(graph)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 5)
# Now check that the next tick can run WITHOUT inputs:boop being high.
await controller.evaluate(graph)
self.assertEqual(boop_count, 1) # No change in boop count (OM-64856).
self.assertEqual(tick_count, 6)
# Now check that we can't re-trigger execIn.
self.assertEqual(exec_in_latent_count, 0)
og.Controller.set(controller.attribute("state:enableImpulse", start), True)
# Start will not trigger any compute because the node is latent.
await controller.evaluate(graph)
self.assertEqual(exec_in_latent_count, 0)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 7)
# Unset the impulse.
og.Controller.set(controller.attribute("state:enableImpulse", start), False)
# Now check the normal tick proceeds as normal.
await controller.evaluate(graph)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 8)
# Cancel.
counter_attr = controller.attribute("outputs:count", counter)
count_0 = og.Controller.get(counter_attr)
og.Controller.set(controller.attribute("state:enableImpulse", cancel), True)
await controller.evaluate(graph) # Latent finish.
await controller.evaluate(graph) # No action.
await controller.evaluate(graph) # No action.
count_1 = og.Controller.get(counter_attr)
self.assertEqual(count_0 + 1, count_1)
# ----------------------------------------------------------------------
async def test_simple_expression(self):
"""Test ActionGraph simple expression of add nodes"""
keys = og.Controller.Keys
controller = og.Controller()
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Const", "omni.graph.nodes.ConstantDouble3"),
("Add", "omni.graph.nodes.Add"),
("Add2", "omni.graph.nodes.Add"),
("Add3", "omni.graph.nodes.Add"),
("PostAdd", "omni.graph.nodes.Add"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
("Write2", "omni.graph.nodes.WritePrimAttribute"),
("Write3", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: (
"/World/TestPrim",
{
"val1": ("double[3]", Gf.Vec3d(1, 1, 1)),
"val2": ("double[3]", Gf.Vec3d(2, 2, 2)),
"val3": ("double[3]", Gf.Vec3d(2, 2, 2)),
},
),
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Const.inputs:value", [1, 2, 3]),
("Write1.inputs:name", "val1"),
("Write1.inputs:primPath", "/World/TestPrim"),
("Write1.inputs:usePath", True),
("Write2.inputs:name", "val2"),
("Write2.inputs:primPath", "/World/TestPrim"),
("Write2.inputs:usePath", True),
("Write3.inputs:name", "val3"),
("Write3.inputs:primPath", "/World/TestPrim"),
("Write3.inputs:usePath", True),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Write1.inputs:execIn"),
("Write1.outputs:execOut", "Write2.inputs:execIn"),
("Write2.outputs:execOut", "Write3.inputs:execIn"),
("Const.inputs:value", "Add.inputs:a"),
("Const.inputs:value", "Add.inputs:b"),
("Const.inputs:value", "Add2.inputs:a"),
("Const.inputs:value", "Add2.inputs:b"),
("Add.outputs:sum", "Add3.inputs:a"),
("Add2.outputs:sum", "Add3.inputs:b"),
("Add3.outputs:sum", "Write1.inputs:value"),
("Add3.outputs:sum", "Write2.inputs:value"),
("Add3.outputs:sum", "PostAdd.inputs:a"),
("Add3.outputs:sum", "PostAdd.inputs:b"),
("PostAdd.outputs:sum", "Write3.inputs:value"),
],
},
)
await controller.evaluate(graph)
context = omni.usd.get_context()
stage = context.get_stage()
await omni.kit.app.get_app().next_update_async()
self.assertListEqual([4, 8, 12], list(stage.GetAttributeAtPath("/World/TestPrim.val1").Get()))
self.assertListEqual([4, 8, 12], list(stage.GetAttributeAtPath("/World/TestPrim.val2").Get()))
self.assertListEqual([8, 16, 24], list(stage.GetAttributeAtPath("/World/TestPrim.val3").Get()))
# ----------------------------------------------------------------------
async def test_stateful_flowcontrol_evaluation(self):
"""Test that stateful flow control nodes are fully evaluated"""
# b
# +----------+ +---------+
# +--->| Sequence +-->|Counter1 |
# | +----------+ +---------+
# +-----------+ |
# | OnImpulse +-+
# +-----------+ |
# | +----------+ +----------+
# +--->| ForLoop1 +-->| Counter2 |
# +----------+ +----------+
# finished
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, counter1_node, _, counter2_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Sequence", "omni.graph.action.Sequence"),
("Counter1", "omni.graph.action.Counter"),
("ForLoop1", "omni.graph.action.ForLoop"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Sequence.inputs:execIn"),
("Sequence.outputs:b", "Counter1.inputs:execIn"),
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:finished", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False), ("ForLoop1.inputs:stop", 10)],
},
)
await controller.evaluate(graph)
# Trigger graph once.
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# Verify that counter was called in spite of sequence 'a' being disconnected.
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter1_node)), 1)
# Verify that counter was called in spite of there being no loopBody - execution evaluator has to still trigger
# the loop 11 times despite there being no downstream connection.
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 1)
# ----------------------------------------------------------------------
async def test_unresolve_on_disconnect(self):
"""Tests unresolving attribs when action node is disconnected"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, for_each_node, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("ForEach", "omni.graph.action.ForEach"),
("IntArrayPrim", "omni.graph.nodes.ReadPrimAttribute"),
("IntSinkPrim", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: [
("/World/IntArray", {"myintarray": ("int[]", range(10))}),
("/World/IntSink", {"myint": ("int", 0)}),
],
keys.CONNECT: [
("OnTick.outputs:tick", "ForEach.inputs:execIn"),
("IntArrayPrim.outputs:value", "ForEach.inputs:arrayIn"),
("ForEach.outputs:element", "IntSinkPrim.inputs:value"),
],
keys.SET_VALUES: [
("IntArrayPrim.inputs:name", "myintarray"),
("IntArrayPrim.inputs:primPath", "/World/IntArray"),
("IntArrayPrim.inputs:usePath", True),
("IntSinkPrim.inputs:name", "myint"),
("IntSinkPrim.inputs:primPath", "/World/IntSink"),
("IntSinkPrim.inputs:usePath", True),
("OnTick.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
array_attr = controller.attribute("inputs:arrayIn", for_each_node)
element_attr = controller.attribute("outputs:element", for_each_node)
self.assertEqual(element_attr.get_resolved_type(), og.Type(og.BaseDataType.INT, 1, 0))
# When we disconnect all data connections, they should unresolve even though we still
# have the execution connection in place.
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.DISCONNECT: [
("IntArrayPrim.outputs:value", "ForEach.inputs:arrayIn"),
("ForEach.outputs:element", "IntSinkPrim.inputs:value"),
]
},
)
await controller.evaluate(graph)
self.assertEqual(array_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN))
self.assertEqual(element_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN))
async def test_actiongraph_abi(self):
"""Tests IActionGraph ABI functions"""
i_ag = get_interface()
g_exec_out = 0
class State(Enum):
ENABLED = auto()
ENABLED_AND_PUSH = auto()
START = auto()
END = auto()
class _TestActionGraphPy:
"""Helper node to test behavior"""
class _State:
val = None
instance_states = {}
@staticmethod
def initialize(context, node):
_TestActionGraphPy.instance_states[node] = _TestActionGraphPy._State()
@staticmethod
def compute(_: og.GraphContext, node: og.Node) -> bool:
"""Compute method"""
nonlocal g_exec_out
if not i_ag.get_latent_state():
self.assertTrue(i_ag.get_execution_enabled("inputs:execIn"))
self.assertFalse(i_ag.get_execution_enabled("inputs:execUnused"))
self.assertFalse(i_ag.get_execution_enabled("inputs:boolUnused"))
state = _TestActionGraphPy.instance_states[node]
if state.val == State.ENABLED_AND_PUSH:
# Must be re-entering
i_ag.set_execution_enabled("outputs:finished_from_pushed")
state.val = None
return True
if state.val == State.START:
# Must be in latent state tick
self.assertTrue(i_ag.get_latent_state())
i_ag.end_latent_state()
i_ag.set_execution_enabled("outputs:finished_from_latent")
state.val = None
return True
if g_exec_out == State.ENABLED:
i_ag.set_execution_enabled("outputs:execOut")
elif g_exec_out == State.ENABLED_AND_PUSH:
i_ag.set_execution_enabled_and_pushed("outputs:execOut")
elif g_exec_out == State.START:
self.assertFalse(i_ag.get_latent_state())
i_ag.start_latent_state()
elif g_exec_out == State.END:
i_ag.end_latent_state()
state.val = g_exec_out
return True
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.action._TestActionGraphPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input("inputs:execIn", "execution", True)
node_type.add_input("inputs:execUnused", "execution", True)
node_type.add_input("inputs:boolUnused", "bool", True)
node_type.add_output("outputs:execOut", "execution", True)
node_type.add_output("outputs:finished_from_latent", "execution", True)
node_type.add_output("outputs:finished_from_pushed", "execution", True)
og.register_node_type(_TestActionGraphPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Test", "omni.graph.action._TestActionGraphPy"),
("CounterOut", "omni.graph.action.Counter"),
("CounterLatent", "omni.graph.action.Counter"),
("CounterPushed", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Test.inputs:execIn"),
("Test.outputs:execOut", "CounterOut.inputs:execIn"),
("Test.outputs:finished_from_latent", "CounterLatent.inputs:execIn"),
("Test.outputs:finished_from_pushed", "CounterPushed.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 0)
g_exec_out = State.ENABLED
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 1)
g_exec_out = State.ENABLED_AND_PUSH
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 2)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterPushed.outputs:count"), 1)
g_exec_out = State.START
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 2)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterPushed.outputs:count"), 1)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterLatent.outputs:count"), 0)
g_exec_out = State.END
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 2)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterPushed.outputs:count"), 1)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterLatent.outputs:count"), 1)
with ogts.ExpectedError():
with self.assertRaises(RuntimeError):
i_ag.start_latent_state()
# ------------------------------------------------------------------------
async def test_node_self_destruction(self):
"""Test that we don't crash if a very bad node causes a resync of the stage"""
# Executing this node may cause errors and fail the test as the underlying
# authoring node is destroyed while the task is executing. We just verify that only
# the expected error is generated.
class _TestBadNodePy:
@staticmethod
def compute(_: og.GraphContext, node: og.Node) -> bool:
context = omni.usd.get_context()
stage = context.get_stage()
stage.RemovePrim(node.get_prim_path())
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.action._TestBadNodePy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input("inputs:execIn", "execution", True)
node_type.add_output("outputs:execOut", "execution", True)
og.register_node_type(_TestBadNodePy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Test", "omni.graph.action._TestBadNodePy"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Test.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
},
)
with ogts.ExpectedError(): # Authoring node for Test was lost
await controller.evaluate(graph)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_nodes_01.py | """Action Graph Node Tests, Part 1"""
import time
import carb
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.app
import omni.kit.test
import omni.usd
from omni.graph.core import ThreadsafetyTestUtils
from pxr import Gf, OmniGraphSchemaTools, Sdf, Vt
# ======================================================================
class TestActionGraphNodes(ogts.OmniGraphTestCase):
"""Tests action graph node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
keys = og.Controller.Keys
E = og.ExecutionAttributeState.ENABLED
D = og.ExecutionAttributeState.DISABLED
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
# -----------------------------------------------------------------------
async def test_addprimrelationship_node(self):
"""Test AddPrimRelationship node"""
# Check that we can add a relationship to a prim and get that relationship.
#
# +---------+ +---------------------+
# | ONTICK +-->| AddPrimRelationship +
# +---------+ +---------------------+
#
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("AddRel", "omni.graph.action.AddPrimRelationship"),
],
self.keys.CREATE_PRIMS: [
("/Test", {}),
("/Target", {}),
],
self.keys.CONNECT: [("OnTick.outputs:tick", "AddRel.inputs:execIn")],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("AddRel.inputs:path", "/Test"),
("AddRel.inputs:name", "rel"),
("AddRel.inputs:target", "/Target"),
],
},
)
prim = stage.GetPrimAtPath("/Test")
await og.Controller.evaluate()
rel = prim.GetRelationship("rel")
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertTrue(str(targets[0]) == "/Target")
# ----------------------------------------------------------------------
# The Branch node has a built-in test construct in its .ogn file located at ../../nodes/OgnBranch.ogn
# (relative to the source location of the currently-opened testing script) AND is used in other testing
# methods, so we skip adding extra node-specific tests for it here.
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_counter_node(self, test_instance_id: int = 0):
"""Test Counter node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (ontick_node, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: ("OnTick.outputs:tick", "Counter.inputs:execIn"),
},
)
# Obtain necessary attributes.
in_exec_attr = counter_node.get_attribute("inputs:execIn")
in_reset_attr = counter_node.get_attribute("inputs:reset")
state_cnt_attr = counter_node.get_attribute("state:count")
out_exec_attr = counter_node.get_attribute("outputs:execOut")
out_cnt_attr = counter_node.get_attribute("outputs:count")
out_tick_attr = ontick_node.get_attribute("outputs:tick")
# Check that the counter node gets correctly incremented when executing.
self.assertEqual(state_cnt_attr.get(), 0)
self.assertEqual(out_cnt_attr.get(), 0)
self.assertEqual(out_exec_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(state_cnt_attr.get(), 1)
self.assertEqual(out_cnt_attr.get(), 1)
self.assertEqual(out_exec_attr.get(), self.E)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(state_cnt_attr.get(), 2)
self.assertEqual(out_cnt_attr.get(), 2)
self.assertEqual(out_exec_attr.get(), self.E)
# Check that the counter node doesn't increment when not executing.
og.Controller.disconnect(
out_tick_attr,
in_exec_attr,
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(state_cnt_attr.get(), 2)
self.assertEqual(out_cnt_attr.get(), 2)
self.assertEqual(out_exec_attr.get(), self.E)
# Check that the reset flag for the Counter node instance works correctly when
# inputs:execIn is set to 0 (i.e. when the Counter node is NOT supposed to be
# executing).
og.Controller.connect(out_tick_attr, in_reset_attr)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(state_cnt_attr.get(), 0)
self.assertEqual(out_cnt_attr.get(), 0)
self.assertEqual(out_exec_attr.get(), self.E)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_delay_node(self, test_instance_id: int = 0):
"""Test Delay node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_impulse_node, _, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Delay", "omni.graph.action.Delay"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnImpulse.outputs:execOut", "Delay.inputs:execIn"),
("Delay.outputs:finished", "Counter.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("Delay.inputs:duration", 0.01),
],
},
)
# Obtain necessary attributes.
out_cnt_attr = counter_node.get_attribute("outputs:count")
state_enable_impulse_attr = on_impulse_node.get_attribute("state:enableImpulse")
# Trigger the graph(s) once.
state_enable_impulse_attr.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Downstream execution is delayed, so the counter node won't be incremented.
self.assertEqual(out_cnt_attr.get(), 0)
# Wait to ensure that the delay finishes before checking that the counter node
# has indeed been incremented.
time.sleep(0.02)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(out_cnt_attr.get(), 1)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_flipflop_node(self, test_instance_id: int = 0):
"""Test FlipFlop node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(graph, (_, flip_flop_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: (
"OnTick.outputs:tick",
"FlipFlop.inputs:execIn",
),
},
)
# Obtain necessary attributes.
out_a_attr = flip_flop_node.get_attribute("outputs:a")
out_b_attr = flip_flop_node.get_attribute("outputs:b")
out_isa_attr = flip_flop_node.get_attribute("outputs:isA")
# First eval, 'a'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.D)
self.assertTrue(out_isa_attr.get())
# Second eval 'b'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.E)
self.assertFalse(out_isa_attr.get())
# Third eval 'a'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.D)
self.assertTrue(out_isa_attr.get())
# Test that non-usd-backed FlipFlop nodes correctly
# set their execution-type attributes.
# Make sure that the node paths are prefaced with the path to the
# graph that they should reside in (so that each node creation command
# can be processed to produce unique nodes for each test instance)!
_, on_tick_no_usd = og.cmds.CreateNode(
graph=graph,
node_path=f"{graph_path}/OnTickNoUSD",
node_type="omni.graph.action.OnTick",
create_usd=False,
)
_, flip_flop_no_usd = og.cmds.CreateNode(
graph=graph,
node_path=f"{graph_path}/FlipFlopNoUSD",
node_type="omni.graph.action.FlipFlop",
create_usd=False,
)
# Obtain necessary attributes.
out_a_attr = flip_flop_no_usd.get_attribute("outputs:a")
out_b_attr = flip_flop_no_usd.get_attribute("outputs:b")
out_isa_attr = flip_flop_no_usd.get_attribute("outputs:isA")
on_tick_no_usd.get_attribute("inputs:onlyPlayback").set(False)
# Make sure that the node attribute paths are prefaced with the graph
# path that they reside in (so that each instanced node attribute can
# be uniquely processed)!
og.cmds.ConnectAttrs(
src_attr=f"{graph_path}/OnTickNoUSD.outputs:tick",
dest_attr=f"{graph_path}/FlipFlopNoUSD.inputs:execIn",
modify_usd=False,
)
# First eval, 'a'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.D)
self.assertTrue(out_isa_attr.get())
# Second eval 'b'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.E)
self.assertFalse(out_isa_attr.get())
# Third eval 'a'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.D)
self.assertTrue(out_isa_attr.get())
# ----------------------------------------------------------------------
# The ForEach node has a built-in test construct in its .ogn file located at ../../nodes/OgnForEach.ogn
# (relative to the source location of the currently-opened testing script), so we skip adding extra
# node-specific tests for it here.
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_forloop_node(self, test_instance_id: int = 0):
"""Test ForLoop node"""
context = omni.usd.get_context()
stage = context.get_stage()
# Since we want to use the same prim across all graph instances in the
# thread-safety test, we add it to the threading cache like so:
prim = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim("/World/TestPrim"))
ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
prim.CreateAttribute("val1", Sdf.ValueTypeNames.Int2, False).Set(Gf.Vec2i(1, 1)),
)
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (_, _, _, _, _, _, write_node, finish_counter), _, _) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Const", "omni.graph.nodes.ConstantInt2"),
("StopNum", "omni.graph.nodes.ConstantInt"),
("Add", "omni.graph.nodes.Add"),
("Branch", "omni.graph.action.Branch"),
("For", "omni.graph.action.ForLoop"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
("FinishCounter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Const.inputs:value", [1, 2]),
("StopNum.inputs:value", 3),
("Write1.inputs:name", "val1"),
("Write1.inputs:primPath", "/World/TestPrim"),
("Write1.inputs:usePath", True),
("Branch.inputs:condition", True),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "For.inputs:execIn"),
("StopNum.inputs:value", "For.inputs:stop"),
("For.outputs:loopBody", "Branch.inputs:execIn"),
("For.outputs:finished", "FinishCounter.inputs:execIn"),
("Branch.outputs:execTrue", "Write1.inputs:execIn"),
("For.outputs:value", "Add.inputs:a"),
("Const.inputs:value", "Add.inputs:b"),
("Add.outputs:sum", "Write1.inputs:value"),
],
},
)
# Evaluate the graph(s).
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertListEqual([3, 4], list(stage.GetAttributeAtPath("/World/TestPrim.val1").Get()))
self.assertEqual(3, write_node.get_compute_count())
self.assertEqual(1, finish_counter.get_compute_count())
# This tests make sure that a for loop writing arrays to diferent prims
# work as expected (OM-84129)
async def test_foreach_node_write_multiple_prim(self, test_instance_id: int = 0):
"""Test the foreach node writing arrays to output prims"""
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, _, (prim1, prim2), _) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_PRIMS: [
("/World/Prim1", {"graph_output": ("Int[]", [])}),
("/World/Prim2", {"graph_output": ("Int[]", [])}),
],
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("For", "omni.graph.action.ForEach"),
("Write", "omni.graph.nodes.WritePrimAttribute"),
("MakeArray", "omni.graph.nodes.ConstructArray"),
],
self.keys.SET_VALUES: [
("For.inputs:arrayIn", {"type": "token[]", "value": ["/World/Prim1", "/World/Prim2"]}),
("OnTick.inputs:onlyPlayback", False),
("Write.inputs:name", "graph_output"),
("Write.inputs:usePath", True),
("Write.inputs:usdWriteBack", True),
("MakeArray.inputs:arraySize", 1),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "For.inputs:execIn"),
("For.outputs:loopBody", "Write.inputs:execIn"),
("For.outputs:element", "Write.inputs:primPath"),
("For.outputs:arrayIndex", "MakeArray.inputs:input0"),
("MakeArray.outputs:array", "Write.inputs:value"),
],
},
)
await omni.kit.app.get_app().next_update_async()
prim1_out = prim1.GetAttribute("graph_output")
prim2_out = prim2.GetAttribute("graph_output")
self.assertEqual(prim1_out.Get(), Vt.IntArray([0]))
self.assertEqual(prim2_out.Get(), Vt.IntArray([1]))
# ----------------------------------------------------------------------
# The Gate node has a built-in test construct in its .ogn file located at ../../nodes/OgnGate.ogn
# (relative to the source location of the currently-opened testing script) AND is used in other
# testing methods, so we skip adding extra node-specific tests for it here.
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_multigate_node(self, test_instance_id: int = 0):
"""Test Multigate node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
(_, (_, multigate_node), _, _) = og.Controller.edit(
{"graph_path": graph_path, "evaluator_name": "execution"},
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Multigate", "omni.graph.action.Multigate"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Multigate.inputs:execIn"),
],
},
)
# Add 5 extra outputs to the Multigate node.
for i in range(1, 6):
og.Controller.create_attribute(
multigate_node,
f"outputs:output{i}",
og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
# Obtain necessary attributes.
out_attr_0 = multigate_node.get_attribute("outputs:output0")
out_attr_1 = multigate_node.get_attribute("outputs:output1")
out_attr_2 = multigate_node.get_attribute("outputs:output2")
out_attr_3 = multigate_node.get_attribute("outputs:output3")
out_attr_4 = multigate_node.get_attribute("outputs:output4")
out_attr_5 = multigate_node.get_attribute("outputs:output5")
# Check that the Multigate node correctly cycles through each of its outputs.
# Note that we trigger an execution through the Multigate node via the OnTick node,
# whose onlyPlayback input we've set to False in order to trigger an execution each
# time we evaluate the graph(s).
for i in range(0, 6):
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 0) % 6}").get(), self.E)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 1) % 6}").get(), self.D)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 2) % 6}").get(), self.D)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 3) % 6}").get(), self.D)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 4) % 6}").get(), self.D)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 5) % 6}").get(), self.D)
# Next try removing some output attributes during evaluation and test if the
# Multigate node correctly cycles through.
for _ in range(4):
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.D)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.E)
self.assertEqual(out_attr_4.get(), self.D)
self.assertEqual(out_attr_5.get(), self.D)
multigate_node.remove_attribute("outputs:output4")
# The Multigate node cycles back to 0 instead of going to 5 since it thinks that it's
# reached the end of its outputs list (i.e. it expects to jump from pin 3 to 4, but b/c
# there is no such pin it goes back to 0 rather than 5).
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_attr_0.get(), self.E)
self.assertEqual(out_attr_1.get(), self.D)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.D)
self.assertEqual(out_attr_5.get(), self.D)
# Further showing that executing 4 times brings us back to pin 0 rather than pin 5.
for _ in range(4):
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_attr_0.get(), self.E)
self.assertEqual(out_attr_1.get(), self.D)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.D)
self.assertEqual(out_attr_5.get(), self.D)
# Execute the graph(s) once, then remove the currently-enabled output pin. The Multigate node will think
# that it's reached the end of the outputs list, and cycle back. Because we removed pin 1, it'll go
# back to pin 0 and never cycle through the other outputs since it cannot make the jump from
# pin 0 to 2 (as mentioned previously).
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
multigate_node.remove_attribute("outputs:output1")
for _ in range(3):
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_attr_0.get(), self.E)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.D)
self.assertEqual(out_attr_5.get(), self.D)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_multisequence_node(self, test_instance_id: int = 0):
"""Test Multisequence node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(
_,
(on_tick_node, multisequence_node, counter0_node, counter1_node, counter2_node),
_,
_,
) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Multisequence", "omni.graph.action.Multisequence"),
("Counter0", "omni.graph.action.Counter"),
("Counter1", "omni.graph.action.Counter"),
("Counter2", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Multisequence.inputs:execIn"),
],
},
)
# Add 3 extra outputs to the Multisequence node.
for j in range(1, 4):
og.Controller.create_attribute(
multisequence_node,
f"outputs:output{j}",
og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
# Obtain necessary attributes.
out_attr_0 = multisequence_node.get_attribute("outputs:output0")
out_attr_1 = multisequence_node.get_attribute("outputs:output1")
out_attr_2 = multisequence_node.get_attribute("outputs:output2")
out_attr_3 = multisequence_node.get_attribute("outputs:output3")
in_exec_attr_0 = counter0_node.get_attribute("inputs:execIn")
in_exec_attr_1 = counter1_node.get_attribute("inputs:execIn")
in_exec_attr_2 = counter2_node.get_attribute("inputs:execIn")
out_cnt_attr_0 = counter0_node.get_attribute("outputs:count")
out_cnt_attr_1 = counter1_node.get_attribute("outputs:count")
out_cnt_attr_2 = counter2_node.get_attribute("outputs:count")
in_onlyplayback_attr = on_tick_node.get_attribute("inputs:onlyPlayback")
# Connect Multisequence node output attributes to the counter nodes.
og.Controller.connect(out_attr_0, in_exec_attr_0)
og.Controller.connect(out_attr_2, in_exec_attr_1)
og.Controller.connect(out_attr_1, in_exec_attr_2)
# Check that the Multisequence node correctly executes through its outputs when input
# execution is enabled via the OnTick node. This is done by checking whether
# each counter has been incremented by 1, and if the last output pin on the
# Multisequence node remains enabled (regardless of the fact that it's not connected
# downstream).
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 1)
self.assertEqual(out_cnt_attr_1.get(), 1)
self.assertEqual(out_cnt_attr_2.get(), 1)
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.D)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.E)
# Connect the Counter2 node to another Multisequence output pin.
og.Controller.connect(out_attr_3, in_exec_attr_2)
# Once again evaluate the graph(s). In this situation the Counter2 node should be incremented twice
# (since it's connected to 2 separate Multisequence output pins). Also Multisequence output pins
# 1 AND 3 should both be enabled by the end of the execution; this is because pin 3 would
# typically be the last output that gets enabled, but because pin 3 shares a downstream
# node with pin 1 (that node being Counter2), both outputs need to be enabled by the end.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 2)
self.assertEqual(out_cnt_attr_1.get(), 2)
self.assertEqual(out_cnt_attr_2.get(), 3)
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.E)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.E)
# Set the OnTick node to only trigger downstream execution when playback is enabled; check
# that in this situation the Multisequence node correctly skips executing through its outputs
# (i.e. that the Counter nodes don't get incremented). The state of the Multisequence's output
# pins should not have changed since the last graph evaluation.
in_onlyplayback_attr.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 2)
self.assertEqual(out_cnt_attr_1.get(), 2)
self.assertEqual(out_cnt_attr_2.get(), 3)
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.E)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.E)
# Try removing an output attribute from the Multisequence node, check that all other
# outputs that come before in the list get triggered. In this example we remove outputs2,
# which means that outputs3 won't get triggered at all (as evidenced by the fact that the
# Counter2 node only gets incremented once by output1).
og.Controller.disconnect(out_attr_2, in_exec_attr_1)
multisequence_node.remove_attribute("outputs:output2")
in_onlyplayback_attr.set(False)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 3)
self.assertEqual(out_cnt_attr_1.get(), 2)
self.assertEqual(out_cnt_attr_2.get(), 4)
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.E)
self.assertEqual(out_attr_3.get(), self.D)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_once_node(self, test_instance_id: int = 0):
"""Test Once node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (ontick_node, once_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Once", "omni.graph.action.Once"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: ("OnTick.outputs:tick", "Once.inputs:execIn"),
},
)
# Obtain necessary attributes.
in_exec_attr = once_node.get_attribute("inputs:execIn")
in_reset_attr = once_node.get_attribute("inputs:reset")
out_once_attr = once_node.get_attribute("outputs:once")
out_after_attr = once_node.get_attribute("outputs:after")
out_tick_attr = ontick_node.get_attribute("outputs:tick")
# Check that the Once node controls flow of execution by passing flow
# differently the first time it's executed compared to all subsequent
# executions.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.E)
self.assertEqual(out_after_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.E)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.E)
# Check that the reset flag works correctly when inputs:execIn is set to 0 (i.e. when
# the Once node is NOT supposed to be executing).
og.Controller.disconnect(out_tick_attr, in_exec_attr)
og.Controller.connect(out_tick_attr, in_reset_attr)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.D)
og.Controller.disconnect(out_tick_attr, in_reset_attr)
og.Controller.connect(out_tick_attr, in_exec_attr)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.E)
self.assertEqual(out_after_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.E)
# Check that when both the execIn and reset input attributes get triggered, the latter
# overrides the former and execution flow does not pass through outputs:after.
# FIXME: Something about the 2nd connection here is messing up the data model such
# that inputs:reset is being read as 0 inside the node
og.Controller.connect(out_tick_attr, in_reset_attr)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# self.assertEqual(out_once_attr.get(), self.D)
# self.assertEqual(out_after_attr.get(), self.D)
# ----------------------------------------------------------------------
# NOTE: Even though the OnClosing node is threadsafe (its compute method is very simple),
# we don't adapt the below test to check for thread-safety conditions because it relies
# on other nodes (omni.graph.action.SendCustomEvent and omni.graph.nodes.GraphTarget)
# which are NOT threadsafe.
async def test_onclosing_node(self):
"""Test OnClosing node"""
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# Testing OnClosing is tricky because OG is being destroyed when it happens -
# so test by sending a custom event when the network is triggered
# and then checking if we got that event.
def registered_event_name(event_name):
"""Returns the internal name used for the given custom event name"""
name = "omni.graph.action." + event_name
return carb.events.type_from_string(name)
got_event = [0]
def on_event(_):
got_event[0] = got_event[0] + 1
reg_event_name = registered_event_name("foo")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_push_by_type(reg_event_name, on_event)
self.assertIsNotNone(sub)
async def set_up_graph():
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnClosing", "omni.graph.action.OnClosing"),
("Send", "omni.graph.action.SendCustomEvent"),
("GraphTarget", "omni.graph.nodes.GraphTarget"),
],
keys.CONNECT: [
("OnClosing.outputs:execOut", "Send.inputs:execIn"),
("GraphTarget.outputs:primPath", "Send.inputs:path"),
],
keys.SET_VALUES: [("Send.inputs:eventName", "foo")],
},
)
await set_up_graph()
# Evaluate once so that the standalone graph is in steady state.
await omni.kit.app.get_app().next_update_async()
self.assertEqual(got_event[0], 0)
# Close the stage.
usd_context = omni.usd.get_context()
(result, _) = await usd_context.close_stage_async()
self.assertTrue(result)
# Check our handler was called.
self.assertEqual(got_event[0], 1)
# Reset the counter.
got_event[0] = 0
# Now check that the same works with instanced graphs.
await usd_context.new_stage_async()
await set_up_graph()
og.cmds.SetEvaluationMode(
graph=og.get_graph_by_path(self.TEST_GRAPH_PATH),
new_evaluation_mode=og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED,
)
stage = usd_context.get_stage()
prims = [stage.DefinePrim(f"/prim_{i}") for i in range(0, 100)]
for prim in prims:
OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim.GetPath(), self.TEST_GRAPH_PATH)
# Wait an update for the graphs to get set up.
await omni.kit.app.get_app().next_update_async()
# Close the stage.
(result, _) = await usd_context.close_stage_async()
self.assertTrue(result)
# Check that our handler was called.
self.assertEqual(got_event[0], len(prims))
# ----------------------------------------------------------------------
async def test_oncustomevent_and_sendcustomevent_nodes(self):
"""Test OnCustomEvent and SendCustomEvent nodes"""
controller = og.Controller()
controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, (_, _, event1_node, counter1_node, event2_node, counter2_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Send", "omni.graph.action.SendCustomEvent"),
("OnCustomEvent1", "omni.graph.action.OnCustomEvent"),
("Counter1", "omni.graph.action.Counter"),
("OnCustomEvent2", "omni.graph.action.OnCustomEvent"),
("Counter2", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnImpulse.outputs:execOut", "Send.inputs:execIn"),
("OnCustomEvent1.outputs:execOut", "Counter1.inputs:execIn"),
("OnCustomEvent2.outputs:execOut", "Counter2.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnCustomEvent1.inputs:onlyPlayback", False),
("OnCustomEvent2.inputs:onlyPlayback", False),
("OnImpulse.inputs:onlyPlayback", False),
("Send.inputs:eventName", "foo"),
("Send.inputs:path", "Test Path"),
("OnCustomEvent1.inputs:eventName", "foo"),
("OnCustomEvent2.inputs:eventName", "foo"),
],
},
)
counter1_controller = og.Controller(og.Controller.attribute("outputs:count", counter1_node))
counter2_controller = og.Controller(og.Controller.attribute("outputs:count", counter2_node))
event1_controller = og.Controller(og.Controller.attribute("outputs:path", event1_node))
event2_controller = og.Controller(og.Controller.attribute("outputs:path", event2_node))
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 0)
# Trigger graph once, this will queue up the event for the next evaluation.
controller.edit(self.TEST_GRAPH_PATH, {self.keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
# Note that if this is a push subscription, the receivers will run this frame instead of next.
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 0)
# This evaluation should trigger the receivers.
await omni.kit.app.get_app().next_update_async()
# Verify that events were received.
self.assertEqual(counter1_controller.get(), 1)
self.assertEqual(event1_controller.get(), "Test Path")
self.assertEqual(counter2_controller.get(), 1)
self.assertEqual(event2_controller.get(), "Test Path")
# Verify the contents of the associated bundle.
# FIXME: Authored bundle is always empty?
# bundle_contents = og.BundleContents(graph.get_default_graph_context(), event1_node, "outputs:bundle", True)
# self.assertEqual(1, bundle_contents.size)
# Modify the event name one receiver and sender and ensure it still works.
controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.SET_VALUES: [("Send.inputs:eventName", "bar"), ("OnImpulse.state:enableImpulse", True)],
},
)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# We changed the sender event name, so counter should NOT have triggered again.
self.assertEqual(counter1_controller.get(), 1)
# Change the receiver name to match.
controller.edit(self.TEST_GRAPH_PATH, {self.keys.SET_VALUES: ("OnCustomEvent1.inputs:eventName", "bar")})
await omni.kit.app.get_app().next_update_async()
# Trigger send again and verify we get it (1 frame lag for pop).
controller.edit(self.TEST_GRAPH_PATH, {self.keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 2)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_evaluation_01.py | """Action Graph Evaluation Tests, Part 1"""
import asyncio
import json
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
# ======================================================================
class TestActionGraphEvaluation(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_active_latent(self):
"""Exercise a latent node that executes downstream nodes while latent"""
# +--------+ +----------+finished+-------------+
# | OnTick+-->| Countdown+-------->FinishCounter|
# +--------+ | | +-------------+
# | +-+
# +----------+ | +------------+ +------------+ +------------+
# +-----> TickCounter+----->TickCounter2+---->TickCounter3|
# tick +------------+ +------------+ +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Countdown", "omni.graph.action.Countdown"),
("FinishCounter", "omni.graph.action.Counter"),
("TickCounter", "omni.graph.action.Counter"),
("TickCounter2", "omni.graph.action.Counter"),
("TickCounter3", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Countdown.inputs:execIn"),
("Countdown.outputs:finished", "FinishCounter.inputs:execIn"),
("Countdown.outputs:tick", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickCounter2.inputs:execIn"),
("TickCounter2.outputs:execOut", "TickCounter3.inputs:execIn"),
],
keys.SET_VALUES: [("Countdown.inputs:duration", 3), ("OnTick.inputs:onlyPlayback", False)],
},
)
(_, _, finish_counter, tick_counter, _, tick_counter_3) = nodes
finish_counter_controller = og.Controller(og.Controller.attribute("outputs:count", finish_counter))
tick_counter_controller = og.Controller(og.Controller.attribute("outputs:count", tick_counter))
tick_counter_3_controller = og.Controller(og.Controller.attribute("outputs:count", tick_counter_3))
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
await controller.evaluate(graph)
self.assertEqual(tick_counter_controller.get(), 1)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
self.assertEqual(tick_counter_controller.get(), 2)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
self.assertEqual(tick_counter_3_controller.get(), 3)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 1)
self.assertEqual(tick_counter_3_controller.get(), 3)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 1)
self.assertEqual(tick_counter_3_controller.get(), 3)
# ----------------------------------------------------------------------
async def test_async_nodes(self):
"""Test asynchronous action nodes"""
# Check that a nested loop state is maintained when executing a latent delay.
#
# +---------+ +----------+ +----------+ +-------+ +--------+
# | IMPULSE +-->| FOR-LOOP +--->| FOR-LOOP +--->| DELAY +--->| COUNTER|
# +---------+ +----------+ +----------+ +-------+ +--------+
#
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, _, counter_node, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ForLoop1", "omni.graph.action.ForLoop"),
("ForLoop2", "omni.graph.action.ForLoop"),
("Delay", "omni.graph.action.Delay"),
("Counter", "omni.graph.action.Counter"),
("OnTick", "omni.graph.action.OnTick"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "ForLoop2.inputs:execIn"),
("ForLoop2.outputs:loopBody", "Delay.inputs:execIn"),
("Delay.outputs:finished", "Counter.inputs:execIn"),
("OnTick.outputs:tick", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("OnImpulse.inputs:onlyPlayback", False),
("Delay.inputs:duration", 0.1),
("ForLoop1.inputs:stop", 2),
("ForLoop2.inputs:stop", 5),
],
},
)
await controller.evaluate(graph)
# Trigger graph once.
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# In delay now, no count.
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
self.assertEqual(counter_controller.get(), 0)
# Wait to ensure the first 5 delays compute.
for _ in range(5):
await asyncio.sleep(0.2)
await controller.evaluate(graph)
count_val = counter_controller.get()
self.assertGreater(count_val, 4)
# Wait and verify the remainder go through.
for _ in range(5):
await asyncio.sleep(0.1)
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 10)
# ----------------------------------------------------------------------
async def test_chained_stateful_nodes(self):
"""Test that chaining loop nodes works"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("ForLoop1", "omni.graph.action.ForLoop"),
("ForLoop2", "omni.graph.action.ForLoop"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "ForLoop2.inputs:execIn"),
("ForLoop2.outputs:loopBody", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("ForLoop1.inputs:stop", 5),
("ForLoop2.inputs:stop", 5),
],
},
)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_node)), 5 * 5)
# ----------------------------------------------------------------------
async def test_cycle_break(self):
"""Test that an illegal cycle issues a warning"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (on_impulse, count_a, count_b), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("A", "omni.graph.action.Counter"),
("B", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "A.inputs:execIn"),
("A.outputs:execOut", "B.inputs:execIn"),
("B.outputs:execOut", "A.inputs:execIn"),
],
keys.SET_VALUES: [
("OnImpulse.state:enableImpulse", True),
("OnImpulse.inputs:onlyPlayback", False),
],
},
)
with ogts.ExpectedError():
await controller.evaluate(graph)
og.Controller.set(controller.attribute("state:enableImpulse", on_impulse), True)
with ogts.ExpectedError():
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", count_a)), 2)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", count_b)), 2)
# ----------------------------------------------------------------------
async def test_dep_sort_fan_out(self):
"""Test that dependency sort works when there is data fan-out"""
# +-------------+
# +-------->| |
# | | SwitchTokenA|
# | +--->+-------------+
# +----------+ |
# |OnImpulse +----|------+ +--------------+
# +----------+ | +---------->| SwitchTokenB |
# | +^-------------+
# +------+-+ +--------+ |
# | ConstA +--->AppendB +---+
# +--------+ +--------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, _, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ConstA", "omni.graph.nodes.ConstantToken"),
("AppendB", "omni.graph.nodes.AppendString"),
("SwitchTokenA", "omni.graph.action.SwitchToken"),
("SwitchTokenB", "omni.graph.action.SwitchToken"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "SwitchTokenA.inputs:execIn"),
("OnImpulse.outputs:execOut", "SwitchTokenB.inputs:execIn"),
("ConstA.inputs:value", "SwitchTokenA.inputs:value"),
("ConstA.inputs:value", "AppendB.inputs:value"),
("AppendB.outputs:value", "SwitchTokenB.inputs:value"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("AppendB.inputs:suffix", {"value": "Foo", "type": "token"}),
],
},
)
await controller.evaluate(graph)
graph_state = og.OmniGraphInspector().as_json(graph, flags=["evaluation"])
graph_state_obj = json.loads(graph_state)
trace = graph_state_obj["Evaluator"]["Instances"][0]["LastNonEmptyEvaluation"]["Trace"]
# The switches can run in any order
self.assertTrue(
trace in (["SwitchTokenA", "AppendB", "SwitchTokenB"], ["AppendB", "SwitchTokenB", "SwitchTokenA"])
)
# ----------------------------------------------------------------------
async def test_diamond_fan(self):
"""Test latent nodes in parallel fan-out which fan-in to a downstream node"""
# +--------++ +----------+
# +--> TickA +--->|FinishedA |---+
# | +---------+ +----------+ |
# +---------+ +-----------+ | | +------------+
# |OnImpulse+-->|TickCounter+-+ +-->|MergeCounter|
# +---------+ +-----------+ | | +------------+
# | +---------+ +----------+ |
# +-->| TickB +--->|FinishedB |--+
# +--------++ +----------+
# | +---------+
# +-->| TickC |
# +--------++
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickCounter", "omni.graph.action.Counter"),
("TickA", "omni.graph.action.Countdown"),
("TickB", "omni.graph.action.Countdown"),
("TickC", "omni.graph.action.Countdown"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
("MergeCounter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickA.inputs:execIn"),
("TickCounter.outputs:execOut", "TickB.inputs:execIn"),
("TickCounter.outputs:execOut", "TickC.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
("FinishCounterA.outputs:execOut", "MergeCounter.inputs:execIn"),
("FinishCounterB.outputs:execOut", "MergeCounter.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 1),
("TickB.inputs:duration", 1),
("TickC.inputs:duration", 1),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, tick_counter, _, _, tick_c, finish_counter_a, finish_counter_b, merge_counter) = nodes
def check_counts(t_c, f_a, f_b, m_c, tick_c_count):
for node, expected in (
(tick_counter, t_c),
(finish_counter_a, f_a),
(finish_counter_b, f_b),
(merge_counter, m_c),
):
count = og.Controller.get(controller.attribute("outputs:count", node))
self.assertEqual(count, expected, node.get_prim_path())
self.assertEqual(tick_c.get_compute_count(), tick_c_count)
self.assertEqual(tick_c.get_compute_count(), 0)
# Set up latent tickers.
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 1)
# Latent ticks.
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 2)
# Both branches complete.
await controller.evaluate(graph)
check_counts(1, 1, 1, 2, 3)
# No count changes + no additional computes of tickC.
await controller.evaluate(graph)
check_counts(1, 1, 1, 2, 3)
# ----------------------------------------------------------------------
async def test_diamond_latent_fan(self):
"""Test latent nodes in parallel fan-out which fan-in to a latent downstream node"""
# +--------++
# +--> TickA +--+
# | +---------+ |
# +---------+ | | +-------+ +-------+
# |OnImpulse+-->+ +-->|TickD +-+--->|CountF |
# +---------+ | | +-------+ | +-------+
# | +--------+ | +--->+-------+
# +-->| TickB +--+ |TickE |
# | +--------+ +--->+-------+
# | +--------+ |
# +-->| TickC +----------------+
# +--------+
# Note that when TickA triggers TickD into latent state, then TickB hits TickD subsequently. This subsequent
# evaluation is _transient_. Meaning that TickB will not block on a new copy of TickD.
# This is because there is only one TickD so there can be only one state (latent or not).
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.Countdown"),
("TickB", "omni.graph.action.Countdown"),
("TickC", "omni.graph.action.Countdown"),
("TickD", "omni.graph.action.Countdown"),
("TickE", "omni.graph.action.Countdown"),
("CountF", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("OnImpulse.outputs:execOut", "TickB.inputs:execIn"),
("OnImpulse.outputs:execOut", "TickC.inputs:execIn"),
("TickA.outputs:finished", "TickD.inputs:execIn"),
("TickB.outputs:finished", "TickD.inputs:execIn"),
("TickC.outputs:finished", "TickE.inputs:execIn"),
("TickD.outputs:finished", "TickE.inputs:execIn"),
("TickD.outputs:finished", "CountF.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 1),
("TickB.inputs:duration", 1),
("TickC.inputs:duration", 2),
("TickD.inputs:duration", 1),
("TickE.inputs:duration", 1),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, tick_a, tick_b, tick_c, tick_d, tick_e, count_f) = nodes
def check_counts(i, t_a, t_b, t_c, t_d, t_e):
for node, expected in ((tick_a, t_a), (tick_b, t_b), (tick_c, t_c), (tick_d, t_d), (tick_e, t_e)):
self.assertEqual(node.get_compute_count(), expected, f"Check {i} for {node.get_prim_path()}")
# A, B, C, D, E
compute_counts = [
(1, 1, 1, 0, 0), # 0. fan out to trigger A, B, C into latent state
(2, 2, 2, 0, 0), # 1. A, B, C tick
(3, 3, 3, 2, 0), # 2. A, B end latent, D into latent via A or B, D ticks via A or B, C ticks
(3, 3, 4, 3, 2), # 3.
(3, 3, 4, 3, 3), # 4.
(3, 3, 4, 3, 3), # 5.
(3, 3, 4, 3, 3), # 6.
]
for i, c_c in enumerate(compute_counts):
await controller.evaluate(graph)
check_counts(i, *c_c)
# Verify that CountF has computed 1x due to the fan-in at TickD NOT acting like separate threads.
self.assertEqual(count_f.get_compute_count(), 1)
# ----------------------------------------------------------------------
async def test_dynamic_exec_pins(self):
"""Test that adding execution pins to a non-action node works"""
controller = og.Controller()
keys = og.Controller.Keys
(_, (on_tick, to_string), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("ToString", "omni.graph.nodes.ToString"),
],
keys.SET_VALUES: [
("ToString.inputs:value", 42, "double"),
("OnTick.inputs:onlyPlayback", False),
],
},
)
# Verify to_string has not been computed.
await controller.evaluate()
self.assertEqual(0, to_string.get_compute_count())
self.assertEqual(1, on_tick.get_compute_count())
# Add execution attribs and verify it still doesn't get computed.
attrib = og.Controller.create_attribute(
to_string,
"inputs:execIn",
"execution",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
)
self.assertIsNotNone(attrib)
await controller.evaluate()
self.assertEqual(0, to_string.get_compute_count())
self.assertEqual(2, on_tick.get_compute_count())
# Hook up to OnTick and verify it is now computing.
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CONNECT: [
("OnTick.outputs:tick", "ToString.inputs:execIn"),
]
},
)
for i in range(10):
await controller.evaluate()
self.assertEqual(i + 1, to_string.get_compute_count())
self.assertEqual(i + 3, on_tick.get_compute_count())
# ----------------------------------------------------------------------
async def test_exec_fan_out(self):
"""Test that fanning out from an exec port works"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FF1", "omni.graph.action.FlipFlop"),
("FF2", "omni.graph.action.FlipFlop"),
("FF11", "omni.graph.action.FlipFlop"),
("FF12", "omni.graph.action.FlipFlop"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
keys.CONNECT: [
("OnTick.outputs:tick", "FF1.inputs:execIn"),
("OnTick.outputs:tick", "FF2.inputs:execIn"),
("FF1.outputs:a", "FF11.inputs:execIn"),
("FF1.outputs:a", "FF12.inputs:execIn"),
],
},
)
# 1. OnTick triggers FF1 which triggers FF11 and FF12, then FF2.
# 2. OnTick triggers FF1 and FF2.
# 3. OnTick triggers FF1 which triggers FF11 and FF12, then FF2.
await controller.evaluate(graph)
flip_flops = nodes[1:]
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [True, True, True, True])
await controller.evaluate(graph)
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [False, False, True, True])
await controller.evaluate(graph)
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [True, True, False, False])
# ----------------------------------------------------------------------
async def test_exec_fan_out_shared_deps(self):
"""Test that dependency sort works when there is shared data in exec fan-out"""
# +---------+
# +---------->| Write1 |
# | +----^----+
# | |
# | +----------+
# | |
# +-----------+ | |
# | OnImpulse +-----+-----+----> +---------+
# +-----------+ | | | Write2 |
# | +----->+---------+
# | |
# | | +---------+
# +-----+----->| Write3 |
# | +---------+
# | ^
# +-------+ +---+----+---+
# | Const +----->| Inc |
# +-------+ +--------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Const", "omni.graph.nodes.ConstantDouble"),
("Inc", "omni.graph.nodes.Increment"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
("Write2", "omni.graph.nodes.WritePrimAttribute"),
("Write3", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: [
("/World/TestPrim1", {"val": ("double", 1.0)}),
("/World/TestPrim2", {"val": ("double", 2.0)}),
("/World/TestPrim3", {"val": ("double", 3.0)}),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Write1.inputs:execIn"),
("OnImpulse.outputs:execOut", "Write2.inputs:execIn"),
("OnImpulse.outputs:execOut", "Write3.inputs:execIn"),
("Const.inputs:value", "Inc.inputs:value"),
("Inc.outputs:result", "Write1.inputs:value"),
("Inc.outputs:result", "Write2.inputs:value"),
("Inc.outputs:result", "Write3.inputs:value"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("Const.inputs:value", 41.0),
("Inc.inputs:increment", 1.0),
("Write1.inputs:primPath", "/World/TestPrim1"),
("Write1.inputs:usePath", True),
("Write1.inputs:name", "val"),
("Write2.inputs:primPath", "/World/TestPrim2"),
("Write2.inputs:usePath", True),
("Write2.inputs:name", "val"),
("Write3.inputs:primPath", "/World/TestPrim3"),
("Write3.inputs:usePath", True),
("Write3.inputs:name", "val"),
],
},
)
await controller.evaluate(graph)
stage = omni.usd.get_context().get_stage()
for i in (1, 2, 3):
self.assertEqual(stage.GetAttributeAtPath(f"/World/TestPrim{i}.val").Get(), 42.0)
# ----------------------------------------------------------------------
async def test_exec_sort_failure(self):
"""Test that sorting dependencies with non-trivial authored graph"""
# Our global sort excludes exec nodes, so a global topo (Kahn) sort will fail such that Inc3 doesn't get
# computed until after Add2, so instead we sort each dep network independently. This test verifies the case
# where that matters.
#
# +-----------------------------> Write1(var) +----------------------------------------+
# | ^ | |
# | | | v
# OnTick --------------------+ | +-----------Inc------------+ Write2(var2)
# | | | ^
# v | | |
# Read1(var)------------> Add1 --Inc2--+ v |
# Inc3 --------------> Add2 ---------------+
controller = og.Controller()
keys = og.Controller.Keys
(_, (on_tick, a_1, a_2, _, _, _, _, _, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("A1", "omni.graph.nodes.Add"),
("A2", "omni.graph.nodes.Add"),
("Write1", "omni.graph.core.WriteVariable"),
("Write2", "omni.graph.core.WriteVariable"),
("Read1", "omni.graph.core.ReadVariable"),
("Inc", "omni.graph.nodes.Increment"),
("Inc2", "omni.graph.nodes.Increment"),
("Inc3", "omni.graph.nodes.Increment"),
],
keys.CREATE_VARIABLES: [
("var", og.Type(og.BaseDataType.DOUBLE)),
("var2", og.Type(og.BaseDataType.DOUBLE)),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Inc3.inputs:value", {"type": "double", "value": 42.0}),
("Write1.inputs:variableName", "var"),
("Write2.inputs:variableName", "var2"),
("Read1.inputs:variableName", "var"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Write1.inputs:execIn"),
("OnTick.outputs:timeSinceStart", "A1.inputs:a"),
("Read1.outputs:value", "A1.inputs:b"),
("A1.outputs:sum", "Inc2.inputs:value"),
("Inc2.outputs:result", "Write1.inputs:value"),
("Write1.outputs:execOut", "Write2.inputs:execIn"),
("Write1.outputs:value", "Inc.inputs:value"),
("Inc.outputs:result", "A2.inputs:a"),
("Inc3.outputs:result", "A2.inputs:b"),
("A2.outputs:sum", "Write2.inputs:value"),
],
},
)
await omni.kit.app.get_app().next_update_async()
a_1_v = og.Controller.get(controller.attribute("outputs:sum", a_1))
a_2_v = og.Controller.get(controller.attribute("outputs:sum", a_2))
on_tick_dt = og.Controller.get(controller.attribute("outputs:timeSinceStart", on_tick))
a_1_expected = 0 + on_tick_dt
a_2_expected = (a_1_expected + 1.0 + 1.0) + (42.0 + 1.0)
self.assertAlmostEqual(a_1_v, a_1_expected, places=3)
self.assertAlmostEqual(a_2_v, a_2_expected, places=3)
# ----------------------------------------------------------------------
async def test_fan_in(self):
"""Test that fan-in of execution connections works as expected (from a loaded test .usda file)"""
(result, error) = await ogts.load_test_file("TestActionFanIn.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
graph_path = "/World/ActionGraph"
controller = og.Controller()
graph = controller.graph(graph_path)
# Trigger the loop.
og.Controller.set(controller.attribute(f"{graph_path}/on_impulse_event.state:enableImpulse"), True)
await controller.evaluate(graph)
graph_state = og.OmniGraphInspector().as_json(controller.graph(graph_path), flags=["evaluation"])
graph_state_obj = json.loads(graph_state)
trace = graph_state_obj["Evaluator"]["Instances"][0]["LastNonEmptyEvaluation"]["Trace"]
# Verify the first loop iteration.
self.assertEqual("for_loop", trace[0])
# These nodes can compute in any order
self.assertEqual(["counter", "counter_01"], sorted(trace[1:3]))
expected_trace = [
"to_uint64",
"sync_gate",
"to_uint64",
"sync_gate",
]
self.assertListEqual(expected_trace, trace[3:7])
trace[0:7] = []
# Verify downstream from sync gate.
expected_trace = [
"counter_02",
]
self.assertListEqual(expected_trace, trace[0:1])
trace[0 : len(expected_trace)] = []
# Verify second iteration.
self.assertEqual("for_loop", trace[0])
# These nodes can compute in any order
self.assertEqual(["counter", "counter_01"], sorted(trace[1:3]))
expected_trace = [
"to_uint64",
"sync_gate",
"to_uint64",
"sync_gate",
]
self.assertListEqual(expected_trace, trace[3:7])
# ----------------------------------------------------------------------
async def test_loading_type_resol(self):
"""Test that loading a file with weird type resolution pattern works"""
(result, error) = await ogts.load_test_file("load_with_type_resol.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
graph_path = "/World/ActionGraph"
controller = og.Controller()
graph = controller.graph(graph_path)
# eval
await controller.evaluate(graph)
# check result
var = graph.find_variable("Result")
val = var.get_array(graph.get_default_graph_context(), False, 0)
self.assertTrue((val == [(-50, -50, -50), (50, 50, 50)]).all())
# ----------------------------------------------------------------------
async def test_fan_in_exec(self):
"""Test that execution fan-in is handled correctly"""
# The evaluator has to consider the case that gate.enter will have contradicting upstream values.
# Gate needs to know which input is active, it needs the value of enter to be ENABLED when it
# is triggered by OnTick, even though OnTickDisabled has set it's output to the same attrib as DISABLED.
#
# +--------------+
# |OnImpulseEvent+---+ +-----------+
# +--------------+ | |Gate |
# +--->toggle |
# +--------------+ | |
# |OnTick +------>|enter |
# +--------------+ +^-----exit-+
# |
# +--------------+ |
# |OnTickDisabled+--------+
# +--------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, gate, on_impulse_event), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("OnTickDisabled", "omni.graph.action.OnTick"),
("Gate", "omni.graph.action.Gate"),
("OnImpulseEvent", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Gate.inputs:enter"),
("OnTickDisabled.outputs:tick", "Gate.inputs:enter"),
("OnImpulseEvent.outputs:execOut", "Gate.inputs:toggle"),
],
keys.SET_VALUES: [
("Gate.inputs:startClosed", True),
("OnTick.inputs:onlyPlayback", False),
("OnImpulseEvent.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
gate_exit = controller.attribute("outputs:exit", gate)
# Verify the Gate has not triggered.
self.assertFalse(gate_exit.get())
await controller.evaluate(graph)
self.assertFalse(gate_exit.get())
# Toggle the gate and verify that the tick goes through. The first evaluate it isn't known if the Gate will
# trigger because the order that entry points are executed is not defined... FIXME.
controller.attribute("state:enableImpulse", on_impulse_event).set(True)
await controller.evaluate(graph)
await controller.evaluate(graph)
self.assertTrue(gate_exit.get())
# ----------------------------------------------------------------------
async def test_fan_out_exec(self):
"""Test that execution fan-out is handled correctly"""
# We want to reset the execution attribute states before the node compute() to avoid bugs
# that arise when authors forget to fully specify the output states. However we can't
# do this in the middle of traversal, because fan-out from a connection requires that the state
# be preserved for every downstream node which may read from it (like Gate).
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, gate, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Gate", "omni.graph.action.Gate"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Counter.inputs:execIn"),
("OnTick.outputs:tick", "Gate.inputs:enter"),
],
keys.SET_VALUES: [
("Gate.inputs:startClosed", False),
("OnTick.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
gate_exit = controller.attribute("outputs:exit", gate)
# Verify the Gate has triggered.
self.assertTrue(gate_exit.get())
await controller.evaluate(graph)
self.assertTrue(gate_exit.get())
# ----------------------------------------------------------------------
async def test_latent_and_push(self):
"""Exercise latent nodes in combination with stateful loop node"""
#
# +---------+ +-------+ tick +--------+ loopBody +-------+ +------------+
# |OnImpulse+-->|TickA +----------->ForLoop1++--------->|TickB +-+->|TickCounterB|
# +---------+ +----+--+ +--------++ +-------+ | +------------+
# | finish | |
# | | |
# | +--------------+ +v----------------+ +-v------------+
# +----->|FinishCounterA| |FinishLoopCounter| |FinishCounterB|
# +--------------+ +-----------------+ +--------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.Countdown"),
("ForLoop1", "omni.graph.action.ForLoop"),
("TickB", "omni.graph.action.Countdown"),
("FinishLoopCounter", "omni.graph.action.Counter"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("TickA.outputs:tick", "ForLoop1.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("ForLoop1.outputs:loopBody", "TickB.inputs:execIn"),
("ForLoop1.outputs:finished", "FinishLoopCounter.inputs:execIn"),
("TickB.outputs:tick", "TickCounterB.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
],
keys.SET_VALUES: [
("ForLoop1.inputs:start", 0),
("ForLoop1.inputs:stop", 3),
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("OnImpulse.state:enableImpulse", True),
("OnImpulse.inputs:onlyPlayback", False),
],
},
)
(_, _, _, _, finish_loop_counter, finish_counter_a, finish_counter_b, tick_counter_b) = nodes
for _ in range(20):
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_counter_a)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_b)), 12)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_counter_b)), 6)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_loop_counter)), 2)
# ----------------------------------------------------------------------
async def test_latent_chain(self):
"""Exercise a chain of latent nodes"""
# +---------+ +-------+ tick +-------+ tick +-------+
# |OnImpulse+-->TickA +-------->TickB +-------->|LatentC|
# +---------+ +-----+-+ +------++ +-------+-----+
# | finish | finish |
# finish | +-------------+ | +-------------+ +-v----------+
# +->TickCounterA | +-->| TickCounterB| |TickCounterC|
# +-------------+ +-------------+ +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.Countdown"),
("TickB", "omni.graph.action.Countdown"),
("LatentC", "omni.graph.action.Countdown"),
("TickCounterA", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
("TickCounterC", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("TickA.outputs:tick", "TickB.inputs:execIn"),
("TickA.outputs:finished", "TickCounterA.inputs:execIn"),
("TickB.outputs:tick", "LatentC.inputs:execIn"),
("TickB.outputs:finished", "TickCounterB.inputs:execIn"),
("LatentC.outputs:finished", "TickCounterC.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("LatentC.inputs:duration", 2),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, _, _, _, tick_counter_a, tick_counter_b, tick_counter_c) = nodes
for _ in range(16):
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_a)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_b)), 2)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_c)), 4)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_on_stage_event_node.py | """Basic tests of the OnStageEvent node"""
import omni.client
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.tools.ogn as ogn
import omni.kit.app
import omni.kit.test
import omni.usd
from pxr import Sdf
# ======================================================================
class TestOnStageEventNode(ogts.OmniGraphTestCase):
"""Tests OnStageEvent node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
async def test_backward_compatibility_v3(self):
"""Validate backward compatibility for legacy versions of OnStageEvent node."""
# load the test scene which contains a OnStageEvent V2 node
(result, error) = await ogts.load_test_file("TestOnStageEventNode_v2.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
action_graph_path = "/World/ActionGraph"
action_graph = og.get_graph_by_path(action_graph_path)
on_stage_event_node = action_graph.get_node(action_graph_path + "/on_stage_event")
self.assertTrue(on_stage_event_node.is_valid())
# The "Hierarchy Changed" event has been introduced since V3. Validate that it is
# automatically included by the list of allowed tokens after loading V2.
attr = on_stage_event_node.get_attribute("inputs:eventName")
allowed_tokens = attr.get_metadata(ogn.MetadataKeys.ALLOWED_TOKENS)
self.assertTrue(isinstance(allowed_tokens, str))
self.assertTrue("Hierarchy Changed" in allowed_tokens.split(","))
async def test_stage_events(self):
"""Test OnStageEvent"""
controller = og.Controller()
keys = og.Controller.Keys
(_, (on_stage_node, _, _, counter_sel_node, counter_stop_node, counter_start_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnStageEvent", "omni.graph.action.OnStageEvent"),
("OnStageEvent2", "omni.graph.action.OnStageEvent"),
("OnStageEvent3", "omni.graph.action.OnStageEvent"),
("Counter", "omni.graph.action.Counter"),
("Counter2", "omni.graph.action.Counter"),
("Counter3", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnStageEvent.outputs:execOut", "Counter.inputs:execIn"),
("OnStageEvent2.outputs:execOut", "Counter2.inputs:execIn"),
("OnStageEvent3.outputs:execOut", "Counter3.inputs:execIn"),
],
keys.SET_VALUES: [
("OnStageEvent.inputs:eventName", "Selection Changed"),
("OnStageEvent.inputs:onlyPlayback", False),
("OnStageEvent2.inputs:eventName", "Animation Stop Play"),
("OnStageEvent2.inputs:onlyPlayback", True),
("OnStageEvent3.inputs:eventName", "Animation Start Play"),
("OnStageEvent3.inputs:onlyPlayback", True),
],
},
)
async def wait_2():
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
def get_start_count():
return og.Controller.get(controller.attribute("outputs:count", counter_start_node))
def get_stop_count():
return og.Controller.get(controller.attribute("outputs:count", counter_stop_node))
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 0)
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 0)
selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([self.TEST_GRAPH_PATH + "/OnStageEvent"], False)
# 1 frame delay on the pop, 1 frame delay on the compute
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 1)
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 0)
# change the tracked event, verify selection doesn't fire
og.Controller.set(controller.attribute("inputs:eventName", on_stage_node), "Saved")
selection.set_selected_prim_paths([self.TEST_GRAPH_PATH + "/OnStageEvent2"], False)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 1)
await omni.kit.app.get_app().next_update_async()
# change it back, verify it does fire when selection changes again
og.Controller.set(controller.attribute("inputs:eventName", on_stage_node), "Selection Changed")
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 1)
selection.set_selected_prim_paths([self.TEST_GRAPH_PATH + "/OnStageEvent"], False)
await wait_2()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 2)
# Verify that start/stop events work when only-playback is true
timeline = omni.timeline.get_timeline_interface()
timeline.set_start_time(1.0)
timeline.set_end_time(10.0)
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
timeline.play()
await wait_2()
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 1)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 1)
# Check that pausing / resuming does not trigger
timeline.pause()
await wait_2()
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 1)
timeline.play()
await wait_2()
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 1)
timeline.stop()
await wait_2()
self.assertEqual(get_stop_count(), 1)
self.assertEqual(get_start_count(), 1)
await controller.evaluate()
self.assertEqual(get_stop_count(), 1)
self.assertEqual(get_start_count(), 1)
# Verify that stopping while paused triggers the event
timeline.play()
await wait_2()
self.assertEqual(get_stop_count(), 1)
self.assertEqual(get_start_count(), 2)
timeline.pause()
await wait_2()
self.assertEqual(get_stop_count(), 1)
self.assertEqual(get_start_count(), 2)
timeline.stop()
await wait_2()
self.assertEqual(get_stop_count(), 2)
self.assertEqual(get_start_count(), 2)
# ----------------------------------------------------------------------
async def test_stage_hierarchy_changed_event(self):
"""Test the Hierarchy Changed event"""
app = omni.kit.app.get_app()
controller = og.Controller()
keys = og.Controller.Keys
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
root_path = Sdf.Path.absoluteRootPath
# Create Xform
omni.kit.commands.execute("CreatePrim", prim_type="Xform")
xform_path = root_path.AppendChild("Xform")
xform = stage.GetPrimAtPath(xform_path)
self.assertTrue(xform)
# Create Material
omni.kit.commands.execute("CreatePrim", prim_type="Material")
material_path = root_path.AppendChild("Material")
material = stage.GetPrimAtPath(material_path)
self.assertTrue(material)
# Create action graph
(_, (on_stage_node, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnStageEvent", "omni.graph.action.OnStageEvent"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnStageEvent.outputs:execOut", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("OnStageEvent.inputs:eventName", "Hierarchy Changed"),
("OnStageEvent.inputs:onlyPlayback", False),
],
},
)
outputs_count_attr = controller.attribute("outputs:count", counter_node)
expected_hierarchy_changed_event_count = 0
await app.next_update_async()
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Create cube
omni.kit.commands.execute("CreatePrim", prim_type="Cube")
cube_path = root_path.AppendChild("Cube")
cube = stage.GetPrimAtPath(cube_path)
self.assertTrue(cube)
# 1 frame delay on the pop, 1 frame delay on the compute
await app.next_update_async()
await app.next_update_async()
expected_hierarchy_changed_event_count += 1
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Reparent cube
cube_path_reparented = xform_path.AppendChild("Cube")
omni.kit.commands.execute("MovePrim", path_from=cube_path, path_to=cube_path_reparented)
await app.next_update_async()
await app.next_update_async()
expected_hierarchy_changed_event_count += 1
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Rename cube to lowercase
cube_path_lowercase = xform_path.AppendChild("cube")
omni.kit.commands.execute("MovePrim", path_from=cube_path_reparented, path_to=cube_path_lowercase)
await app.next_update_async()
await app.next_update_async()
expected_hierarchy_changed_event_count += 1
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Modify size attribute.
cube = stage.GetPrimAtPath(cube_path_lowercase)
self.assertTrue(cube)
cube.GetAttribute("size").Set(1.0)
await app.next_update_async()
await app.next_update_async()
# The "Hierarchy Changed" event is not expected for attribute change.
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Modify material binding.
rel = cube.CreateRelationship("material:binding", False)
rel.SetTargets([material_path])
await app.next_update_async()
await app.next_update_async()
# The "Hierarchy Changed" event is not expected for relationship change.
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Change the tracked event
og.Controller.set(controller.attribute("inputs:eventName", on_stage_node), "Saved")
await og.Controller.evaluate()
omni.kit.commands.execute("MovePrim", path_from=cube_path_lowercase, path_to=cube_path)
await app.next_update_async()
await app.next_update_async()
# verify hierarchy changed event doesn't fire
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Change it back, verify it does fire when hierarchy changes again
og.Controller.set(controller.attribute("inputs:eventName", on_stage_node), "Hierarchy Changed")
await og.Controller.evaluate()
# Remove cube
omni.kit.commands.execute("DeletePrims", paths=[cube_path])
await app.next_update_async()
await app.next_update_async()
expected_hierarchy_changed_event_count += 1
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_evaluation.py | """Action Graph Evaluation Tests"""
import asyncio
import carb.events
import omni.client
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
# ======================================================================
class TestActionGraphEvaluation(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_exec_fan_out(self):
"""Test that fanning out from an exec port works"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FF1", "omni.graph.action.FlipFlop"),
("FF2", "omni.graph.action.FlipFlop"),
("FF11", "omni.graph.action.FlipFlop"),
("FF12", "omni.graph.action.FlipFlop"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
keys.CONNECT: [
("OnTick.outputs:tick", "FF1.inputs:execIn"),
("OnTick.outputs:tick", "FF2.inputs:execIn"),
("FF1.outputs:a", "FF11.inputs:execIn"),
("FF1.outputs:a", "FF12.inputs:execIn"),
],
},
)
# 1. OnTick triggers FF1 which triggers FF11 and FF12, then FF2
# 2. OnTick triggers FF1 and FF2
# 3. OnTick triggers FF1 which triggers FF11 and FF12, then FF2
await controller.evaluate(graph)
flip_flops = nodes[1:]
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [True, True, True, True])
await controller.evaluate(graph)
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [False, False, True, True])
await controller.evaluate(graph)
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [True, True, False, False])
# ----------------------------------------------------------------------
async def test_chained_stateful_nodes(self):
"""Test that chaining loop nodes works"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("ForLoop1", "omni.graph.action.ForLoop"),
("ForLoop2", "omni.graph.action.ForLoop"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "ForLoop2.inputs:execIn"),
("ForLoop2.outputs:loopBody", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("ForLoop1.inputs:stop", 5),
("ForLoop2.inputs:stop", 5),
],
},
)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_node)), 5 * 5)
# ----------------------------------------------------------------------
async def test_async_nodes(self):
"""Test asynchronous action nodes"""
# Check that a nested loop state is maintained when executing a latent delay
#
# +---------+ +----------+ +----------+ +-------+ +--------+
# | IMPULSE +-->| FOR-LOOP +--->| FOR-LOOP +--->| DELAY +--->| COUNTER|
# +---------+ +----------+ +----------+ +-------+ +--------+
#
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, _, counter_node, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ForLoop1", "omni.graph.action.ForLoop"),
("ForLoop2", "omni.graph.action.ForLoop"),
("Delay", "omni.graph.action.Delay"),
("Counter", "omni.graph.action.Counter"),
("OnTick", "omni.graph.action.OnTick"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "ForLoop2.inputs:execIn"),
("ForLoop2.outputs:loopBody", "Delay.inputs:execIn"),
("Delay.outputs:finished", "Counter.inputs:execIn"),
("OnTick.outputs:tick", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("OnImpulse.inputs:onlyPlayback", False),
("Delay.inputs:duration", 0.1),
("ForLoop1.inputs:stop", 2),
("ForLoop2.inputs:stop", 5),
],
},
)
await controller.evaluate(graph)
# trigger graph once
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# in delay now, no count
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
self.assertEqual(counter_controller.get(), 0)
# wait to ensure the first 5 delays compute
for _ in range(5):
await asyncio.sleep(0.2)
await controller.evaluate(graph)
count_val = counter_controller.get()
self.assertGreater(count_val, 4)
# wait and verify the remainder go through
for _ in range(5):
await asyncio.sleep(0.1)
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 10)
# ----------------------------------------------------------------------
async def test_stateful_flowcontrol_evaluation(self):
"""Test that stateful flow control nodes are fully evaluated"""
# b
# +----------+ +---------+
# +--->| Sequence +-->|Counter1 |
# | +----------+ +---------+
# +-----------+ |
# | OnImpulse +-+
# +-----------+ |
# | +----------+ +----------+
# +--->| ForLoop1 +-->| Counter2 |
# +----------+ +----------+
# finished
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, counter1_node, _, counter2_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Sequence", "omni.graph.action.Sequence"),
("Counter1", "omni.graph.action.Counter"),
("ForLoop1", "omni.graph.action.ForLoop"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Sequence.inputs:execIn"),
("Sequence.outputs:b", "Counter1.inputs:execIn"),
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:finished", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False), ("ForLoop1.inputs:stop", 10)],
},
)
await controller.evaluate(graph)
# trigger graph once
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# verify that counter was called in spite of sequence 'a' being disconnected
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter1_node)), 1)
# verify that counter was called in spite of there being no loopBody - execution evaluator has to still trigger
# the loop 11 times despite there being no downstream connection
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 1)
# ----------------------------------------------------------------------
async def test_request_driven_node(self):
"""Test that RequestDriven nodes are computed as expected"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Counter", "omni.graph.action.Counter"),
],
keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False)],
keys.CONNECT: ("OnImpulse.outputs:execOut", "Counter.inputs:execIn"),
},
)
# After several updates, there should have been no compute calls
await controller.evaluate(graph)
await controller.evaluate(graph)
await controller.evaluate(graph)
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
self.assertEqual(counter_controller.get(), 0)
# change OnImpulse state attrib. The node should now request compute
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 1)
# more updates should not result in more computes
await controller.evaluate(graph)
await controller.evaluate(graph)
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 1)
# ----------------------------------------------------------------------
async def test_fan_in_exec(self):
"""Test that execution fan-in is handled correctly."""
# The evaluator has to consider the case that gate.enter will have contradicting upstream values.
# Gate needs to know which input is active, it needs the value of enter to be ENABLED when it
# is triggered by OnTick, even though OnTickDisabled has set it's output to the same attrib as DISABLED.
#
# +--------------+
# |OnImpulseEvent+---+ +-----------+
# +--------------+ | |Gate |
# +--->toggle |
# +--------------+ | |
# |OnTick +------>|enter |
# +--------------+ +^-----exit-+
# |
# +--------------+ |
# |OnTickDisabled+--------+
# +--------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, gate, on_impulse_event), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("OnTickDisabled", "omni.graph.action.OnTick"),
("Gate", "omni.graph.action.Gate"),
("OnImpulseEvent", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Gate.inputs:enter"),
("OnTickDisabled.outputs:tick", "Gate.inputs:enter"),
("OnImpulseEvent.outputs:execOut", "Gate.inputs:toggle"),
],
keys.SET_VALUES: [
("Gate.inputs:startClosed", True),
("OnTick.inputs:onlyPlayback", False),
("OnImpulseEvent.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
gate_exit = controller.attribute("outputs:exit", gate)
# Verify the Gate has not triggered
self.assertFalse(gate_exit.get())
await controller.evaluate(graph)
self.assertFalse(gate_exit.get())
# toggle the gate and verify that the tick goes through. The first evaluate it isn't known if the Gate will
# trigger because the order that entry points are executed is not defined... FIXME
controller.attribute("state:enableImpulse", on_impulse_event).set(True)
await controller.evaluate(graph)
await controller.evaluate(graph)
self.assertTrue(gate_exit.get())
# ----------------------------------------------------------------------
async def test_fan_out_exec(self):
"""Test that execution fan-out is handled correctly."""
# We want to reset the execution attribute states before the node compute() to avoid bugs
# that arise when authors forget to fully specify the output states. However we can't
# do this in the middle of traversal, because fan-out from a connection requires that the state
# be preserved for every downstream node which may read from it (like Gate).
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, gate, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Gate", "omni.graph.action.Gate"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Counter.inputs:execIn"),
("OnTick.outputs:tick", "Gate.inputs:enter"),
],
keys.SET_VALUES: [
("Gate.inputs:startClosed", False),
("OnTick.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
gate_exit = controller.attribute("outputs:exit", gate)
# Verify the Gate has triggered
self.assertTrue(gate_exit.get())
await controller.evaluate(graph)
self.assertTrue(gate_exit.get())
# ----------------------------------------------------------------------
async def test_onclosing(self):
"""Test OnClosing node"""
# Test OnClosing is tricky because OG is being destroyed when it happens -
# so test by sending a custom event when the network is triggered
# and then checking if we got that event
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)
got_event = [False]
def on_event(_):
got_event[0] = True
reg_event_name = registered_event_name("foo")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_push_by_type(reg_event_name, on_event)
self.assertIsNotNone(sub)
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnClosing", "omni.graph.action.OnClosing"),
("Send", "omni.graph.action.SendCustomEvent"),
],
keys.CONNECT: [("OnClosing.outputs:execOut", "Send.inputs:execIn")],
keys.SET_VALUES: [("Send.inputs:eventName", "foo"), ("Send.inputs:path", "Test Path")],
},
)
# evaluate once so that graph is in steady state
await controller.evaluate()
# close the stage
usd_context = omni.usd.get_context()
(result, _) = await usd_context.close_stage_async()
self.assertTrue(result)
# Check our handler was called
self.assertTrue(got_event[0])
async def test_onloaded(self):
"""Test OnLoaded node"""
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)
events = []
def on_event(e):
events.append(e.payload["!path"])
reg_event_name = registered_event_name("foo")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_push_by_type(reg_event_name, on_event)
self.assertIsNotNone(sub)
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("OnLoaded", "omni.graph.action.OnLoaded"),
("Send1", "omni.graph.action.SendCustomEvent"),
("Send2", "omni.graph.action.SendCustomEvent"),
],
keys.CONNECT: [
("OnLoaded.outputs:execOut", "Send1.inputs:execIn"),
("OnTick.outputs:tick", "Send2.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Send1.inputs:eventName", "foo"),
("Send2.inputs:eventName", "foo"),
("Send1.inputs:path", "Loaded"),
("Send2.inputs:path", "Tick"),
],
},
)
# evaluate once so that graph is in steady state
await controller.evaluate()
# Verify Loaded came before OnTick
self.assertListEqual(events, ["Loaded", "Tick"])
# ----------------------------------------------------------------------
async def test_active_latent(self):
"""exercise a latent node that executes downstream nodes while latent"""
# +--------+ +----------+finished+-------------+
# | OnTick+-->| TickN +-------->FinishCounter|
# +--------+ | | +-------------+
# | +-+
# +----------+ | +------------+ +------------+ +------------+
# +-----> TickCounter+----->TickCounter2+---->TickCounter3|
# tick +------------+ +------------+ +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("TickN", "omni.graph.action.TickN"),
("FinishCounter", "omni.graph.action.Counter"),
("TickCounter", "omni.graph.action.Counter"),
("TickCounter2", "omni.graph.action.Counter"),
("TickCounter3", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "TickN.inputs:execIn"),
("TickN.outputs:finished", "FinishCounter.inputs:execIn"),
("TickN.outputs:tick", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickCounter2.inputs:execIn"),
("TickCounter2.outputs:execOut", "TickCounter3.inputs:execIn"),
],
keys.SET_VALUES: [("TickN.inputs:duration", 3), ("OnTick.inputs:onlyPlayback", False)],
},
)
(_, _, finish_counter, tick_counter, _, tick_counter_3) = nodes
finish_counter_controller = og.Controller(og.Controller.attribute("outputs:count", finish_counter))
tick_counter_controller = og.Controller(og.Controller.attribute("outputs:count", tick_counter))
tick_counter_3_controller = og.Controller(og.Controller.attribute("outputs:count", tick_counter_3))
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
await controller.evaluate(graph)
self.assertEqual(tick_counter_controller.get(), 1)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
self.assertEqual(tick_counter_controller.get(), 2)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
self.assertEqual(tick_counter_3_controller.get(), 3)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 1)
self.assertEqual(tick_counter_3_controller.get(), 3)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 1)
self.assertEqual(tick_counter_3_controller.get(), 3)
# ----------------------------------------------------------------------
async def test_latent_chain(self):
"""exercise a chain of latent nodes"""
# +---------+ +-------+ tick +-------+ tick +-------+
# |OnImpulse+-->TickA +-------->TickB +-------->|LatentC|
# +---------+ +-----+-+ +------++ +-------+-----+
# | finish | finish |
# finish | +-------------+ | +-------------+ +-v----------+
# +->TickCounterA | +-->| TickCounterB| |TickCounterC|
# +-------------+ +-------------+ +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.TickN"),
("TickB", "omni.graph.action.TickN"),
("LatentC", "omni.graph.action.TickN"),
("TickCounterA", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
("TickCounterC", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("TickA.outputs:tick", "TickB.inputs:execIn"),
("TickA.outputs:finished", "TickCounterA.inputs:execIn"),
("TickB.outputs:tick", "LatentC.inputs:execIn"),
("TickB.outputs:finished", "TickCounterB.inputs:execIn"),
("LatentC.outputs:finished", "TickCounterC.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("LatentC.inputs:duration", 2),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, _, _, _, tick_counter_a, tick_counter_b, tick_counter_c) = nodes
for _ in range(16):
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_a)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_b)), 2)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_c)), 4)
# ----------------------------------------------------------------------
async def test_latent_and_push(self):
"""exercise latent nodes in combination with stateful loop node"""
#
# +---------+ +-------+ tick +--------+ loopBody +-------+ +------------+
# |OnImpulse+-->|TickA +----------->ForLoop1++--------->|TickB +-+->|TickCounterB|
# +---------+ +----+--+ +--------++ +-------+ | +------------+
# | finish | |
# | | |
# | +--------------+ +v----------------+ +-v------------+
# +----->|FinishCounterA| |FinishLoopCounter| |FinishCounterB|
# +--------------+ +-----------------+ +--------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.TickN"),
("ForLoop1", "omni.graph.action.ForLoop"),
("TickB", "omni.graph.action.TickN"),
("FinishLoopCounter", "omni.graph.action.Counter"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("TickA.outputs:tick", "ForLoop1.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("ForLoop1.outputs:loopBody", "TickB.inputs:execIn"),
("ForLoop1.outputs:finished", "FinishLoopCounter.inputs:execIn"),
("TickB.outputs:tick", "TickCounterB.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
],
keys.SET_VALUES: [
("ForLoop1.inputs:start", 0),
("ForLoop1.inputs:stop", 3),
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("OnImpulse.state:enableImpulse", True),
("OnImpulse.inputs:onlyPlayback", False),
],
},
)
(_, _, _, _, finish_loop_counter, finish_counter_a, finish_counter_b, tick_counter_b) = nodes
for _ in range(20):
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_counter_a)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_b)), 12)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_counter_b)), 6)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_loop_counter)), 2)
# ----------------------------------------------------------------------
async def test_latent_fan_out(self):
"""Test latent nodes when part of parallel evaluation"""
# +------------+
# +---->|TickCounterA|
# | +------------+
# |
# +--------++ +----------+
# +-> TickA +--->|FinishedA |
# | +---------+ +----------+
# +---------+ +-----------+ |
# |OnImpulse+-->|TickCounter+-+
# +---------+ +-----------+ |
# | +---------+ +----------+
# +>| TickB +--->|FinishedB |
# +--------++ +----------+
# |
# | +------------+
# +---->|TickCounterB|
# +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.TickN"),
("TickB", "omni.graph.action.TickN"),
("TickCounter", "omni.graph.action.Counter"),
("TickCounterA", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickA.inputs:execIn"),
("TickCounter.outputs:execOut", "TickB.inputs:execIn"),
("TickA.outputs:tick", "TickCounterA.inputs:execIn"),
("TickB.outputs:tick", "TickCounterB.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, _, _, tick_counter, tick_counter_a, tick_counter_b, finish_counter_a, finish_counter_b) = nodes
def check_counts(c, a, b, f_a, f_b):
for node, expected in (
(tick_counter, c),
(tick_counter_a, a),
(tick_counter_b, b),
(finish_counter_a, f_a),
(finish_counter_b, f_b),
):
count = og.Controller.get(controller.attribute("outputs:count", node))
self.assertEqual(count, expected, node.get_prim_path())
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 0)
await controller.evaluate(graph)
check_counts(1, 1, 1, 0, 0)
await controller.evaluate(graph)
check_counts(1, 2, 2, 0, 0)
await controller.evaluate(graph)
check_counts(1, 2, 2, 1, 1)
# ----------------------------------------------------------------------
async def test_diamond_fan(self):
"""Test latent nodes in parallel fan-out which fan-in to a downstream node"""
# +--------++ +----------+
# +--> TickA +--->|FinishedA |---+
# | +---------+ +----------+ |
# +---------+ +-----------+ | | +------------+
# |OnImpulse+-->|TickCounter+-+ +-->|MergeCounter|
# +---------+ +-----------+ | | +------------+
# | +---------+ +----------+ |
# +-->| TickB +--->|FinishedB |--+
# +--------++ +----------+
# | +---------+
# +-->| TickC |
# +--------++
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickCounter", "omni.graph.action.Counter"),
("TickA", "omni.graph.action.TickN"),
("TickB", "omni.graph.action.TickN"),
("TickC", "omni.graph.action.TickN"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
("MergeCounter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickA.inputs:execIn"),
("TickCounter.outputs:execOut", "TickB.inputs:execIn"),
("TickCounter.outputs:execOut", "TickC.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
("FinishCounterA.outputs:execOut", "MergeCounter.inputs:execIn"),
("FinishCounterB.outputs:execOut", "MergeCounter.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 1),
("TickB.inputs:duration", 1),
("TickC.inputs:duration", 1),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, tick_counter, _, _, tick_c, finish_counter_a, finish_counter_b, merge_counter) = nodes
def check_counts(tc, f_a, f_b, mc, tick_c_count):
for node, expected in (
(tick_counter, tc),
(finish_counter_a, f_a),
(finish_counter_b, f_b),
(merge_counter, mc),
):
count = og.Controller.get(controller.attribute("outputs:count", node))
self.assertEqual(count, expected, node.get_prim_path())
self.assertEqual(tick_c.get_compute_count(), tick_c_count)
self.assertEqual(tick_c.get_compute_count(), 0)
# set up latent tickers
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 1)
# latent ticks
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 2)
# both branches complete
await controller.evaluate(graph)
check_counts(1, 1, 1, 2, 3)
# no count changes + no additional computes of tickC
await controller.evaluate(graph)
check_counts(1, 1, 1, 2, 3)
# ----------------------------------------------------------------------
async def test_diamond_latent_fan(self):
"""Test latent nodes in parallel fan-out which fan-in to a latent downstream node"""
# +--------++
# +--> TickA +--+
# | +---------+ |
# +---------+ | | +-------+ +-------+
# |OnImpulse+-->+ +-->|TickD +-+--->|CountF |
# +---------+ | | +-------+ | +-------+
# | +--------+ | +--->+-------+
# +-->| TickB +--+ |TickE |
# | +--------+ +--->+-------+
# | +--------+ |
# +-->| TickC +----------------+
# +--------+
# Note that when TickA triggers TickD into latent state, then TickB hits TickD subsequently. This subsequent
# evaluation is _transient_. Meaning that TickB will not block on a new copy of TickD.
# This is because there is only one TickD so there can be only one state (latent or not).
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.TickN"),
("TickB", "omni.graph.action.TickN"),
("TickC", "omni.graph.action.TickN"),
("TickD", "omni.graph.action.TickN"),
("TickE", "omni.graph.action.TickN"),
("CountF", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("OnImpulse.outputs:execOut", "TickB.inputs:execIn"),
("OnImpulse.outputs:execOut", "TickC.inputs:execIn"),
("TickA.outputs:finished", "TickD.inputs:execIn"),
("TickB.outputs:finished", "TickD.inputs:execIn"),
("TickC.outputs:finished", "TickE.inputs:execIn"),
("TickD.outputs:finished", "TickE.inputs:execIn"),
("TickD.outputs:finished", "CountF.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 1),
("TickB.inputs:duration", 1),
("TickC.inputs:duration", 2),
("TickD.inputs:duration", 1),
("TickE.inputs:duration", 1),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, tick_a, tick_b, tick_c, tick_d, tick_e, count_f) = nodes
def check_counts(i, ta, tb, tc, td, te):
# print(f"{[node.get_compute_count() for node, expected in ((tick_a, ta), (tick_b, tb), (tick_c, tc), (tick_d, td), (tick_e, te))]}")
for node, expected in ((tick_a, ta), (tick_b, tb), (tick_c, tc), (tick_d, td), (tick_e, te)):
self.assertEqual(node.get_compute_count(), expected, f"Check {i} for {node.get_prim_path()}")
# A, B, C, D, E
compute_counts = [
(1, 1, 1, 0, 0), # 0. fan out to trigger A, B, C into latent state
(2, 2, 2, 0, 0), # 1. A, B, C tick
(3, 3, 3, 2, 0), # 2. A, B end latent, D into latent via A or B, D ticks via A or B, C ticks
(3, 3, 4, 3, 2), # 3.
(3, 3, 4, 3, 3), # 4.
(3, 3, 4, 3, 3), # 5.
(3, 3, 4, 3, 3), # 6.
]
for i, cc in enumerate(compute_counts):
await controller.evaluate(graph)
check_counts(i, *cc)
# Verify that CountF has computed 1x due to the fan-in at TickD NOT acting like separate threads
self.assertEqual(count_f.get_compute_count(), 1)
async def test_om_63924(self):
"""Test OM-63924 bug is fixed"""
# The problem here was that if there was fan in to a node which was
# computed once and then totally unwound before the other history was
# processed, there would never be a deferred activation and so the 2nd
# compute would never happen. Instead we want to only unwind one history
# at a time to ensure each one is fully evaluated.
i = 2
class OnForEachEventPy:
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
nonlocal i
go = node.get_attribute("inputs:go")
go_val = og.Controller.get(go)
if not go_val:
return True
if i > 0:
og.Controller.set(
node.get_attribute("outputs:execOut"), og.ExecutionAttributeState.ENABLED_AND_PUSH
)
og.Controller.set(node.get_attribute("outputs:syncValue"), i)
i -= 1
return True
@staticmethod
def get_node_type() -> str:
return "omni.graph.test.OnForEachEventPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
node_type.add_input(
"inputs:go",
"bool",
False,
)
node_type.add_output("outputs:execOut", "execution", True)
node_type.add_output("outputs:syncValue", "uint64", True)
return True
og.register_node_type(OnForEachEventPy, 1)
class NoOpPy:
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
og.Controller.set(node.get_attribute("outputs:execOut"), og.ExecutionAttributeState.ENABLED)
return True
@staticmethod
def get_node_type() -> str:
return "omni.graph.test.NoOpPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
node_type.add_input(
"inputs:execIn",
"execution",
True,
)
node_type.add_output("outputs:execOut", "execution", True)
return True
og.register_node_type(NoOpPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (for_each, _, _, _, _, no_op_2), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("PostProcessDispatcher", "omni.graph.test.OnForEachEventPy"),
("TSA1", "omni.graph.action.SyncGate"),
("TSA0", "omni.graph.action.SyncGate"),
("TestSyncAccum", "omni.graph.action.SyncGate"),
("TestPrimBbox", "omni.graph.test.NoOpPy"),
("NoOpPy2", "omni.graph.test.NoOpPy"),
],
keys.CONNECT: [
("PostProcessDispatcher.outputs:execOut", "TSA0.inputs:execIn"),
("PostProcessDispatcher.outputs:execOut", "TSA1.inputs:execIn"),
("TSA1.outputs:execOut", "TestSyncAccum.inputs:execIn"),
("TSA0.outputs:execOut", "TestPrimBbox.inputs:execIn"),
("TestPrimBbox.outputs:execOut", "TestSyncAccum.inputs:execIn"),
("TestSyncAccum.outputs:execOut", "NoOpPy2.inputs:execIn"),
("PostProcessDispatcher.outputs:syncValue", "TSA1.inputs:syncValue"),
("PostProcessDispatcher.outputs:syncValue", "TSA0.inputs:syncValue"),
("PostProcessDispatcher.outputs:syncValue", "TestSyncAccum.inputs:syncValue"),
],
},
)
og.Controller.set(controller.attribute("inputs:go", for_each), True)
await controller.evaluate(graph)
# Verify the final sync gate triggered due to being computed 2x
exec_out = og.Controller.get(controller.attribute("outputs:execOut", no_op_2))
self.assertEqual(exec_out, og.ExecutionAttributeState.ENABLED)
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/data/load_with_type_resol.usda | #usda 1.0
(
customLayerData = {
dictionary cameraSettings = {
dictionary Front = {
double3 position = (0, 0, 50000)
double radius = 500
}
dictionary Perspective = {
double3 position = (500, 500, 500)
double3 target = (-0.00000397803842133726, 0.000007956076785831101, -0.00000397803842133726)
}
dictionary Right = {
double3 position = (-50000, 0, 0)
double radius = 500
}
dictionary Top = {
double3 position = (0, 50000, 0)
double radius = 500
}
string boundCamera = "/OmniverseKit_Persp"
}
dictionary omni_layer = {
string authoring_layer = "./load_with_type_resol.usda"
dictionary muteness = {
}
}
dictionary renderSettings = {
float3 "rtx:debugView:pixelDebug:textColor" = (0, 1e18, 0)
float3 "rtx:fog:fogColor" = (0.75, 0.75, 0.75)
float3 "rtx:post:backgroundZeroAlpha:backgroundDefaultColor" = (0, 0, 0)
float3 "rtx:post:colorcorr:contrast" = (1, 1, 1)
float3 "rtx:post:colorcorr:gain" = (1, 1, 1)
float3 "rtx:post:colorcorr:gamma" = (1, 1, 1)
float3 "rtx:post:colorcorr:offset" = (0, 0, 0)
float3 "rtx:post:colorcorr:saturation" = (1, 1, 1)
float3 "rtx:post:colorgrad:blackpoint" = (0, 0, 0)
float3 "rtx:post:colorgrad:contrast" = (1, 1, 1)
float3 "rtx:post:colorgrad:gain" = (1, 1, 1)
float3 "rtx:post:colorgrad:gamma" = (1, 1, 1)
float3 "rtx:post:colorgrad:lift" = (0, 0, 0)
float3 "rtx:post:colorgrad:multiply" = (1, 1, 1)
float3 "rtx:post:colorgrad:offset" = (0, 0, 0)
float3 "rtx:post:colorgrad:whitepoint" = (1, 1, 1)
float3 "rtx:post:lensDistortion:lensFocalLengthArray" = (10, 30, 50)
float3 "rtx:post:lensFlares:anisoFlareFalloffX" = (450, 475, 500)
float3 "rtx:post:lensFlares:anisoFlareFalloffY" = (10, 10, 10)
float3 "rtx:post:lensFlares:cutoffPoint" = (2, 2, 2)
float3 "rtx:post:lensFlares:haloFlareFalloff" = (10, 10, 10)
float3 "rtx:post:lensFlares:haloFlareRadius" = (75, 75, 75)
float3 "rtx:post:lensFlares:isotropicFlareFalloff" = (50, 50, 50)
float3 "rtx:post:tonemap:whitepoint" = (1, 1, 1)
float3 "rtx:raytracing:inscattering:singleScatteringAlbedo" = (0.9, 0.9, 0.9)
float3 "rtx:raytracing:inscattering:transmittanceColor" = (0.5, 0.5, 0.5)
float3 "rtx:sceneDb:ambientLightColor" = (0.1, 0.1, 0.1)
}
}
defaultPrim = "World"
endTimeCode = 100
metersPerUnit = 0.01
startTimeCode = 0
timeCodesPerSecond = 30
upAxis = "Y"
)
def Xform "World"
{
def OmniGraph "ActionGraph"
{
token evaluationMode = "Automatic"
token evaluator:type = "execution"
token fabricCacheBacking = "Shared"
int2 fileFormatVersion = (1, 6)
custom token[] graph:variable:Prims (
customData = {
token scope = "private"
}
displayName = "Prims"
)
custom float3[] graph:variable:Result (
customData = {
token scope = "private"
}
displayName = "Result"
)
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "for_each_loop" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom token inputs:arrayIn
prepend token inputs:arrayIn.connect = </World/ActionGraph/read_variable_prims.outputs:value>
custom uint inputs:execIn
prepend uint inputs:execIn.connect = </World/ActionGraph/write_variable_prims.outputs:execOut>
token node:type = "omni.graph.action.ForEach"
int node:typeVersion = 1
custom int outputs:arrayIndex
custom token outputs:element
custom uint outputs:finished (
customData = {
bool isExecution = 1
}
)
custom uint outputs:loopBody (
customData = {
bool isExecution = 1
}
)
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (1196.8728, 393.20004)
}
def OmniGraphNode "read_prim_attribute" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom token inputs:name = "extent"
custom rel inputs:prim
custom token inputs:primPath
prepend token inputs:primPath.connect = </World/ActionGraph/for_each_loop.outputs:element>
custom timecode inputs:usdTimecode = nan
custom bool inputs:usePath = 1
token node:type = "omni.graph.nodes.ReadPrimAttribute"
int node:typeVersion = 2
custom token outputs:value
custom bool state:correctlySetup = 0
custom uint64 state:srcAttrib
custom uint64 state:srcPath
custom uint64 state:srcPathToken
custom double state:time
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (1411.2406, 506.13638)
}
def OmniGraphNode "make_array" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom int inputs:arraySize = 1
custom token inputs:arrayType = "auto" (
allowedTokens = ["auto", "bool[]", "double[]", "float[]", "half[]", "int[]", "int64[]", "token[]", "uchar[]", "uint[]", "uint64[]", "double[2][]", "double[3][]", "double[4][]", "matrixd[3][]", "matrixd[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]", "int[2][]", "int[3][]", "int[4][]"]
)
custom token inputs:input0
delete token inputs:input0.connect = </World/ActionGraph/constant_token.inputs:value>
prepend token inputs:input0.connect = </World/ActionGraph/constant_token.inputs:value>
token node:type = "omni.graph.nodes.ConstructArray"
int node:typeVersion = 1
custom token outputs:array
uniform token ui:nodegraph:node:expansionState = "minimized"
uniform float2 ui:nodegraph:node:pos = (740.5124, 444.31375)
}
def OmniGraphNode "constant_token" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom token inputs:value = "/World/Cube"
token node:type = "omni.graph.nodes.ConstantToken"
int node:typeVersion = 1
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (500.63202, 450.1503)
}
def OmniGraphNode "on_tick" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom uint inputs:framePeriod = 0
custom bool inputs:onlyPlayback = 0
token node:type = "omni.graph.action.OnTick"
int node:typeVersion = 1
custom double outputs:absoluteSimTime
custom double outputs:deltaSeconds
custom double outputs:frame
custom bool outputs:isPlaying
custom uint outputs:tick (
customData = {
bool isExecution = 1
}
)
custom double outputs:time
custom double outputs:timeSinceStart
custom double state:accumulatedSeconds = 0
custom uint state:frameCount = 0
uniform token ui:nodegraph:node:expansionState = "minimized"
uniform float2 ui:nodegraph:node:pos = (694.81226, 319.50287)
}
def OmniGraphNode "write_variable_prims" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom uint inputs:execIn
prepend uint inputs:execIn.connect = </World/ActionGraph/on_tick.outputs:tick>
custom rel inputs:graph = </World/ActionGraph>
custom token inputs:targetPath
custom token inputs:value (
customData = {
dictionary omni = {
dictionary graph = {
token[] attrValue = []
string resolvedType = "token[]"
}
}
}
)
prepend token inputs:value.connect = </World/ActionGraph/make_array.outputs:array>
custom token inputs:variableName = "Prims"
token node:type = "omni.graph.core.WriteVariable"
int node:typeVersion = 1
custom uint outputs:execOut (
customData = {
bool isExecution = 1
}
)
custom token outputs:value
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (982.9669, 353.47394)
}
def OmniGraphNode "read_variable_prims" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom rel inputs:graph = </World/ActionGraph>
custom token inputs:targetPath
custom token inputs:variableName = "Prims"
token node:type = "omni.graph.core.ReadVariable"
int node:typeVersion = 1
custom token outputs:value
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (1110.3953, 538.19904)
}
def OmniGraphNode "write_variable_result" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom uint inputs:execIn
prepend uint inputs:execIn.connect = </World/ActionGraph/for_each_loop.outputs:loopBody>
custom rel inputs:graph = </World/ActionGraph>
custom token inputs:targetPath
custom token inputs:value
prepend token inputs:value.connect = </World/ActionGraph/read_prim_attribute.outputs:value>
custom token inputs:variableName = "Result"
token node:type = "omni.graph.core.WriteVariable"
int node:typeVersion = 1
custom uint outputs:execOut (
customData = {
bool isExecution = 1
}
)
custom token outputs:value
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (1634.9531, 392.43527)
}
}
def Mesh "Cube"
{
float3[] extent = [(-50, -50, -50), (50, 50, 50)]
int[] faceVertexCounts = [4, 4, 4, 4, 4, 4]
int[] faceVertexIndices = [0, 1, 3, 2, 4, 6, 7, 5, 4, 5, 1, 0, 6, 2, 3, 7, 4, 0, 2, 6, 5, 7, 3, 1]
normal3f[] normals = [(0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (1, 0, 0), (1, 0, 0), (1, 0, 0), (1, 0, 0)] (
interpolation = "faceVarying"
)
point3f[] points = [(-50, -50, 50), (50, -50, 50), (-50, 50, 50), (50, 50, 50), (-50, -50, -50), (50, -50, -50), (-50, 50, -50), (50, 50, -50)]
float2[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 1), (1, 0), (0, 0), (0, 1), (1, 1), (0, 0), (0, 1), (1, 1), (1, 0), (0, 0), (0, 1), (1, 1), (1, 0), (0, 0), (1, 0), (1, 1), (0, 1), (1, 0), (0, 0), (0, 1), (1, 1)] (
interpolation = "faceVarying"
)
uniform token subdivisionScheme = "none"
double3 xformOp:rotateXYZ = (0, 0, 0)
double3 xformOp:scale = (1, 1, 1)
double3 xformOp:translate = (0, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
}
}
def Xform "Environment"
{
double3 xformOp:rotateXYZ = (0, 0, 0)
double3 xformOp:scale = (1, 1, 1)
double3 xformOp:translate = (0, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
def DistantLight "defaultLight" (
prepend apiSchemas = ["ShapingAPI"]
)
{
float inputs:angle = 1
float inputs:intensity = 3000
float inputs:shaping:cone:angle = 180
float inputs:shaping:cone:softness
float inputs:shaping:focus
color3f inputs:shaping:focusTint
asset inputs:shaping:ies:file
double3 xformOp:rotateXYZ = (315, 0, 0)
double3 xformOp:scale = (1, 1, 1)
double3 xformOp:translate = (0, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/data/TestActionFanIn.usda | #usda 1.0
(
customLayerData = {
dictionary cameraSettings = {
dictionary Front = {
double3 position = (0, 0, 50000)
double radius = 500
}
dictionary Perspective = {
double3 position = (500, 500, 500)
double3 target = (-0.00000397803842133726, 0.000007956076785831101, -0.00000397803842133726)
}
dictionary Right = {
double3 position = (-50000, 0, 0)
double radius = 500
}
dictionary Top = {
double3 position = (0, 50000, 0)
double radius = 500
}
string boundCamera = "/OmniverseKit_Persp"
}
}
defaultPrim = "World"
endTimeCode = 100
metersPerUnit = 0.01
startTimeCode = 0
timeCodesPerSecond = 24
upAxis = "Y"
)
def Xform "World"
{
def OmniGraph "ActionGraph"
{
token evaluationMode = "Automatic"
token evaluator:type = "execution"
token fabricCacheBacking = "Shared"
int2 fileFormatVersion = (1, 4)
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "on_keyboard_input" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom bool inputs:altIn = 0
custom bool inputs:ctrlIn = 0
custom token inputs:keyIn = "A" (
allowedTokens = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Apostrophe", "Backslash", "Backspace", "CapsLock", "Comma", "Del", "Down", "End", "Enter", "Equal", "Escape", "F1", "F10", "F11", "F12", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "GraveAccent", "Home", "Insert", "Key0", "Key1", "Key2", "Key3", "Key4", "Key5", "Key6", "Key7", "Key8", "Key9", "Left", "LeftAlt", "LeftBracket", "LeftControl", "LeftShift", "LeftSuper", "Menu", "Minus", "NumLock", "Numpad0", "Numpad1", "Numpad2", "Numpad3", "Numpad4", "Numpad5", "Numpad6", "Numpad7", "Numpad8", "Numpad9", "NumpadAdd", "NumpadDel", "NumpadDivide", "NumpadEnter", "NumpadEqual", "NumpadMultiply", "NumpadSubtract", "PageDown", "PageUp", "Pause", "Period", "PrintScreen", "Right", "RightAlt", "RightBracket", "RightControl", "RightShift", "RightSuper", "ScrollLock", "Semicolon", "Slash", "Space", "Tab", "Up"]
)
custom bool inputs:onlyPlayback = 0
custom bool inputs:shiftIn = 0
token node:type = "omni.graph.action.OnKeyboardInput"
int node:typeVersion = 3
custom bool outputs:isPressed
custom token outputs:keyOut
custom uint outputs:pressed (
customData = {
bool isExecution = 1
}
)
custom uint outputs:released (
customData = {
bool isExecution = 1
}
)
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (-28.32303, 30.558456)
}
def OmniGraphNode "for_loop" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom uint inputs:breakLoop
custom uint inputs:execIn
prepend uint inputs:execIn.connect = [
</World/ActionGraph/on_keyboard_input.outputs:pressed>,
</World/ActionGraph/on_impulse_event.outputs:execOut>,
]
custom int inputs:start = 0
custom int inputs:step = 1
custom int inputs:stop = 2
token node:type = "omni.graph.action.ForLoop"
int node:typeVersion = 1
custom uint outputs:finished (
customData = {
bool isExecution = 1
}
)
custom int outputs:index
custom uint outputs:loopBody (
customData = {
bool isExecution = 1
}
)
custom int outputs:value
custom int state:i = -1
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (310, 94)
}
def OmniGraphNode "counter" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom uint inputs:execIn
prepend uint inputs:execIn.connect = </World/ActionGraph/for_loop.outputs:loopBody>
custom token inputs:logLevel = "Info" (
allowedTokens = ["Info", "Warning", "Error"]
)
custom uint inputs:reset
token node:type = "omni.graph.action.Counter"
int node:typeVersion = 1
custom int outputs:count
custom uint outputs:execOut (
customData = {
bool isExecution = 1
}
)
custom int state:count
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (664.4135, -53.116158)
}
def OmniGraphNode "counter_01" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom uint inputs:execIn
prepend uint inputs:execIn.connect = </World/ActionGraph/for_loop.outputs:loopBody>
custom token inputs:logLevel = "Info" (
allowedTokens = ["Info", "Warning", "Error"]
)
custom uint inputs:reset
token node:type = "omni.graph.action.Counter"
int node:typeVersion = 1
custom int outputs:count
custom uint outputs:execOut (
customData = {
bool isExecution = 1
}
)
custom int state:count
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (660.609, 374.31915)
}
def OmniGraphNode "counter_02" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom uint inputs:execIn
prepend uint inputs:execIn.connect = </World/ActionGraph/sync_gate.outputs:execOut>
custom token inputs:logLevel = "Info" (
allowedTokens = ["Info", "Warning", "Error"]
)
custom uint inputs:reset
token node:type = "omni.graph.action.Counter"
int node:typeVersion = 1
custom int outputs:count
custom uint outputs:execOut (
customData = {
bool isExecution = 1
}
)
custom int state:count
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (1403.963, 203.39139)
}
def OmniGraphNode "on_impulse_event" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom bool inputs:onlyPlayback = 0
token node:type = "omni.graph.action.OnImpulseEvent"
int node:typeVersion = 2
custom uint outputs:execOut (
customData = {
bool isExecution = 1
}
)
custom bool state:enableImpulse
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (10.181118, -137.32922)
}
def OmniGraphNode "sync_gate" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom uint inputs:execIn
prepend uint inputs:execIn.connect = [
</World/ActionGraph/counter.outputs:execOut>,
</World/ActionGraph/counter_01.outputs:execOut>,
]
custom uint64 inputs:syncValue = 0
prepend uint64 inputs:syncValue.connect = </World/ActionGraph/to_uint64.outputs:converted>
token node:type = "omni.graph.action.SyncGate"
int node:typeVersion = 1
custom uint outputs:execOut (
customData = {
bool isExecution = 1
}
)
custom uint64 outputs:syncValue
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (1065.7456, 144.79875)
}
def OmniGraphNode "to_uint64" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom token inputs:value
prepend token inputs:value.connect = </World/ActionGraph/for_loop.outputs:index>
token node:type = "omni.graph.nodes.ToUint64"
int node:typeVersion = 1
custom token outputs:converted
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (734.48773, 203.07834)
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/data/TestOnStageEventNode_v2.usda | #usda 1.0
(
customLayerData = {
dictionary cameraSettings = {
dictionary Front = {
double3 position = (0, 0, 50000)
double radius = 500
}
dictionary Perspective = {
double3 position = (500, 500, 500)
double3 target = (-0.00000397803842133726, 0.000007956076785831101, -0.000003978038307650422)
}
dictionary Right = {
double3 position = (-50000, 0, 0)
double radius = 500
}
dictionary Top = {
double3 position = (0, 50000, 0)
double radius = 500
}
string boundCamera = "/OmniverseKit_Persp"
}
dictionary omni_layer = {
dictionary muteness = {
}
}
dictionary renderSettings = {
float3 "rtx:debugView:pixelDebug:textColor" = (0, 1e18, 0)
float3 "rtx:fog:fogColor" = (0.75, 0.75, 0.75)
float3 "rtx:post:backgroundZeroAlpha:backgroundDefaultColor" = (0, 0, 0)
float3 "rtx:post:colorcorr:contrast" = (1, 1, 1)
float3 "rtx:post:colorcorr:gain" = (1, 1, 1)
float3 "rtx:post:colorcorr:gamma" = (1, 1, 1)
float3 "rtx:post:colorcorr:offset" = (0, 0, 0)
float3 "rtx:post:colorcorr:saturation" = (1, 1, 1)
float3 "rtx:post:colorgrad:blackpoint" = (0, 0, 0)
float3 "rtx:post:colorgrad:contrast" = (1, 1, 1)
float3 "rtx:post:colorgrad:gain" = (1, 1, 1)
float3 "rtx:post:colorgrad:gamma" = (1, 1, 1)
float3 "rtx:post:colorgrad:lift" = (0, 0, 0)
float3 "rtx:post:colorgrad:multiply" = (1, 1, 1)
float3 "rtx:post:colorgrad:offset" = (0, 0, 0)
float3 "rtx:post:colorgrad:whitepoint" = (1, 1, 1)
float3 "rtx:post:lensDistortion:lensFocalLengthArray" = (10, 30, 50)
float3 "rtx:post:lensFlares:anisoFlareFalloffX" = (450, 475, 500)
float3 "rtx:post:lensFlares:anisoFlareFalloffY" = (10, 10, 10)
float3 "rtx:post:lensFlares:cutoffPoint" = (2, 2, 2)
float3 "rtx:post:lensFlares:haloFlareFalloff" = (10, 10, 10)
float3 "rtx:post:lensFlares:haloFlareRadius" = (75, 75, 75)
float3 "rtx:post:lensFlares:isotropicFlareFalloff" = (50, 50, 50)
float3 "rtx:post:tonemap:whitepoint" = (1, 1, 1)
float3 "rtx:raytracing:inscattering:singleScatteringAlbedo" = (0.9, 0.9, 0.9)
float3 "rtx:raytracing:inscattering:transmittanceColor" = (0.5, 0.5, 0.5)
float3 "rtx:sceneDb:ambientLightColor" = (0.1, 0.1, 0.1)
}
}
defaultPrim = "World"
endTimeCode = 100
metersPerUnit = 0.01
startTimeCode = 0
timeCodesPerSecond = 24
upAxis = "Y"
)
def Xform "World"
{
def OmniGraph "ActionGraph"
{
token evaluationMode = "Automatic"
token evaluator:type = "execution"
token fabricCacheBacking = "Shared"
int2 fileFormatVersion = (1, 6)
token pipelineStage = "pipelineStageSimulation"
def OmniGraphNode "on_stage_event" (
prepend apiSchemas = ["NodeGraphNodeAPI"]
)
{
custom token inputs:eventName = "" (
allowedTokens = ["Saved", "Selection Changed", "OmniGraph Start Play", "OmniGraph Stop Play", "Simulation Start Play", "Simulation Stop Play", "Animation Start Play", "Animation Stop Play"]
)
custom bool inputs:onlyPlayback = 1
token node:type = "omni.graph.action.OnStageEvent"
int node:typeVersion = 2
custom uint outputs:execOut (
customData = {
bool isExecution = 1
}
)
uniform token ui:nodegraph:node:expansionState = "open"
uniform float2 ui:nodegraph:node:pos = (314, 47)
}
}
}
|
omniverse-code/kit/exts/omni.graph.action/docs/ui_nodes.md | (ogn_ui_nodes)=
# UI Nodes
You may have seen the `omni.ui` extension that gives you the ability to create user interface elements through Python scripting. OmniGraph provides some nodes that can be used to do the same thing through an action graph.
These nodes provide an interface to the equivalent `omni.ui` script elements. The attributes of the nodes match the parameters you would pass to the script.
| Node | omni.ui Equivalent |
| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| {ref}`Button<GENERATED - Documentation _ognomni.graph.ui.Button>` | {py:class}`omni.ui.Button` |
| {ref}`ComboBox<GENERATED - Documentation _ognomni.graph.ui.ComboBox>` | {py:class}`omni.ui.ComboBox` |
| {ref}`OnWidgetClicked<GENERATED - Documentation _ognomni.graph.ui.OnWidgetClicked>` | {py:class}`omni.ui.Widget.call_mouse_pressed_fn` |
| {ref}`OnWidgetValueChanged<GENERATED - Documentation _ognomni.graph.ui.OnWidgetValueChanged>` | {py:class}`omni.ui.Widget.add_value_changed_fn` |
| {ref}`Slider<GENERATED - Documentation _ognomni.graph.ui.Slider>` | {py:class}`omni.ui.IntSlider` {py:class}`omni.ui.FloatSlider` |
| {ref}`VStack<GENERATED - Documentation _ognomni.graph.ui.VStack>` | {py:class}`omni.ui.VStack` |
## How To Use Them
The UI nodes are meant to be triggered to exist temporarily, meaning you want to ensure that they are part of a graph that creates them only once and then destroys them once their utility has ended.
|
omniverse-code/kit/exts/omni.graph.action/docs/CHANGELOG.md | # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.31.1] - 2023-02-10
### Fixed
- Add tests for AG fan-out with shared dependencies
## [1.31.0] - 2022-09-01
### Added
- SwitchToken, OnLoaded
## [1.30.2] - 2022-08-30
### Fixed
- Linting errors
## [1.30.1] - 2022-08-09
### Fixed
- Applied formatting to all of the Python files
## [1.30.0] - 2022-07-29
### Changed
- Add prim input to OnObjectChanged node
## [1.29.0] - 2022-07-29
### Added
- Support for relative image urls in UI widget nodes
## [1.28.1] - 2022-07-28
### Fixed
- Spurious error messages about 'Node compute request is ignored because XXX is not request-driven'
## [1.28.0] - 2022-07-26
### Added
- Placer node.
- Added ReadWidgetProperty node
## [1.27.0] - 2022-07-26
### Changed
- Removed internal Placers from the widget nodes.
## [1.26.1] - 2022-07-25
### Fixed
- Various UI nodes were rejecting valid exec inputs like ENABLED_AND_PUSH
## [1.26.0] - 2022-07-22
### Added
- 'style' input attributes for Button, Spacer and Stack nodes.
### Fixed
- WriteWidgetStyle was failing on styles containing hex values (e.g. for colors)
## [1.25.0] - 2022-07-20
### Added
- WriteWidgetStyle node
## [1.24.1] - 2022-07-21
### Changed
- Undo revert
## [1.24.0] - 2022-07-18
### Added
- Spacer node
### Changed
- VStack node:
- Removed all execution inputs except for create.
- Added support for OgnWriteWidgetProperty.
- inputs:parentWidgetPath is no longer optional.
## [1.23.0] - 2022-07-18
### Changed
- Reverted changes in 1.21.1
## [1.22.0] - 2022-07-15
### Added
- WriteWidgetProperty node
### Changed
- Removed all of Button node's execution inputs except for Create
- Removed Button node's 'iconSize' input.
- Modified Button node to work with WriteWidgetProperty
## [1.21.1] - 2022-07-15
### Changed
- Added test node TickN, modified tests
## [1.21.0] - 2022-07-14
### Changed
- Added +/- icons to Multigate and Sequence
## [1.20.0] - 2022-07-07
### Added
- Test for public API consistency
## [1.19.0] - 2022-07-04
### Changed
- OgnButton requires a parentWidgetPath. It no longer defaults to the current viewport.
- Each OgnButton instance can create multiples buttons. They no longer destroy the previous ones.
- widgetIdentifiers are now unique within GraphContext
## [1.18.1] - 2022-06-20
### Changed
- Optimized MultiSequence
## [1.18.0] - 2022-05-30
### Added
- OnClosing
## [1.17.1] - 2022-05-23
### Changed
- Changed VStack ui name to Stack
## [1.17.0] - 2022-05-24
### Changed
- Converted ForEach node from Python to C++
- Removed OnWidgetDoubleClicked
## [1.16.1] - 2022-05-23
### Changed
- Converted Counter node from Python to C++
## [1.16.0] - 2022-05-21
### Added
- Removed OnGraphInitialize, added Once to replace
## [1.15.1] - 2022-05-20
### Changed
- Added direction input to VStack node to allow objects to stack in width, height & depth directions.
- Button node uses styles to select icons rather than mouse functions.
## [1.15.0] - 2022-05-19
### Added
- OnGraphInitialize - triggers when the graph is created
### Changed
- OnStageEvent - removed non-functional events
## [1.14.1] - 2022-05-19
### Fixed
- Fixed OgnOnWidgetValueChanged output type resolution
## [1.14.0] - 2022-05-17
### Changed
- Added '(BETA)' to the ui_names of the new UI nodes.
## [1.13.0] - 2022-05-16
### Added
- Added Sequence node with dynamic outputs named OgnMultisequence
## [1.12.0] - 2022-05-11
### Added
- Node definitions for UI creation and manipulation
- Documentation on how to use the new UI nodes
- Dependencies on extensions omni.ui_query and omni.kit.window.filepicker(optional)
## [1.11.3] - 2022-04-12
### Fixed
- OnCustomEvent when onlyPlayback=true
- Remove state attrib from PrintText
## [1.11.2] - 2022-04-08
### Added
- Added absoluteSimTime output attribute to the OnTick node
## [1.11.1] - 2022-03-16
### Fixed
- OnStageEvent Animation Stop event when only-on-playback is true
## [1.11.0] - 2022-03-10
### Added
- Removed _outputs::shiftOut_, _outputs::ctrlOut_, _outputs::altOut_ from _OnKeyboardInput_ node.
- Added _inputs::shiftIn_, _inputs::ctrlIn_, _inputs::altIn_ from _OnKeyboardInput_ node.
- Added support for key modifiers to _OnKeyboardInput_ node.
## [1.10.1] - 2022-03-09
### Changed
- Made all input attributes of all event source nodes literalOnly
## [1.10.0] - 2022-02-24
### Added
- added SyncGate node
## [1.9.1] - 2022-02-14
### Fixed
- add additional extension enabled check for omni.graph.ui not enabled error
## [1.9.0] - 2022-02-04
### Added
- added SetPrimRelationship node
## [1.8.0] - 2022-02-04
### Modified
- Several event nodes now have _inputs:onlyPlayback_ attributes to control when they are active. The default is enabled, which means these nodes will only operate what playback is active.
### Fixed
- Category for Counter
## [1.7.0] - 2022-01-27
### Added
- Added SetPrimActive node
## [1.6.0] - 2022-01-27
### Added
- Added OnMouseInput node
### Modified
- Changed OnGamepadInput to use SubscriptionToInputEvents instead
- Changed OnKeyboardInput to use SubscriptionToInputEvents instead
## [1.5.0] - 2022-01-25
### Added
- Added OnGamepadInput node
## [1.4.5] - 2022-01-24
### Fixed
- categories for several nodes
## [1.4.4] - 2022-01-14
### Added
- Added car customizer tutorial
## [1.4.2] - 2022-01-05
### Modified
- Categories added to all nodes
## [1.4.1] - 2021-12-20
### Modified
- _GetLookAtRotation_ moved to _omni.graph.nodes_
## [1.4.0] - 2021-12-10
### Modified
- _OnStageEvent_ handles new stage events
## [1.3.0] - 2021-11-22
### Modified
- _OnKeyboardInput_ to use allowedTokens for input key
- _OnStageEvent_ bugfix to avoid spurious error messages on shutdown
## [1.2.0] - 2021-11-10
### Modified
- _OnKeyboardInput_, _OnCustomEvent_ to use _INode::requestCompute()_
## [1.1.0] - 2021-11-04
### Modified
- _OnImpulseEvent_ to use _INode::requestCompute()_
## [1.0.0] - 2021-05-10
### Initial Version
|
omniverse-code/kit/exts/omni.graph.action/docs/README.md | # OmniGraph Action Graphs
## Introduction to Action Graphs
Provides visual-programming graphs to help designers bring their omniverse creations to life. Action Graphs are
triggered by events and can execute nodes which modify the stage.
## The Action Graph Extension
Contains nodes which work only with Action Graphs. Compute Nodes from other extensions can be used with Action Graphs;
for example omni.graph.nodes.
|
omniverse-code/kit/exts/omni.graph.action/docs/index.rst | .. _ogn_omni_graph_action:
OmniGraph Action Graph
######################
.. tabularcolumns:: |L|R|
.. csv-table::
:width: 100%
**Extension**: omni.graph.action,**Documentation Generated**: |today|
.. toctree::
:maxdepth: 1
CHANGELOG
This extension is a collection of functionality required for OmniGraph Action Graphs.
.. toctree::
:maxdepth: 2
:caption: Contents
Overview of Action Graphs<Overview>
Hands-on Introduction to Action Graphs<https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph/quickstart.html>
Action Graph Car Customizer Tutorial<https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph/car_customizer.html>
Building UI With Action Graph<ui_nodes>
For more comprehensive examples targeted at explaining the use of OmniGraph features in detail see
:ref:`ogn_user_guide`
.. note::
Action Graphs are in an early development state
|
omniverse-code/kit/exts/omni.graph.action/docs/Overview.md | (ogn_omni_graph_action_overview)=
```{csv-table}
**Extension**: omni.graph.action,**Documentation Generated**: {sub-ref}`today`
```
This extension is a collection of functionality required for OmniGraph Action Graphs.
```{note}
Action Graphs are in an early development state
```
# Action Graph Overview
For a hands-on introduction to OmniGraph Action Graphs see
[Action Graph Quickstart](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph/quickstart.html)
For more comprehensive and thorough documentation on various OmniGraph features see {ref}`ogn_user_guide`
Action Graphs are comprised of any number of separate chains of nodes, like deformer graphs. However there are important differences which make Action graphs more suited to particular applications.
## Event Sources
Action graphs are *event driven*, which means that each chain of nodes must start with an *Event Source* node. Each event source node can be thought of as an entry point of the graph.
*Event Source* nodes are named with an *On* prefix, never have an *execution* input attribute, and always have at least one output *execution* attribute.
| Event Source Nodes |
| ------------------------------------------------------------------------------------------ |
| {ref}`On Keyboard Input <GENERATED - Documentation _ognomni.graph.action.OnKeyboardInput>` |
| {ref}`On Tick <GENERATED - Documentation _ognomni.graph.action.OnTick>` |
| {ref}`On Playback Tick <GENERATED - Documentation _ognomni.graph.action.OnPlaybackTick>` |
| {ref}`On Impulse Event <GENERATED - Documentation _ognomni.graph.action.OnImpulseEvent>` |
| {ref}`On Object Change <GENERATED - Documentation _ognomni.graph.action.OnObjectChange>` |
| {ref}`On Custom Event <GENERATED - Documentation _ognomni.graph.action.OnCustomEvent>` |
## Execution Attributes
Action graphs make use of *execution*-type attributes.
The *execution* evaluator works by following *execution* connections downstream and computing nodes it encounters until there are no more downstream connections to follow. The entire chain is executed to completion. When there is no downstream node the execution terminates and the next node is popped off the *execution stack*
Note that if there is more than one downstream connection from an *execution* attribute, each path will be followed in an undetermined order. Multiple downstream chains can be executed in a fixed order either by chaining the end of one to the start of the other, or by using the {ref}`Sequence <GENERATED - Documentation _ognomni.graph.action.Sequence>` node.
The value of an *execution* attribute tells the evaluator what the next step should be in the chain. It can be one of:
| Value | Description
| ---------------- | ------------------------------------------------------------------------------------------- |
| DISABLED | Do not continue from this attribute. |
| ENABLED | Continue downstream from this attribute. |
| ENABLED_AND_PUSH | Save the current node on the *execution stack* and continue downstream from this attribute. |
| LATENT_PUSH | Save the current node as it performs some asynchronous operation |
| LATENT_FINISH | Finish the asynchronous operation and continue downstream from this attribute. |
# Flow Control
Many Action graphs will need to do different things depending on some state. In a python script you would use an *if* or *while* loop to accomplish this. Similarly in Action graph there are nodes which provide this branching functionality. Flow control nodes have more than one *execution* output attribute, which is used to branch the evaluation flow.
| Flow Control Nodes |
| --------------------------------------------------------------------------- |
| {ref}`Branch <GENERATED - Documentation _ognomni.graph.action.Branch>` |
| {ref}`ForEach <GENERATED - Documentation _ognomni.graph.action.ForEach>` |
| {ref}`For Loop <GENERATED - Documentation _ognomni.graph.action.ForLoop>` |
| {ref}`Flip Flop <GENERATED - Documentation _ognomni.graph.action.FlipFlop>` |
| {ref}`Gate <GENERATED - Documentation _ognomni.graph.action.Gate>` |
| {ref}`Sequence <GENERATED - Documentation _ognomni.graph.action.Sequence>` |
| {ref}`Delay <GENERATED - Documentation _ognomni.graph.action.Delay>` |
|
omniverse-code/kit/exts/omni.kit.renderer.cuda_interop/omni/kit/renderer/cuda_interop_test/__init__.py | from ._renderer_cuda_interop_test import *
# Cached interface instance pointer
def get_renderer_cuda_interop_test_interface() -> IRendererCudaInteropTest:
if not hasattr(get_renderer_cuda_interop_test_interface, "renderer_cuda_interop_test"):
get_renderer_cuda_interop_test_interface.renderer_cuda_interop_test = acquire_renderer_cuda_interop_test_interface()
return get_renderer_cuda_interop_test_interface.renderer_cuda_interop_test
|
omniverse-code/kit/exts/omni.kit.renderer.cuda_interop/omni/kit/renderer/cuda_interop/__init__.py | from ._renderer_cuda_interop import *
# Cached interface instance pointer
def get_renderer_cuda_interop_interface() -> IRendererCudaInterop:
"""Returns cached :class:`omni.kit.renderer.IRendererCudaInterop` interface"""
if not hasattr(get_renderer_cuda_interop_interface, "renderer_cuda_interop"):
get_renderer_cuda_interop_interface.renderer = acquire_renderer_cuda_interop_interface()
return get_renderer_cuda_interop_interface.renderer_cuda_interop
|
omniverse-code/kit/exts/omni.kit.renderer.cuda_interop/omni/kit/renderer/cuda_interop/_renderer_cuda_interop.pyi | """
This module contains bindings to C++ omni::kit::renderer::IRendererCudaInterop interface, core C++ part of Omniverse Kit.
>>> import omni.kit.renderer.cuda_interop
>>> e = omni.kit.renderer.cuda_interop.get_renderer_cuda_interop_interface()
"""
from __future__ import annotations
import omni.kit.renderer.cuda_interop._renderer_cuda_interop
import typing
__all__ = [
"IRendererCudaInterop",
"acquire_renderer_cuda_interop_interface",
"release_renderer_cuda_interop_interface"
]
class IRendererCudaInterop():
pass
def acquire_renderer_cuda_interop_interface(plugin_name: str = None, library_path: str = None) -> IRendererCudaInterop:
pass
def release_renderer_cuda_interop_interface(arg0: IRendererCudaInterop) -> None:
pass
|
omniverse-code/kit/exts/omni.kit.renderer.cuda_interop/omni/kit/renderer/cuda_interop/tests/__init__.py | from .test_renderer_cuda_interop import *
|
omniverse-code/kit/exts/omni.kit.renderer.cuda_interop/omni/kit/renderer/cuda_interop/tests/test_renderer_cuda_interop.py | import inspect
import pathlib
import carb
import carb.settings
import carb.tokens
import omni.kit.app
import omni.kit.test
import omni.kit.renderer.cuda_interop_test
class RendererCudaInteropTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.acquire_settings_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
self._renderer_cuda_interop_test = omni.kit.renderer.cuda_interop_test.acquire_renderer_cuda_interop_test_interface()
self._renderer.startup()
self._renderer_cuda_interop_test.startup()
def __test_name(self) -> str:
return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}"
async def tearDown(self):
self._renderer_cuda_interop_test.shutdown()
self._renderer.shutdown()
self._renderer_cuda_interop_test = None
self._renderer = None
self._app_window_factory = None
self._settings = None
async def test_1_render_cuda_interop_test(self):
app_window = self._app_window_factory.create_window_from_settings()
app_window.startup_with_desc(
title="Renderer test OS window",
width=16,
height=16,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._renderer.attach_app_window(app_window)
self._app_window_factory.set_default_window(app_window)
TEST_COLOR = (1, 2, 3, 255)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_cuda_interop_test.startup_resources_for_app_window(app_window)
self._renderer_cuda_interop_test.setup_simple_comparison_for_app_window(app_window, TEST_COLOR[0], TEST_COLOR[1], TEST_COLOR[2], TEST_COLOR[3])
test_name = self.__test_name()
for _ in range(3):
await omni.kit.app.get_app().next_update_async()
self._renderer_cuda_interop_test.shutdown_resources_for_app_window(app_window)
self._app_window_factory.set_default_window(None)
self._renderer.detach_app_window(app_window)
app_window.shutdown()
app_window = None
|
omniverse-code/kit/exts/omni.kit.window.audioplayer/PACKAGE-LICENSES/omni.kit.window.audioplayer-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. |
omniverse-code/kit/exts/omni.kit.window.audioplayer/config/extension.toml | [package]
title = "Kit Audio Player Window"
category = "Audio"
version = "1.0.1"
description = "A simple audio player window"
detailedDescription = """This adds a window for playing audio assets.
This also adds an option to the content browser to play audio assets in this
audio player.
"""
preview_image = "data/preview.png"
authors = ["NVIDIA"]
keywords = ["audio", "playback"]
[dependencies]
"omni.audioplayer" = {}
"omni.ui" = {}
"omni.kit.window.content_browser" = { optional=true }
"omni.kit.window.filepicker" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.kit.window.audioplayer"
[[test]]
unreliable = true
args = [
# Use the null device backend so we don't scare devs by playing audio.
"--/audio/deviceBackend=null",
# Needed for UI testing
"--/app/menu/legacy_mode=false",
]
dependencies = [
"omni.kit.mainwindow",
"omni.kit.ui_test",
]
stdoutFailPatterns.exclude = [
"*" # I don't want these but OmniUiTest forces me to use them
]
|
Subsets and Splits